irneb 发表于 2022-7-6 10:19:48

Both mapcar and foreach run from 1st to last. The major difference between the 2 is what's known in programming parlance as functional and procedural. In both the list is processes one item at a time starting from the 1st. The differences are: 


[*]With mapcar a function is applied to each item in turn, and then a new list containing the modified results is what comes out.
[*]With foreach multiple statements are run with the current item in its nth state. No new list is (necessarily) returned or created - normally only the very last calculation is returned at the end of foreach.

Think of it as such:
 


[*]When you want to modify each item in a list and get a resulting list - mapcar is most probably your choice.
[*]If you want to use the list to modify something else foreach is probably best.

This does not mean that you use foreach when making a procedural (also called imperative) and mapcar when you're making a functional thing. You can easily alter the result and set variables states in either one. Thus what you do inside each can have similar effects, but on their own they're quite distinct.
 
E.g. let's say you've got a list of integers want to add 10 to each:
(mapcar '(lambda (item) (+ item 10)) '(1 2 3 4 5)) ;Result is (11 12 13 14 15)To get the same using foreach:
(setq result nil)(foreach item '(1 2 3 4 5) (setq result (cons (+ item 10) result)) ;Last call to setq returns (15 14 13 12 11) because the cons adds the new item in front(reverse result) ;So reverse the list to get (11 12 13 14 15)Now let's say we want to sum each value together to get a grand total:
(setq total 0)(mapcar '(lambda (item) (setq total (+ total item))) '(1 2 3 4 5));; Result of mapcar would be (1 3 6 10 15)(princ total) ;Total's value becomes 15Here it's probably more in-line with using foreach:
(setq total 0)(foreach item '(1 2 3 4 5) (setq total (+ total item))) ;The result at the end is 15, as is the value inside total.Or slightly off topic: to use a pure functional way:
(apply '+ '(1 2 3 4 5)) ;Result is 15

muthu123 发表于 2022-7-6 10:27:46

Nice Explanation.
Thank you.
页: 1 [2]
查看完整版本: Difference between 'forea