Wednesday, July 9, 2008

EoPL - Ch 1 - Ex 18

Exercise 18 in Chapter 1 of Essentials of Programming Languages is our last Scheme introductory programming exercise. It broaches the topic of function composition.

Ex. 18, Pt. 1
Define a function compose : (f1 : 'b -> 'c) * (f2 : a' -> b') -> 'c that returns the composition of the functions f1 and f2, such that ((compose f g) x) is equivalent to (f (g x)). Solution.

Ex. 18, Pt. 2
Define a function car&cdr : (s : 'a) * (slist : ['a]) * (errvalue: 'b) -> [_] that returns an expression which, when evaluated, produces a function in turn. This expression should be comprised of car, cdr, and compose (see Pt. 1) applications only. The function generated by this expression, when given a list similar to slist, should return the element in the given list that is at the same position as the first occurrence of s in slist. If slist does not contain an instance of s, car&cdr should return errvalue instead of an expression. Solution.

Ex. 18, Pt. 3
Define a function car&cdr2 : (s : 'a) * (slist : ['a]) * (errvalue: 'b) -> [_] that returns an expression which, when evaluated, produces a function in turn. This expression should be comprised of car and cdr applications, and lambda expressions only. The function generated by this expression, when given a list similar to slist, should return the element in the given list that is at the same position as the first occurrence of s in slist. If slist does not contain an instance of s, car&cdr2 should return errvalue instead of an expression. Solution.

No comments: