Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang equivalents of Haskell where/partial/lambda

Coming from Haskell to play with Nitrogen and running into a few things I can't find examples of, so if somebody could help me out:

Haskell's where (and or let or any type of function nesting with access to parent variables) in erlang? How? Can you?

burnOrDie hotness = foldl1 (>>) $ map burn ["Jimmy", "Adam", "Gonzo"]
  where burn x
          | hotness < 3 = print $ x ++ ": Ouch!"
          | otherwise = print $ x ++ ": GAHHH! *die*"

Partial application? Haskell: addOne = +1

in-line lambda function? Haskell: map (\x -> x+x) [1,2,3]

like image 748
Jimmy Hoffa Avatar asked Nov 13 '12 04:11

Jimmy Hoffa


1 Answers

I am no expert in erlang but I will try to answer.

Nesting functions

out(A) ->
    X = A + 1,
    SQ = fun(C) -> C*C end,
    io:format("~p",[SQ(X)]).

here SQ function has access to parent variables.

In Lambda

This is same as above, you can use fun to define your anonymous functions.

Partial application

I don't think erlang has partial function application in any sane way. The only thing you can do is to wrap functions to return function.

add(X) -> 
    Add2 = fun(Y) -> X + Y end,
    Add2.

Now you can do something like

1> c(test).
{ok,test}
2> A=test:add(1).
#Fun<test.0.41627352>
3> A(2).
3
like image 172
Satvik Avatar answered Sep 28 '22 00:09

Satvik