For-each和map in Scheme [英] For-each and map in Scheme

查看:315
本文介绍了For-each和map in Scheme的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

for-each 评估从左到右的列表元素的给定函数,并放弃函数的返回值。对于列表中的每一个元素来说,这是非常理想的。



map 列表元素没有特定的顺序(虽然大多数实现将使用从右到左或从左到右),并保存函数的返回值返回给调用者。对于列表的每个元素进行纯功能处理是理想的。



如果 map 的返回值为不要使用,最好使用 for-each 。这样,它不必费心从函数调用中收集返回值。



(另见:在Clojure中,返回值地图是一个懒惰的序列,这意味着给定的函数只被调用为实现的元素。)






技术实施细节。通常实现一个简单的单列表版本的 for each each / / c $ c>通常是这样实现的:

 (define(for-each func lst)
(let loop((rest lst))
(除非(null?rest)
(func(car rest))
(loop(cdr rest)))))

真的很直接,保证从左到右订购。与简单的单列表版本 map 相比:

 (define (map func lst)
(let recur((rest lst))
(if(null?rest)
'()
(cons(func(car rest)) recur(cdr rest)))))))

在Scheme中,函数参数的评估顺序不是指定。因此,对于(foo(bar)(baz)(qux))之类的表达式,调用 bar code> baz qux 可以按任何顺序进行,但都会在 foo 被调用。



在这种情况下,(func(car rest))可以发生或者它可能发生在(recur(cdr rest))之后。这不能保证任何一种方式。这就是为什么人们说地图不保证评估订单。


Are there any difference between these 2 functions in scheme?I am using Dr Racket R5RS language to make a simulator game and I could not decide which one is better.

解决方案

for-each evaluates the given function on the list elements left-to-right, and discards the return value of the function. It's ideal for doing side-effecting things to each element of the list.

map evaluates the given function on the list elements in no specific order (though most implementations will use either right-to-left or left-to-right), and saves the return value of the function to return to the caller. It's ideal for doing pure-functional processing on each element of the list.

If the return value of map is not going to get used, it is better to use for-each instead. That way, it doesn't have to bother collecting the return values from the function calls.

(Aside: in Clojure, the return value of map is a lazy sequence, which means the given function is only invoked for the elements being materialised.)


Technical implementation details. A simplified one-list version of for-each is usually implemented like this:

(define (for-each func lst)
  (let loop ((rest lst))
    (unless (null? rest)
      (func (car rest))
      (loop (cdr rest)))))

Really straightforward, and guarantees left-to-right order. Contrast with a simplified one-list version of map:

(define (map func lst)
  (let recur ((rest lst))
    (if (null? rest)
        '()
        (cons (func (car rest)) (recur (cdr rest))))))

In Scheme, the evaluation order for function arguments is not specified. So for an expression like (foo (bar) (baz) (qux)), the calls to bar, baz, and qux can occur in any order, but they will all complete before foo is called.

In this case, the (func (car rest)) can happen first, or it may happen after (recur (cdr rest)). It's not guaranteed either way. This is why people say that map does not guarantee an evaluation order.

这篇关于For-each和map in Scheme的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆