Use module Set Ocaml

陌路散爱 提交于 2019-12-24 04:27:37

问题


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?


回答1:


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 */ *)


来源:https://stackoverflow.com/questions/4276131/use-module-set-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!