Variadic functions

11 views
Skip to first unread message

Eric Bailey

unread,
Aug 3, 2015, 9:04:36 PM8/3/15
to Lisp Flavoured Erlang
As an exercise, I've started implementing the various map functions from the CL HyperSpec and ran into a bit of a roadblock their variadic nature.

I know certain functions like the arithmetic operators and ++ are (seem?) variadic, so I'm wondering how I can write my own.

I was toying around with a macro that expands to the appropriate defuns with arities up to 20 à la Clojure, but that proved nontrivial to me and doesn't seem like the best approach overall anyway.

So, what's the preferred way to write variadic functions in LFE?


Related question: Given a defined function, is there a way to get its arity?

As in:

(defun f (x y) (+ x y))

(... f) ; <= 2


Cheers,
Eric

Robert Virding

unread,
Aug 4, 2015, 7:56:51 PM8/4/15
to Lisp Flavoured Erlang
Because of the underlying Erlang machine LFE does not support variadic functions. At all. Functions have a fixed number of arguments and can only be called with the right number of arguments. However, you can have functions with the same name but with a different number of arguments, but they are different functions. For example:

(defun foo (x y) (+ x y))
(defun foo (x y) (* x y z))


but they are different functions. If you call (foo 1 2) you will get the first one, if you call (foo 1 2 3) you get the second one and if you call (foo 1 2 3 4) you get an error as there is no foo/4.

The only variadic forms are either core forms or macros. The arithmetic functions and ++ are macros. (+ x y z) expands to

(let* ((-0- x)
       (-1- y)
       (-2- z))
  (erlang:+ (erlang:+ -0- -1-) -2-))


The let* ensures that the arguments are evaluated strictly left-to-right.

Robert
Reply all
Reply to author
Forward
0 new messages