SolutionPS5

# SolutionPS5 - Com S 342 Spring 2007 Dr Markus Lumpe Problem...

This preview shows pages 1–4. Sign up to view the full content.

Com S 342 Spring 2007 Dr. Markus Lumpe 1 Problem Set 5: Data Types Problem 1 Define the predicate (list-of? pred ) that, when applied to an argument pred , returns a procedure that takes a list as argument. For example, > (define list-of-numbers? (list-of? number?)) > (list-of-numbers? ‘(1 2 3 4 5)) #t > (define list-of-symbols? (list-of? symbol?)) > (list-of-symbols? ‘(a b c d)) #t > (list-of-symbols? ‘(a 2 c 3)) #f Thus, (list-of? pred ) has to return a procedure that when applied to a list returns #t if the application of pred to all elements in that list returns #t . Otherwise, this procedure has to returns #f . Solution: (define fold-left (lambda (f e lst) (if (null? lst) e (fold-left f (f e (car lst)) (cdr lst)) ) ) ) (define list-of? (lambda (pred) (lambda (lst) (fold-left (lambda (x y) (and x (pred y))) #t lst) ) ) ) 20

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Com S 342 Spring 2007 Dr. Markus Lumpe 2 Problem 2 Consider the following BNF specification: <bin-search-tree> ::= () | ( <string> <bin-search-tree> <bin-search-tree> ) The procedure (path-to-key key bst ) , where key is a string and bst is a binary search tree that contains the string key , returns a list of the symbols left and right showing how to find the node that contains the string key . If the string key is found at the root, it returns the empty list. You can use the built-in Scheme string predicates (string<? string 1 string 2 ) and (string>? string 1 string 2 ) to implement the procedure path-to-key . For example, (path-to-key "R" '("Q" ("H" () ("O" () ())) ("W" ("T" ("R" () ()) ()) ("Z" () ())))) returns (right left left) Solution: ; PathToKey.scm ; key is an element of the bst (define path-to-key (lambda (key bst) (if (null? bst) '() (if (equal? (car bst) key) '() (if (string<? (car bst) key) (cons 'right (path-to-key key (caddr bst))) (cons 'left (path-to-key key (cadr bst))) ) ) ) ) ) 20
Com S 342 Spring 2007 Dr. Markus Lumpe 3 Problem 3 Consider the following BNF specification: <Stack> ::= () | ( <SchemeValue> <Stack> ) Using the define-datatype abstraction, define the abstract syntax of data

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 8

SolutionPS5 - Com S 342 Spring 2007 Dr Markus Lumpe Problem...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online