Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: Why does this fail with a 'badarith' exception?

Is it possible to implement a closure in Erlang?

For example, how would I translate this snippet from Scheme?

(define (make-adder n)
  (lamdba (x) (+ x n)))

I've tried the following, but I'm clearly missing something.

make_adder(n) ->
    fun (x) -> x + n end.

Compiling this gives the error

Warning: this expression will fail with a 'badarith' exception
like image 783
grifaton Avatar asked Sep 19 '09 22:09

grifaton


3 Answers

You can't add atoms. Variables start with Capital Letters in erlang. words starting with lower case letters are atoms.

In other words your problem is not related to funs at all, you just need to capitalize your variable names.

like image 90
sepp2k Avatar answered Nov 11 '22 19:11

sepp2k


make_adder(N) ->
  fun (X) -> X + N end.
like image 30
Christian Avatar answered Nov 11 '22 21:11

Christian


Variables start with Capital Letters in erlang. words starting with lower case letters are atoms.

like image 25
BertKing Avatar answered Nov 11 '22 21:11

BertKing