Skip to content

Instantly share code, notes, and snippets.

@wreulicke
Created December 10, 2017 03:17
Show Gist options
  • Save wreulicke/980a775764b7083730b0224a484694be to your computer and use it in GitHub Desktop.
Save wreulicke/980a775764b7083730b0224a484694be to your computer and use it in GitHub Desktop.
ocaml
type 'a myList = MyNil | MyCons of 'a * 'a myList
let myList x y = MyCons (x, MyCons(y, MyNil))
let rec map f x =
match x with
| MyNil -> MyNil
| MyCons (x, xs) ->
MyCons (f x, map f xs)
let rec foreach f x =
match x with
| MyNil -> ()
| MyCons (x, xs) ->
f(x);
foreach f xs
let () = foreach print_string (myList "xxx" "vvv")
let assert_and_dump a e = let _ = print_int(a) in assert (a == e)
let rec repeat f n x = if n > 0 then repeat f (n -1) (f x) else x
let fib n =
let f = fun (a, b) -> (a + b , a) in
let (fibn, _) = repeat f n (0 , 1)
in fibn
let () = assert_and_dump (fib 0) 0
let curry f x y = f (x, y)
let uncurry f (x, y) = f x y
let f (x, y) = x * y
let () = print_int (curry f 1 2)
let () = print_int (uncurry (curry f) (2, 3))
(* let () = print_int (4/0) *)
let rec find x = function
| [] -> None
| a :: l when a = x -> Some 1
| _ :: l -> match find x l
with
| Some i -> Some (i+1)
| None -> None
let () = match find 1 [1; 2; 3] with
| Some i -> print_int(i)
| None -> print_string("not_found")
let () = print_int(2);print_newline()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment