If I want to write list.ml
in OCaml,
Q1
which way is correct?
type 'a list =
| Nil
| Cons of 'a * ('a list)
or
type 'a list =
| Nil
| Cons of 'a * 'a list
Any differences?
Q2
Also, how do I define the Cons
inside the type definition as ::
?
Q3
How do I define Nil
inside the type definition as []
?
Q1 - There is no difference; each has two parameters associated to Cons
. Although, Cons of ('a * 'a list)
is different since it has one parameter, a tuple. You will come across that as an important distinction if you construct a tuple and try to wrap it in Cons
as in, let x = a,Nil in Cons x
. The choice depends on how you plan on constructing elements or some semantics of the data. In this particular case, no parenthesis should be used.
Q2 - You cannot use :
as the first character of infix function names as it is a keyword in the language -- ::
is also a keyword regardless. In general infix operators can be defined with parenthesis around the function name and there is a special set of symbols allowed,
let (!!) a b = Cons( a,b )
Q3 - This would require naming an identifier []
, as in let [] = Nil
. Those characters are not allowed in the naming conventions (see same link as above) as they are also individually keywords.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.