user1993381
user1993381

Reputation: 179

Set notation OCaml

this is just a question regarding notation in OCaml.

I am trying to test the function

let rec add (x : 'a) (l : 'a set) : bool =
  begin 
    match l with
    | [] -> []
    | hd :: rest -> 
      if x = hd then rest 
      else (hd :: (add x rest))
  end

my test case is

let test () : bool =
add (3 [1; 2; 4]) = [1; 2; 3; 4]
;; run_test "add 3 [1; 2; 4]" test

I am getting an "this expression is not a function, cannot be applied" error

Is something wrong with my notation?

Upvotes: 0

Views: 497

Answers (2)

gasche
gasche

Reputation: 31459

There is no set notation in OCaml. I don't know what your 'a set type is, I don't understand why membership would be tested with List.mem, but it should have no specific notation.

There is a Set.Make functor in the standard library, to be instantiated by a module having at least a type and a comparison function on keys (see here):

module StringSet = Set.Make(String)
let set = StringSet.(add 0 (add 1 (add 2 empty)))
let test = StringSet.mem 3 set

If you want a convenient notation, your best bet is to use a conversion function from lists to sets, and use the list notation:

let set_of_list li = List.fold_left (fun s v -> StringSet.add v s) StringSet.empty li
let set = set_of_list [0; 1; 2]

Upvotes: 2

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

OCaml doesn't have a built-in set type (instead there is a Set module, or library). So, there's also no built-in notation for set constants.

For smallish sets, one often uses lists. And, in fact, List.mem is a function that operates on lists (not sets). The notation for a list is like this: [1; 2; 3; 4].

(As a side comment, your function named add doesn't add anything. But maybe you're just getting started.)

Upvotes: 3

Related Questions