我正在创建一个使用语法的程序,并查看该语法是否为 LL (1)。我想使用Set模块,但我不知道如何进行,当然,set元素的类型将是char,你能帮忙吗?
最佳答案
此答案假设您已经知道如何确定语法是否为 LL (1),并且只是在寻求有关 Objective Caml Set
的具体用法的帮助。模块。
标准库Set
提供了一个仿函数,让您可以构建自己的集合模块,以满足您的特定需求。您需要提供一个描述集合内元素类型的模块,以及遵循与 compare
相同约定的比较函数。 :compare a b = 0
如果a = b
, compare a b < 0
如果a < b
等等。对于角色来说,这将是:
module OrderedChar = struct
type t = char
let compare = compare
end
module CharSet = Set.Make(OrderedChar)
CharSet
上面的模块有interface described in the documentation 。其要点是集合是不可变的值(如列表),因此该模块为您提供了通过添加或删除元素从现有集合创建新集合的函数:
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} */ *)
对集合元素的访问主要通过存在查询和迭代进行:
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 */ *)
关于set - 使用模块设置Ocaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4276131/