Some exemple functions in SCHEME

These are some of the scheme programming examples we used in class. You can find more examples in the textbook.

(define (listlen l)
  (if (null? l) 
      0 
      (+ 1 (listlen (cdr l))))) 

(define (power x y)
  (cond ((zero? y) 1)
        ((even? y) (power (* x x) (/ y 2)))
        (else (* x (power x (- y 1))))))

(define (mapfun f l)
  (if (null? l) l
      (cons (f (car l))
            (mapfun f (cdr l)))))

(define (numbers n)
  (if (zero? n) '()
      (cons 1 (map (lambda (x) (+ 1 x))
                   (numbers (- n 1))))))

"mapfun" is the same as the predefine scheme function "map". You can use "map" in your homeworks.

Here are two more examples we will use today in class:

(define (blob1 pred list)
  (cond ((null? list) '())
        ((pred (car list))
         (blob1 pred (cdr list))) 
        (else 
         (cons (car list)
               (blob1 pred (cdr list))))))

(define (blob2 list)
  (if (null? list) '()
      (cons (car list)
            (let ((pred (lambda (x) 
                          (zero? (remainder x (car list))))))
              (blob2 (blob1 pred (cdr list)))))))

Can you guess what they do? What is the result of (blob2 (cdr (numbers 100)))?