Jump to content

lambda , function , mapcar , apply , foreach : explained


Recommended Posts

Posted

why apply do this :

 

_$ (apply '+ '(1 2 3))
6

 

while mapcar do that

 

$ (mapcar '+ '(1 2 3))
(1 2 3)

Posted
why apply do this :

 

_$ (apply '+ '(1 2 3))
6

while mapcar do that

 

$ (mapcar '+ '(1 2 3))
(1 2 3)

 

Because:

(apply '+ '(1 2 3))

Is equivalent to:

(+ 1 2 3)

Whereas:

(mapcar '+ '(1 2 3))

Is equivalent to:

((+ 1) (+ 2) (+ 3))  -->  (1 2 3)

I would suggest reading the documentation on the apply & mapcar functions; you might also find this tutorial on mapcar/lambda useful for your understanding.

Posted
why apply do this :

 

_$ (apply '+ '(1 2 3))
6

while mapcar do that

 

$ (mapcar '+ '(1 2 3))
(1 2 3)

Why indeed! apply applies a function to one list, whereas mapcar is mapped to matching elements in the list(s) provided, which means they must be of equal length. There doesn't seem to be much point to the mapcar example you gave (and you might even ask why it worked at all), but mapping '- might be useful thus.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...