display | more...
Prev Up Next

A special kind of iteration involves repeating the same action for each element of a list. Scheme offers two procedures for this situation: map and for-each.

The map procedure applies a given procedure to every element of a given list, and returns the list of the results. Eg,

(map add2 '(1 2 3))
=> (3 4 5)

The for-each procedure also applies a procedure to each element in a list, but returns void. The procedure application is done purely for any side-effects it may cause. Eg,

(for-each display
  (list "one " "two " "buckle my shoe"))

has the side-effect of displaying the strings (in the order they appear) on the console.

The procedures applied by map and for-each need not be one-argument procedures. For example, given an n-argument procedure, map takes n lists and applies the procedure to every set of n of arguments selected from across the lists. Eg,

(map cons '(1 2 3) '(10 20 30))
=> ((1 . 10) (2 . 20) (3 . 30))

(map + '(1 2 3) '(10 20 30))
=> (11 22 33)

Prev Up Next

Log in or register to write something here or to contact authors.