Sunday, June 8, 2008

EoPL - Ch 1 - Ex 15

Exercise 15 in Chapter 1 of Essentials of Programming Languages attempts to familiarize the reader with programming in the Scheme. It's split into ten parts that together provide a gentle introduction to working with lists, and to a lesser extent vectors, in a functional programming language.

Ex. 15, Pt. 1
Define a function duple : (n : int) * (x : 'a) -> ['a] that returns a list containing n copies of x. Solution.

Ex. 15, Pt. 2
Define a function invert : (lst : [('a,'b)]) -> [('b,'a)] that returns a list like lst but with each pair element of reversed. Solution.

Ex. 15, Pt. 3
Define a function filter-in : (pred : 'a -> bool) * (lst : ['a]) -> ['a] that returns a list of the elements in lst for which pred succeeds. Solution.

Ex. 15, Pt. 4
Define a function every? : (pred : 'a -> bool) * (lst : ['a]) -> bool that returns false if pred fails for any element of lst, or otherwise returns true. Solution.

Ex. 15, Pt. 5
Define a function exists? : (pred : 'a -> bool) * (lst : ['a]) -> bool that returns true if pred succeeds for any element of lst, or otherwise returns false. Solution.

Ex. 15, Pt. 6
Define a function vector-index : (pred : 'a -> bool) * (v : #['a]) -> int|FALSE that returns the zero-based index of the first element in v for which pred succeeds, or returns false if no such element exists. Solution.

Ex. 15, Pt. 7
Define a function list-set : (lst : ['a]) * (n : int) * (x : 'a) -> ['a] that returns a list similar to lst, except that the n-th (using zero-based indexing) element is replaced with x. Solution.

Ex. 15, Pt. 8
Define a function product : (los1 : ['a]) * (los2 : ['b]) -> [('a, 'b)] that returns a list of pairs (in any order) that represents the Cartesian product of los1 and los2. Solution.

Ex. 15, Pt. 9
Define a function down : (lst : [_]) -> [[_]] that returns a list like lst but with each element wrapped in its own (single-element) list. Solution.

Ex. 15, Pt. 10
Define a function vector-append-list : (v : #['a]) * (lst : ['a]) -> #['a] that returns a new vector with the elements of v followed by the elements of lst. Do not use any built-in vector-to-list, list-to-vector, or append functions. Solution.

No comments: