Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Why can't I use constructors as functions?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <Xavier.Leroy@i...>
Subject: Re: [Caml-list] Why can't I use constructors as functions?
> I'm curious as to the reason why I can't use a datatype constructor
> as a function. Eg, in SML I can write a function like this:
>   fun add a b = fold Succ a b (* Use the Succ constructor as a funtion *)
> If I try something similar in Caml, 
> Instead I need to wrap it in a function:
>   # let add a b = fold (fun x -> Succ x) a b

The old Caml V3.1 implementation treated constructors as functions like SML.
In Caml Light, I chose to drop this equivalence for several reasons:

- Simplicity of the compiler.  Internally, constructors are not
functions, and a special case is needed to transform Succ into
(fun x -> Succ x) when needed.  This isn't hard, but remember that
Caml Light was really a minimal, stripped-down version of Caml.

- Constructors in Caml Light and OCaml really have an arity, e.g.
C of int * int is really a constructor with two integer arguments,
not a constructor taking one argument that is a pair.  Hence, there
would be two ways to map the constructor C to a function:
        fun (x,y) -> C(x,y)
or
        fun x y -> C(x,y)
The former is more natural if you come from an SML background
(where constructors have 0 or 1 argument), but the latter fits better
the Caml Light / OCaml execution model, which favors curried
functions.  By not treating constructors like functions, we avoid
having to choose...

- Code clarity.  While using a constructor as a function is sometimes
convenient, I would argue it is often hard to read.  Writing
"fun x -> Succ x" is more verbose, but easier to read, I think.

- Xavier Leroy
-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr