forming cross products
problem
- given two lists, p and q, form the list consisting of all pairs pi.qjin order, where pi is the ith element of p and qj is the jth element of q
prelude: apply
- (apply op l) applies the procedure op to the arguments given by the list l
- (apply + ‘(1 2 3)) ==> 6
a neat solution
- first make a list from p by pairing each of its elements with all the elements of q(define (tensor p q) (map (lambda (pi) (map (lambda (qj) (cons pi qj)) q) p)
- now append all the resulting lists together(define (cross p q) (apply append (tensor p q)))
puzzle
- can you generalize this so that rather than just pairing pi and qj it applies someprocedure proc, giving a list of the results of evaluating (proc pi qj)?
- can you eliminate all pairings that give a result satisfying some property? (example: proc is *, drop all zeros)