[erlang-questions] Funargs: Ruby-like blocks for Erlang

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Thu Jul 21 14:34:37 CEST 2011


On Thu, Jul 21, 2011 at 09:39, Tony Arcieri <tony.arcieri@REDACTED> wrote:

> Ruby has this really nifty feature called blocks which, to put not too
> fine a point on it, provides some awesome syntactic sugar for passing
> an anonymous function as an argument to another function. In Ruby,
> blocks look like this:
>
>     [1,2,3,4,5].map do |n|
>         n * 2
>     end

Most of the trouble stems from

a) No currying in Erlang
b) A long anonymous function notation
c) No sectioning

In Haskell, your example is

map (*2) [1..5]

and if written without sectioning:

map (\x -> x * 2) [1..5]

and in SML which doesn't have a list constructor convenience notation:

List.map (fn x => x * 2) [1,2,3,4,5]

.

Ruby blocks is a weak implementation of anonymous functions in every
way. The problems from using lots of anonymous functions in Erlang
programs is mainly because the notational overhead of using them is
too big. But then again, I don't find

lists:map(fun(X) -> X * 2 end, [1,2,3,4,5]),

much harder to read. Yes, there is more clutter in there due to the
function object. But it has a distinct advantage over the block in
ruby which is that it is not statement-syntax but an expression. I can
write

foo(F) ->
  lists:map(F, [1,2,3,4,5]).

and get away with it. In Ruby you have to do something more here to
turn the do-block, which is a statement, into some kind of value you
can then pass around. When I looked at Ruby in 2002 they had some
"proc" objects to do this with. I am sure it is better today. My main
gripe with the kind of notation you propose is that it doesn't
*compose* in the sense of a mathematical algebra.  It is also why I
like currying, and why I absolutely *love* Agda 2 for its infix
operator definitions. In Agda, you can do:

data List (A : Set) : Set where
  [] : List A
  _∷_ : A -> List A -> List A

which defines that we have a list and that the notation of the cons
is: x ∷ l, where x has type A and l has type List A. You can even do
more advanced stuff like if_then_else to build if-then-else statements
yourself. These tools allow you to construct algebraic solutions to
nearly any problem statement syntax will help with.

TL;DR I don't think we need a new kind of syntax for certain kinds of
lambda sections (see the 'cut' proposal a couple of days ago from
SRFI-26 in Scheme-land). But I do agree the notation is heavier than
it could be. A more convenient notation would encourage people to use
anonymous functions more.

-- 
J.



More information about the erlang-questions mailing list