[erlang-questions] arity part of function name and variadic functions
Richard O'Keefe
ok@REDACTED
Wed Feb 25 04:34:21 CET 2009
On 25 Feb 2009, at 3:23 pm, Peter Michaux wrote:
> Thanks to everyone who replied.
>
> On Mon, Feb 23, 2009 at 3:31 PM, Richard O'Keefe <ok@REDACTED>
> wrote:
>
>> (2) What would you want variadic functions for?
>
> There are many examples in lisp.
Which I am thoroughly familiar with.
> Sum is a variadic function so that
> summing two or more items have the same syntax.
That's #'+, not #'sum.
> If there were no
> variadics and it was desirable to have the same syntax for summing two
> or more items, then summing two would need to be written in quite a
> bulky fashion (+ (list a b))
To call it desirable to have the same syntax
for summing two and for summing more items
would be to beg the question (petitio principii).
Let's look at APL. (APL lives!)
In APL, X + Y adds two things. +/X adds up the
elements of a vector. APL2's strand notation means
that we have
X + Y
+/ A B C ... Z
But +/ is not a variadic function. It is a function of
one argument, namely a vector. There is a visible
relation between + and +/, in fact / is a higher-order
operator applicable to any binary operator.
In Erlang, we have X + Y to add two numbers and
lists:sum([A,B, ..., Z]) to add many of them.
It was always a surprise to me just how useful this
feature of Lisp wasn't. On the occasions when I
wanted to exploit it, say (apply #'+ numbers), I
always ran into problems, like there being a maximum
number of arguments. I always ended up defining my
own #'sum. These days I'd use
(loop for x in numbers sum x)
When it comes to AND and OR, I concede: there I've
always found it useful that they allow many arguments,
and a pain that (apply #'AND booleans) doesn't work.
But with an infix &&, I've never missed AND.
>
> Functions like map are also variadic in lisp. The common case has
> simple syntax (map f a) and then extends naturally to the less common
> case of multiple lists (map f a b c)
Have you ever tried _implementing_ that?
It's a pain. Also, when I met that "feature" of Lisp,
I was coming from another dialect, where one wrote
(map list f)
and since the function was usually the big thing, and
the list already handy, it was _much_ nicer to write
(map pairs #'(lambda (pair)
#|body of lambda|#))
than to write
(map #'(lambda (pair)
#|body of lambda|#)
#|now where do I put 'pairs' so I can see it|#)
ML handles this by having map (one argument functions) and
map2 (two argument functions). Clean does it with list
comprehensions:
[f x y z \\ x <- xs & y <- ys & z <- zs]
although it's long enough since I last used Clean that
I've probably got the syntax wrong. If I have list
comprehensions, I don't _want_ variable arity map, because
I have something better.
I still love Lisp (especially Scheme), but one of the things
I do not miss at all in Haskell or ML or Erlang is variable
arity functions.
More information about the erlang-questions
mailing list