Wednesday, January 18, 2006

Lists and Maps

Lists and Maps

The simplest way to define a list is

(define a-list '(1 2 3 4 5 6 7 8))

If we want a function that works on each member of this list, then we will have to make use of the map inbuilt function.
Here is a function that adds 1 to each member of a list and then returns that list

(define (add-one n)
(+ n 1))

(map add-one a-list)

We can play around a bit more with map
Let us define a function that adds a fixed number to a-list

(define (list-plus n)
(map (lambda (x)
(+ x n))
a-list))


We can refine this further to take any list and add a function that does a minus as well

(define (list-plus-n n some-list)
(map (lambda (x)
(+ x n))
some-list))

(define (list-minus-n n some-list)
(map (lambda (x)
(- x n))
some-list))


Then we can call the functions as

(list-plus-n 10 a-list)
(list-minus-n 10 a-list)


We can even make list-plus-n and list-minus-n to be wrappers for a more generic function

(define (list-plus-n n some-list)
(list-map + n some-list))

(define (list-minus-n n some-list)
(list-map - n some-list))

(define (list-map operation n some-list)
(map (lambda (x)
(operation x n))
some-list))

No comments: