3 <title>CodeMirror: OCaml mode</title>
5 <link rel=stylesheet href=../../lib/codemirror.css>
6 <link rel=stylesheet href=../../doc/docs.css>
9 .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
12 <script src=../../lib/codemirror.js></script>
13 <script src=../../addon/edit/matchbrackets.js></script>
14 <script src=ocaml.js></script>
16 <h1>CodeMirror: OCaml mode</h1>
19 (* Summing a list of integers *)
23 | x :: xs' -> x + sum xs'
26 let rec qsort = function
29 let is_less x = x < pivot in
30 let left, right = List.partition is_less rest in
31 qsort left @ [pivot] @ qsort right
33 (* Fibonacci Sequence *)
34 let rec fib_aux n a b =
37 | _ -> fib_aux (n - 1) (a + b) a
38 let fib n = fib_aux n 0 1
40 (* Birthday paradox *)
43 let rec birthday_paradox prob people =
44 let prob' = (year_size -. float people) /. year_size *. prob in
45 if prob' < 0.5 then
46 Printf.printf "answer = %d\n" (people+1)
48 birthday_paradox prob' (people+1) ;;
50 birthday_paradox 1.0 1
54 let succ n f x = f (n f x)
56 let two = succ (succ zero)
57 let add n1 n2 f x = n1 f (n2 f x)
58 let to_string n = n (fun k -> "S" ^ k) "0"
59 let _ = to_string (add (succ two) two)
61 (* Elementary functions *)
62 let square x = x * x;;
64 if x <= 1 then 1 else x * fact (x - 1);;
66 (* Automatic memory management *)
67 let l = 1 :: 2 :: 3 :: [];;
71 (* Polymorphism: sorting lists *)
72 let rec sort = function
74 | x :: l -> insert x (sort l)
76 and insert elem = function
79 if elem < x then elem :: x :: l else x :: insert elem l;;
81 (* Imperative features *)
82 let add_polynom p1 p2 =
83 let n1 = Array.length p1
84 and n2 = Array.length p2 in
85 let result = Array.create (max n1 n2) 0 in
86 for i = 0 to n1 - 1 do result.(i) <- p1.(i) done;
87 for i = 0 to n2 - 1 do result.(i) <- result.(i) + p2.(i) done;
89 add_polynom [| 1; 2 |] [| 1; 2; 3 |];;
91 (* We may redefine fact using a reference cell and a for loop *)
100 (* Triangle (graphics) *)
102 ignore( Glut.init Sys.argv );
103 Glut.initDisplayMode ~double_buffer:true ();
104 ignore (Glut.createWindow ~title:"OpenGL Demo");
105 let angle t = 10. *. t *. t in
107 GlClear.clear [ `color ];
108 GlMat.load_identity ();
109 GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. ();
110 GlDraw.begins `triangles;
111 List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.];
113 Glut.swapBuffers () in
114 GlMat.mode `modelview;
115 Glut.displayFunc ~cb:render;
116 Glut.idleFunc ~cb:(Some Glut.postRedisplay);
119 (* A Hundred Lines of Caml - http://caml.inria.fr/about/taste.en.html *)
120 (* OCaml page on Wikipedia - http://en.wikipedia.org/wiki/OCaml *)
124 var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
131 <p><strong>MIME types defined:</strong> <code>text/x-ocaml</code>.</p>