Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Niidae Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
OCaml
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Code examples== {{one source|date=January 2024}} Snippets of OCaml code are most easily studied by entering them into the ''top-level [[read–eval–print loop|REPL]]''. This is an interactive OCaml session that prints the inferred types of resulting or defined expressions.<ref>{{Cite web|title=OCaml - The toplevel system or REPL (ocaml)|url=https://ocaml.org/manual/toplevel.html|access-date=2021-05-17|website=ocaml.org}}</ref> The OCaml top-level is started by simply executing the OCaml program: <syntaxhighlight lang="console"> $ ocaml Objective Caml version 3.09.0 # </syntaxhighlight> Code can then be entered at the "#" prompt. For example, to calculate 1+2*3: <syntaxhighlight lang="console"> # 1 + 2 * 3;; - : int = 7 </syntaxhighlight> OCaml infers the type of the expression to be "int" (a [[Word (computer architecture)|machine-precision]] [[Integer (computer science)|integer]]) and gives the result "7". ===Hello World=== The following program "hello.ml": <syntaxhighlight lang="OCaml"> print_endline "Hello World!" </syntaxhighlight> can be compiled into a bytecode executable: $ ocamlc hello.ml -o hello or compiled into an optimized native-code executable: $ ocamlopt hello.ml -o hello and executed: <syntaxhighlight lang="console"> $ ./hello Hello World! $ </syntaxhighlight> The first argument to ocamlc, "hello.ml", specifies the source file to compile and the "-o hello" flag specifies the output file.<ref>{{Cite web|url=https://caml.inria.fr/pub/docs/manual-ocaml/comp.html|title = OCaml - Batch compilation (Ocamlc)}}</ref> === Option === The <code>option</code> type constructor in OCaml, similar to the <code>Maybe</code> type in [[Haskell]], augments a given data type to either return <code>Some</code> value of the given data type, or to return <code>None</code>.<ref>{{Cite web |title=3.7. Options — OCaml Programming: Correct + Efficient + Beautiful |url=https://cs3110.github.io/textbook/chapters/data/options.html |access-date=2022-10-07 |website=cs3110.github.io}}</ref> This is used to express that a value might or might not be present.<syntaxhighlight lang="ocaml"> # Some 42;; - : int option = Some 42 # None;; - : 'a option = None </syntaxhighlight>This is an example of a function that either extracts an int from an option, if there is one inside, and converts it into a [[String (computer science)|string]], or if not, returns an empty string:<syntaxhighlight lang="ocaml"> let extract o = match o with | Some i -> string_of_int i | None -> "";; </syntaxhighlight><syntaxhighlight lang="ocaml"> # extract (Some 42);; - : string = "42" # extract None;; - : string = "" </syntaxhighlight> ===Summing a list of integers=== Lists are one of the fundamental datatypes in OCaml. The following code example defines a [[Recursion (computer science)|recursive]] function ''sum'' that accepts one argument, ''integers'', which is supposed to be a list of integers. Note the keyword <code>rec</code> which denotes that the function is recursive. The function recursively iterates over the given list of integers and provides a sum of the elements. The ''match'' statement has similarities to [[C (programming language)|C]]'s [[Switch statement|switch]] element, though it is far more general. <syntaxhighlight lang="ocaml"> let rec sum integers = (* Keyword rec means 'recursive'. *) match integers with | [] -> 0 (* Yield 0 if integers is the empty list []. *) | first :: rest -> first + sum rest;; (* Recursive call if integers is a non- empty list; first is the first element of the list, and rest is a list of the rest of the elements, possibly []. *) </syntaxhighlight> <syntaxhighlight lang="OCaml"> # sum [1;2;3;4;5];; - : int = 15 </syntaxhighlight> Another way is to use standard [[fold function]] that works with lists. <syntaxhighlight lang="ocaml"> let sum integers = List.fold_left (fun accumulator x -> accumulator + x) 0 integers;; </syntaxhighlight> <syntaxhighlight lang="OCaml"> # sum [1;2;3;4;5];; - : int = 15 </syntaxhighlight> Since the [[anonymous function]] is simply the application of the + operator, this can be shortened to: <syntaxhighlight lang="ocaml"> let sum integers = List.fold_left (+) 0 integers </syntaxhighlight> Furthermore, one can omit the list argument by making use of a [[partial application]]: <syntaxhighlight lang="OCaml"> let sum = List.fold_left (+) 0 </syntaxhighlight> ===Quicksort=== OCaml lends itself to concisely expressing recursive algorithms. The following code example implements an algorithm similar to [[quicksort]] that sorts a list in increasing order. <syntaxhighlight lang="OCaml"> let rec qsort = function | [] -> [] | pivot :: rest -> let is_less x = x < pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort right </syntaxhighlight> Or using partial application of the >= operator. <syntaxhighlight lang="OCaml"> let rec qsort = function | [] -> [] | pivot :: rest -> let is_less = (>=) pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort right </syntaxhighlight> ===Birthday problem=== The following program calculates the smallest number of people in a room for whom the probability of completely unique birthdays is less than 50% (the [[birthday problem]], where for 1 person the probability is 365/365 (or 100%), for 2 it is 364/365, for 3 it is 364/365 × 363/365, etc.) (answer = 23). <syntaxhighlight lang="OCaml"> let year_size = 365. let rec birthday_paradox prob people = let prob = (year_size -. float people) /. year_size *. prob in if prob < 0.5 then Printf.printf "answer = %d\n" (people+1) else birthday_paradox prob (people+1) ;; birthday_paradox 1.0 1 </syntaxhighlight> ===Church numerals=== The following code defines a [[Church encoding]] of [[natural number]]s, with successor (succ) and addition (add). A Church numeral {{OCaml|n}} is a [[higher-order function]] that accepts a function {{OCaml|f}} and a value {{OCaml|x}} and applies {{OCaml|f}} to {{OCaml|x}} exactly {{OCaml|n}} times. To convert a Church numeral from a functional value to a string, we pass it a function that prepends the string {{OCaml|"S"}} to its input and the constant string {{OCaml|"0"}}. <syntaxhighlight lang="OCaml"> let zero f x = x let succ n f x = f (n f x) let one = succ zero let two = succ (succ zero) let add n1 n2 f x = n1 f (n2 f x) let to_string n = n (fun k -> "S" ^ k) "0" let _ = to_string (add (succ two) two) </syntaxhighlight> ===Arbitrary-precision factorial function (libraries)=== A variety of libraries are directly accessible from OCaml. For example, OCaml has a built-in library for [[arbitrary-precision arithmetic]]. As the factorial function grows very rapidly, it quickly overflows machine-precision numbers (typically 32- or 64-bits). Thus, factorial is a suitable candidate for arbitrary-precision arithmetic. In OCaml, the Num module (now superseded by the ZArith module) provides arbitrary-precision arithmetic and can be loaded into a running top-level using: <syntaxhighlight lang=ocaml> # #use "topfind";; # #require "num";; # open Num;; </syntaxhighlight> The factorial function may then be written using the arbitrary-precision numeric operators {{mono|{{=}}/}}, {{mono|*/}} and {{mono|-/}} : <syntaxhighlight lang="OCaml"> # let rec fact n = if n =/ Int 0 then Int 1 else n */ fact(n -/ Int 1);; val fact : Num.num -> Num.num = <fun> </syntaxhighlight> This function can compute much larger factorials, such as 120!: <syntaxhighlight lang="OCaml"> # string_of_num (fact (Int 120));; - : string = "6689502913449127057588118054090372586752746333138029810295671352301633 55724496298936687416527198498130815763789321409055253440858940812185989 8481114389650005964960521256960000000000000000000000000000" </syntaxhighlight> ===Triangle (graphics)=== The following program renders a rotating triangle in 2D using [[OpenGL]]: <syntaxhighlight lang="OCaml"> let () = ignore (Glut.init Sys.argv); Glut.initDisplayMode ~double_buffer:true (); ignore (Glut.createWindow ~title:"OpenGL Demo"); let angle t = 10. *. t *. t in let render () = GlClear.clear [ `color ]; GlMat.load_identity (); GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. (); GlDraw.begins `triangles; List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.]; GlDraw.ends (); Glut.swapBuffers () in GlMat.mode `modelview; Glut.displayFunc ~cb:render; Glut.idleFunc ~cb:(Some Glut.postRedisplay); Glut.mainLoop () </syntaxhighlight> The LablGL bindings to OpenGL are required. The program may then be compiled to bytecode with: $ ocamlc -I +lablGL lablglut.cma lablgl.cma simple.ml -o simple or to nativecode with: $ ocamlopt -I +lablGL lablglut.cmxa lablgl.cmxa simple.ml -o simple or, more simply, using the ocamlfind build command $ ocamlfind opt simple.ml -package lablgl.glut -linkpkg -o simple and run: $ ./simple Far more sophisticated, high-performance 2D and 3D graphical programs can be developed in OCaml. Thanks to the use of OpenGL and OCaml, the resulting programs can be cross-platform, compiling without any changes on many major platforms. ===Fibonacci sequence=== The following code calculates the [[Fibonacci number|Fibonacci sequence]] of a number ''n'' inputted. It uses [[tail recursion]] and pattern matching. <syntaxhighlight lang = OCaml> let fib n = let rec fib_aux m a b = match m with | 0 -> a | _ -> fib_aux (m - 1) b (a + b) in fib_aux n 0 1 </syntaxhighlight> ===Higher-order functions=== Functions may take functions as input and return functions as result. For example, applying ''twice'' to a function ''f'' yields a function that applies ''f'' two times to its argument. <syntaxhighlight lang = OCaml> let twice (f : 'a -> 'a) = fun (x : 'a) -> f (f x);; let inc (x : int) : int = x + 1;; let add2 = twice inc;; let inc_str (x : string) : string = x ^ " " ^ x;; let add_str = twice(inc_str);; </syntaxhighlight> <syntaxhighlight lang = OCaml highlight="1,3"> # add2 98;; - : int = 100 # add_str "Test";; - : string = "Test Test Test Test" </syntaxhighlight> The function ''twice'' uses a type variable'' 'a'' to indicate that it can be applied to any function ''f'' mapping from a type'' 'a'' to itself, rather than only to ''int->int'' functions. In particular, ''twice'' can even be applied to itself. <syntaxhighlight lang = OCaml highlight="1,3,5"> # let fourtimes f = (twice twice) f;; val fourtimes : ('a -> 'a) -> 'a -> 'a = <fun> # let add4 = fourtimes inc;; val add4 : int -> int = <fun> # add4 98;; - : int = 102 </syntaxhighlight>
Summary:
Please note that all contributions to Niidae Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Encyclopedia:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
OCaml
(section)
Add topic