user520000
user520000

Reputation: 21

Use module Set Ocaml

I am creating a program that uses a grammar and see if this grammar is LL (1). I want to use the module Set, but I have no idea how to proceed, of course, the type of the elements of the set will char, can you help?

Upvotes: 2

Views: 1517

Answers (1)

Victor Nicollet
Victor Nicollet

Reputation: 24577

This answer assumes that you already know how to determine if a grammar is LL (1), and are merely looking for help on the specific usage of the Objective Caml Set module.

The standard library Set provides a functor that lets you construct your own set module, adapted for your specific needs. You need to provide a module that describes the type of elements inside the set, and a comparison function that follows the same convention as compare : compare a b = 0 if a = b, compare a b < 0 if a < b and so on. For characters, this would be:

module OrderedChar = struct
  type t = char
  let compare = compare
end

module CharSet = Set.Make(OrderedChar)

The CharSet module above has the interface described in the documentation. The gist of it is that sets are immutable values (like lists), so the module provides you with functions that create a new set from an existing set by adding or removing elements:

let a  = CharSet.add    'a' CharSet.empty 
let ab = CharSet.add    'b' a
let b  = CharSet.remove 'a' ab
(* /* a, b and ab are three sets containing respectively {a}, {b} and {ab} */ *)

Access to elements of a set happens mostly through existence queries and through iteration:

assert (CharSet.mem 'a' ab) 
assert (not (CharSet.mem 'c' b))

CharSet.iter print_char ab 
(* /* Prints 'ab' : follows the order defined by your 'compare' function */ *)

Upvotes: 3

Related Questions