Created
June 2, 2020 16:06
-
-
Save irevoire/f622654f13912f6a8b66e49b725d0b74 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exception Error of string | |
type 'a node = | |
| Cons of { current: 'a; next: 'a node } | |
| Nil | |
module Node = struct | |
let empty = Nil | |
let add a b = Cons { current = a; next = b } | |
end | |
type 'a truc = { cmp: ('a -> 'a -> bool); head: 'a node } | |
module Truc = struct | |
(* create an empty truc *) | |
let empty (cmp: 'a -> 'a -> bool): 'a truc = { cmp = cmp; head = Node.empty } | |
(* add a machin to a truc *) | |
let add (machin: 'a) (truc: 'a truc) = | |
{ | |
cmp = truc.cmp; | |
head = Node.add machin truc.head | |
} | |
(* return the position of the machin in the truc *) | |
let position (machin: 'a) (truc: 'a truc) = | |
let rec aux idx node = | |
match node with | |
| Cons { current = head; next = _ } when truc.cmp machin head -> idx | |
| Cons { next = tail; _ } -> aux (idx + 1) tail | |
| Nil -> raise (Error "Element does not exist in the truc") | |
in | |
aux 0 truc.head | |
end | |
let my_truc = Truc.empty (=) | |
|> Truc.add 5 | |
|> Truc.add 4 | |
|> Truc.add 3 | |
|> Truc.add 2 | |
|> Truc.add 1 | |
;; | |
Printf.printf "The position of 4 is %d\n" (my_truc |> Truc.position 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment