乐筑天下

搜索
欢迎各位开发者和用户入驻本平台 尊重版权,从我做起,拒绝盗版,拒绝倒卖 签到、发布资源、邀请好友注册,可以获得银币 请注意保管好自己的密码,避免账户资金被盗
楼主: muthu123

[编程交流] Difference between 'forea

[复制链接]

11

主题

968

帖子

919

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
99
发表于 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:
  1. (mapcar '(lambda (item) (+ item 10)) '(1 2 3 4 5)) ;Result is (11 12 13 14 15)
To get the same using foreach:
  1. (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:
  1. (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 15
Here it's probably more in-line with using foreach:
  1. (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:
  1. (apply '+ '(1 2 3 4 5)) ;Result is 15
回复

使用道具 举报

55

主题

133

帖子

78

银币

后起之秀

Rank: 20Rank: 20Rank: 20Rank: 20

铜币
280
发表于 2022-7-6 10:27:46 | 显示全部楼层
Nice Explanation.
Thank you.
回复

使用道具 举报

发表回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 微信公众平台

  • 扫描访问手机版

  • 点击图片下载手机App

QQ|关于我们|小黑屋|乐筑天下 繁体中文

GMT+8, 2025-3-7 03:06 , Processed in 0.340690 second(s), 54 queries .

© 2020-2025 乐筑天下

联系客服 关注微信 帮助中心 下载APP 返回顶部 返回列表