21

I have the function below and it works:

(fn x => x * 2) 2; 

but this one doesn't work:

(fn x y => x + y ) 2 3;

Can anyone tell me why? Or give me some hint to get it to work?

Alex Coplan
  • 13,211
  • 19
  • 77
  • 138
jjennifer
  • 1,285
  • 4
  • 12
  • 22
  • it works when I changed to this (fn (x,y) => x + y) (2,3); but why (fn x y => x * y) 2 3; produces an error – jjennifer Mar 13 '10 at 02:23

3 Answers3

35

(fn x => fn y => x+y) 2 3; works. fn simply doesn't have the same syntactic sugar to define curried functions that fun has.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
3

In Standard ML, a function can have only one argument, so use

(fn (x,y) => x + y) (2,3) 

and the type is

fn: int * int -> int

in this time (x,y) and (2,3) is a list structure,

Waverim
  • 41
  • 2
2

The answers posted above are correct. SML functions take only one argument. As a result, SML functions can have only one of two input types :

1) t = (t1 * t2 * ... * tN) , for some N

2) t = a, for some a.

So, technically speaking, SML only takes product types or unary types as arguments to functions. One can more generally think of this as an Unary-Type or a projection of some product Type.

In order to have currying inside anonymous functions, feel free to nest them inside each other as : fn x1 => fn x2 => ... fn xN => ...

I think it's also important to know that : fun a = fn x1 => fn x2 => ... fn xN => ... is the full expansion of the syntactic sugar : fun a x1 x2 .. xN