views:

71

answers:

3

Here we have a function definition:

let f x = x + 3;;

Here is an expression:

let g = 4;;

Could g just be thought of as constant function that takes no arguments? Is there any difference?

+5  A: 

Yes - From a totally functional point of view (like practised in Haskell), everything is a function (Really everything).

And since a purely-functional language disallows any kind of change, this definition does not bear any contradictions.

Is there any difference?

Well, OCaml is not purely-functional. This means the functions are allowed to perform side-effects which differs a bit from the definition of a constant value.

This code (F# here - but quite similar in Caml) would be perfectly valid.

let name = 
    Console.Write("Enter your Name: ")
    Console.ReadLine()
Dario
and the point with the last example is that the side effects in a variable definition can only be performed once
newacct
+1  A: 

Technically, the definition of variables are pattern matches:

let [x] = someList
let y::zs = someList
let (Some z) = someOption
let _ = someIgnoredExpr
newacct
+5  A: 

The difference between

let f() = expr

and

let f = expr

in a non-pure language is that the 'effects' of 'expr' run at every 'call site' in the former case, and just once at the definition site in the latter case. This is one of the very few differences between the two, but perhaps the most important.

Brian