根据reduce定义地图

根据reduce定义地图

本文介绍了根据reduce定义地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了约翰·休斯(John Hughes)的文章为什么函数式编程很重要,而我正在尝试使用Scheme.

I have just picked up John Hughes' essay Why Functional Programming Matters, and i'm trying to follow along using Scheme.

他定义的第一个高阶函数是reduce,我在Scheme中定义如下:

The first higher order function he defines is reduce, which i've defined in Scheme as follows:

(define u-reduce
  (lambda (ff init lst)
    (if (null? lst)
      init
      (ff (car lst) (u-reduce ff init (cdr lst))))))

我可以使用此功能在文章中重新创建reduce的某些应用程序,但是在从reducemap的过程中,事情分崩离析.

I can re-create some of the applications of reduce in the essay using this function, however things break apart in the move from reduce to map.

激励示例是doubleall = reduce doubleandcons nil,其中doubleandcons num list = cons (2*num) list.

我不确定如何将其转换为方案.我可以看到可以通过以下方式获得目标结果:

I am not sure how to translate this into scheme. I can see that the target result can be made with:

(define doubleandcons
  (lambda (lst)
    (if (null? lst)
      '()
      (cons (* 2 (car lst)) (doubleandcons (cdr lst))))))

(doubleandcons '(1 2 3))
> (2 4 6)

但是看不到要传递给reduce的内容是什么,以使其成为列表的每个元素的两倍-可能是因为我一直跳转到map的版本(请参见下面的u-map)作为该问题的解决方案.

However can not see what to pass to reduce to get it to double each element of a list - perhaps because i keep jumping to a version of map (see u-map below) as the solution to the problem.

我可以看到init = '(),但是没有什么函数可以传递到ff位置,以使u-reduce的行为类似于u-map.

I can see that init = '(), but not what function to pass in to the ff place to make u-reduce behave like u-map.

(define u-map
  (lambda (ff lst)
    (if (null? lst)
      '()
      (cons (ff (car lst)) (u-map ff (cdr lst))))))

(u-map (lambda (x) (* 2 x)) '(1 2 3))
> (2 4 6)

这可能吗?还是我错过了要点?

Is this possible? Or perhaps i'm missing the point?

推荐答案

(define u-map
  (lambda (ff lst)
    (reduce (lambda (x y) (cons (ff x) y)) '() lst)))

在列表中折叠不利之处可为您提供该列表的副本.

Folding cons across a list gives you a copy of that list.

这篇关于根据reduce定义地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!