简体   繁体   English

高阶函数

[英]Higher-order functions

given, 给定

(define (reduce f id lis)
    (if (null? lis) id
      (f (car lis) (reduce f id (cdr lis)))))

The length of a list can be defined in terms of reduce (as opposed to using a recursive definition from scratch) as 列表的长度可以用reduce来定义(与从头开始使用递归定义相反):

(define (mylength lis) (reduce  (lambda (x n) (+ 1 n)) 0 lis)).

Define the list function mymap (similar to map ) that takes a unary function uf and a list lis in terms of reduce, that is, by determining the corresponding f and id in 定义列表函数mymap (类似于map ),该列表函数使用一元函数uf lis来表示化lis ,即通过确定in中对应的fid

(mymap uf lis) = (reduce f id lis),

Recall that mymap returns a list resulting from calling the function on every element in the input list such as (mymap (lambda(x) (* 2 x)) '(1 2 3)) = (2 4 6) . 回想一下mymap返回一个列表,该列表是通过在输入列表中的每个元素上调用函数而得到的,例如(mymap (lambda(x) (* 2 x)) '(1 2 3)) = (2 4 6)

A little Explanation to how this has been done would be helpful, rather than a blatant answer. 对如何完成此操作进行一些解释将是有帮助的,而不是公然的答案。 Thank You. 谢谢。

we have 我们有

(mymap uf lis) = (reduce f id lis) = 
 = (if (null? lis) id
     (f (car lis) (reduce f id (cdr lis))))

which must be equal to 必须等于

 = (if null? lis) '()
     (cons (uf (car lis)) (mymap uf (cdr lis))))

matching the corresponding entities, we get 匹配相应的实体,我们得到

id == '()

and, since (mymap uf lis) = (reduce f id lis) , it is also (mymap uf (cdr lis)) = (reduce f id (cdr lis)) , so we have 并且,由于(mymap uf lis) = (reduce f id lis) ,所以它也是(mymap uf (cdr lis)) = (reduce f id (cdr lis)) ,所以我们有

(f x y) = (cons (uf x) y)

Thus, we define 因此,我们定义

(define (mymap uf xs)   ; multiple `x`-es :)
  (reduce (lambda (x r)
             (cons .... r))
          '()
          xs ))

your reduce is a right fold : its combining function receives an element x of the argument list xs , and the recursive result of working on the rest of list, as r . 你的reduce是一个正确的选择 :它的合并函数接收参数列表xs的元素x ,以及处理列表的其余部分的递归结果,如r

r has all the elements of the rest of xs , which were already mapped through uf . r具有xs其余部分的所有元素,这些元素已通过uf映射。 All that's left to do to combine the given element x with this recursive result r , is to cons the (uf x) onto r . 所有剩下要做给定元素结合x这个递归结果rcons(uf x)r

It should pose no problem now to complete the definition by writing the actual code in place of the dots .... there. 现在,通过写实际代码代替点....来完成定义,应该没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM