Wednesday 30 September 2009

functions and funs

To create a function that takes a fun as an argument

   1: mangle(F, X) ->
   2:     F(X).
4> play:mangle(fun(X) -> (X*X) end, 3).

Remember that if you’re defining the fun inline to add the end still – or you’ll see

* 1: syntax error before: ')'

To pass in a function to something that needs a fun, pass a function reference and remember the arity

   1: double(X) ->
   2:     2*X.
6> play:mangle(fun play:double/1, 3).
6

And finally to create a function that returns a fun

   1: getMangler() ->
   2:     (fun(X) ->
   3:         play:double(X) end).
   4:  
1> Mangler = play:getMangler().
#Fun<play.0.65855982>
2> Mangler(3).
6
3> play:mangle(Mangler, 3).
6

and you can naturally just put the getMangler into the call direct:

4> play:mangle(play:getMangler(), 3).
6

Note that this won’t work:

5> play:mangle(fun play:getMangler/0, 3).
** exception error: play:getMangler/0 called with one argument
     in function  play:mangle/2

because you’re attempting to call getMangler with the argument 3.

No comments: