Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elisp how to apply a lambda to a list?

What I'm trying to do seems simple enough, and whatever's wrong must be a really dumb mistake, since I couldn't find other people getting the same error. I just want to apply a lambda to a list - the lambda here isn't what I actually want to do, but it gives the same error.

(apply
(lambda (arg)
  (+ 5 arg)
)
(list 2 3 4)
)

When I try to run this, it tells me that I'm passing the lambda an invalid number of arguments. Do you have any advice?

like image 749
Axle12693 Avatar asked Dec 17 '25 23:12

Axle12693


2 Answers

apply calls the function once, passing it the list you've given as the arguments. I think you instead want to use mapcar:

M-: (mapcar (lambda (arg) (+ 5 arg)) (list 2 3 4)) RET

will return the list (7 8 9).

like image 56
Stefan Avatar answered Dec 20 '25 20:12

Stefan


Just to make the problem a bit clearer:

This form

(apply
 (lambda (arg)
   (+ 5 arg))
 (list 2 3 4))

is basically similar to

(funcall
 (lambda (arg)
   (+ 5 arg))
 2
 3
 4)

In above we try to call a function with one parameter arg with three arguments.

Now if you want to pass more than one argument and receive it as a single list you would need a function with a &rest parameter:

(lambda (&rest args) ...)

You say

I just want to apply a lambda

This is not what you want. You want to map the function over a list. Which means calling the function for each element of the list and returning a new list with the results. This operation is called in Lisp mapping. See the answer by Stefan for an example.

Applying a function to a list would be: call the function with the arguments taken from the list.

like image 22
Rainer Joswig Avatar answered Dec 20 '25 20:12

Rainer Joswig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!