learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-16.scm (1204B)


      1 (define-library (sicp solutions chapter-1 exercise-16)
      2   (import (scheme base)
      3           (srfi :26))
      4   (export flatten
      5           cartesian
      6           fast-expt-recursive
      7           fast-expt-iterative)
      8 
      9   (begin
     10     (define (flatten a)
     11       ;; Why...?
     12       (cond
     13        ((null? a) '())
     14        (else (append (car a) (flatten (cdr a))))))
     15 
     16 
     17     (define (cartesian a b)
     18       ;; Why...?
     19       (define (cartesian' a-element b)
     20         (cond
     21          ((null? b) '())
     22          (else (cons (cons a-element (car b))
     23                      (cartesian' a-element (cdr b))))))
     24       (cond
     25        ((null? a) '())
     26        (else (flatten (map (lambda (a-element)
     27                              (cartesian' a-element b))
     28                            a)))))
     29 
     30     (define (fast-expt-recursive b n)
     31       (cond ((= n 0) 1)
     32             ((even? n) (square (fast-expt-recursive b (/ n 2))))
     33             (else (* b (fast-expt-recursive b (- n 1))))))
     34 
     35     (define (fast-expt-iterative b n)
     36       (define (f a b n)
     37         (cond
     38          ((= n 0) a)
     39          ((even? n) (f a
     40                        (* b b)
     41                        (/ n 2)))
     42          (else (f (* a b)
     43                   b
     44                   (- n 1)))))
     45       (f 1 b n))))