Variadic functions

Sett 11 ganger
Hopp til første uleste melding

Eric Bailey

ulest,
3. aug. 2015, 21:04:3603.08.2015
til 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

ulest,
4. aug. 2015, 19:56:5104.08.2015
til 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
Svar alle
Svar til forfatter
Videresend
0 nye meldinger