Re: How to escape the Ocaml's superfluous parentheses and type declarations?
- From: "Brian Hulley" <brianh@xxxxxxxxxxxx>
- Date: Thu, 8 Sep 2005 20:48:29 +0000 (UTC)
andrewspencers@xxxxxxxxx wrote:
> # type 'a mylist = E | Mycons of 'a * 'a mylist;;
> type 'a mylist = E | Mycons of 'a * 'a mylist
> # let rec mylength x =
> match x with
> E -> 0
> | Mycons (i, l) -> 1 + mylength l;;
> val mylength : 'a mylist -> int = <fun>
> # mylength Mycons (1, Mycons (2, Mycons (3,E)));;
> This function is applied to too many arguments, maybe you forgot a `;'
This is because the parser parses the above as:
((mylength Mycons) (1, Mycons (2, Mycons (3,E))));
so you need the brackets (as you discovered) to glue the first Mycons
to the pair instead of it being treated as an argument by itself ie as
far as the parser is concerned Mycons is just a function like any
other, which in this case takes a pair and returns an object of type 'a
mylist as per your type declaration. Since functions are first class
values, Mycons by itself is treated as an argument just like any other
value...
> <<snip>>
> # mylength (Mycons (3, Mycons ('a', E)));;
> This expression has type char but is here used with type int
>
> I've explicitly defined the union, and it STILL can't figure it out!
> Let's make it even more explicit:
>
> # mylength (Mycons (Int 3, Mycons (Char 'a', E)));;
> - : int = 2
>
> Why is that necessary?
Because you haven't declared the union of char and int. There can be no
such thing because char and int are separate types. What you have
declared is a completely new type called charint, whose values are
constructed from the built-in types as follows: given a char the
constructor function called Char gives you a value of type charint, and
given an int the function Int gives you a value of type charint. ie
Char and Int are just functions. The only thing that's special about
them is that you can use constructor application syntax in pattern
matching to get back the original char or int respectively ie:
# let a = Int 3;;
val a : charint = Int 3
# let Int b = a;;
val b : int = 3
Hope this helps,
Regards, Brian.
.
- References:
- How to escape the Ocaml's superfluous parentheses and type declarations?
- From: andrewspencers
- How to escape the Ocaml's superfluous parentheses and type declarations?
- Prev by Date: Re: How to escape the Ocaml's superfluous parentheses and type
- Next by Date: Can Monads be implemented in pure core SML?
- Previous by thread: Re: How to escape the Ocaml's superfluous parentheses and type
- Next by thread: Re: How to escape the Ocaml's superfluous parentheses and type declarations?
- Index(es):
Relevant Pages
|