I have just picked up John Hughes' essay Why Functional Programming Matters, and i'm trying to follow along using 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))))))
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
.
The motivating example is doubleall = reduce doubleandcons nil
, where 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)
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.
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?