Is it really true that OCaml doesn’t have a function which converts from a list to a set?
If that is the case, is it possible to make a generic function list_to_set? I’ve tried to make a polymorphic set without luck.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Fundamental problem: Lists can contain elements of any types. Sets (assuming you mean the Set module of the standard library), in contrary, rely on a element comparison operation to remain balanced trees. You cannot hope to convert a
t listto a set if you don’t have a comparison operation ont.Practical problem: the
Setmodule of the standard library is functorized: it takes as input a module representing your element type and its comparison operation, and produces as output a module representing the set. Making this work with the simple parametric polymoprhism of lists is a bit sport.To do this, the easiest way is to wrap your set_of_list function in a functor, so that it is itself parametrized by a comparison function.
You can then use for example with the String module, which provides a suitable
comparefunction.It is also possible to use different implementation of sets which are non-functorized, such as Batteries and Extlib ‘PSet’ implementation (documentation). The functorized design is advised because it has better typing guarantees — you can’t mix sets of the same element type using different comparison operations.
NB: of course, if you already have a given set module, instantiated form the Set.Make functor, you don’t need all this; but you conversion function won’t be polymorphic. For example assume I have the
StringSetmodule defined in my code:Then I can write
stringset_of_listeasily, usingStringSet.addandStringSet.empty:In case you’re not familiar with folds, here is a direct, non tail-recursive recursive version: