Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Functor implementation
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Chris Clearwater <chris@s...>
Subject: [Caml-list] Functor implementation
Hi all, I was curious as to how ocaml implements functors and finding no help
with google, I thought I could ask on the list. After giving it a little
thought I was thinking they might be implemented as follows:

type 'a tree = Empty | Node of ('a tree) * 'a * ('a tree)
type comparison = GT | EQ | LT

let node l v r = Node(l, v, r)
let single v = Node(Empty, v, Empty)

let rec insert c t a =
    match t with
        Empty -> single a
      | Node(l, v, r) -> match (c a v) with
            LT -> node (insert c l a) v r
          | EQ -> t
          | GT -> node l v (insert c r a)

let rec member c t a =
    match t with
        Empty -> false
      | Node(l, v, r) -> match (c a v) with
            LT -> member c l a
          | EQ -> true
          | GT -> member c r a

(* Functor implementation follows *)

type 'a setmodule = {
    empty: 'a tree;
    insert: 'a tree -> 'a -> 'a tree;
    member: 'a tree -> 'a -> bool;

let make c = {
    empty = Empty;
    insert = insert c;
    member = member c;

(* Use a functor *)
let compare x y = let cmp = x - y in if cmp > 0 then GT else if cmp < 0 then LT else EQ
let mymodule = make compare
let s = mymodule.insert mymodule.empty 5


How far off is Ocaml's way and is the performance comparable? And on a
sidenote, wouldn't it be beneficial for there to be a built in comparison
type and a function to convert from integers greater than less than or
equal to, to the comparrison type? I imagine this would clarify code
that uses comparisons greatly.

Thanks in advance for your answers!

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: