Here is our recursive definition of the
sum
function
(define (sum lst)
(cond
((null? lst) 0)
(else
(+ (car lst) (sum (cdr lst))))))
(sum '(1 4 7))
(1 + (sum '(4 7)))
(1 + (4 + (sum '(4 7))))
(1 + (4 + (7 + (sum '()))))
(1 + (4 + (7 + 0)))
(1 + (4 + 7))
(1 + 11)
12
(define (sum lst)
(define (sum-helper lst n)
(cond
((null? lst) n)
(else
(sum-helper (cdr lst) (+ (car lst) n)))))
(sum-helper lst 0))
(sum-helper '(1 4 7) 0)
(sum-helper '(4 7) 1)
(sum-helper '(7) 5)
(sum-helper '() 12)
12
Why would we ever want to do this?
Let’s simplify the
sum
function
(define (sum lst)
(apply + lst))
Let’s compose two functions
(define (compose f1 f2)
(define (composed arg1)
(f1 (f2 arg1)))
composed)
;; Last element of a list
(define last (compose car reverse))
(let ((double (lambda (x) (+ x x))))
(double 5))
;; -> 10
define
(define (double x)
(+ x x))
(define x 5)
(define double
(lambda (x)
(+ x x)))
Example Usage
(map (lambda (x) (+ x x)) '(1 4 7 9))
;; '(2 8 14 18)
Let’s implement it!
(define (map proc lst)
(cond
((null? lst) '())
(else
(cons (proc (car lst)) (map proc (cdr lst))))))
Example Usage
(filter odd? '(1 4 7 9 12))
;; '(1 7 9)
Let’s implement it!
(define (filter pred lst)
(cond
((null? lst) '())
(else
(let ((rest (filter pred (cdr lst))))
(if (pred (car lst))
(cons (car lst) rest)
rest)))))
reduce
in other languages
Example Usage
(foldl + 0 '(1 4 7))
;; 12
Let’s implement it!
(define (foldl proc init lst)
(cond
((null? lst) init)
(else
(foldl proc
(proc (car lst) init)
(cdr lst)))))