'Why i can not call returned method directly
I have the following curious case in Erlang:
Tx=fun(A)->G=fun()->A+33 end,G end.
I do not understand why i can't call the returned method directly , and need to store it in a variable first:
Tx(3)(). -> 1: syntax error before: '(' //why does this not work ?
Var=Tx(3) //and this
Var() // works
I can not call a method that is returned ?
Solution 1:[1]
Wrap the returned fun into brackets:
(Tx(3))().
Solution 2:[2]
It's an order of operations problem. The compiler/runtime doesn't understand what's being returned from Tx(3) is a function. By adding () around it (Tx(3)), Tx(3) is evaluated first, is seen as a function, and can then be evaluated again.
Solution 3:[3]
this is a high order function(like closure)
Tx= fun(A)->
G=fun()->A+33 end,
G
end.
Tx is a function where arity = 1, and return a function called G
and
G with arity = 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | dolphin2017 |
