Problem set 2. Due Wednesday February 8th at 11:59pm

Starting code for the problem set:


(ns traverse
  (:require clojure.test))

(use 'clojure.repl)
(use 'clojure.test)

;; traverse returns a function that can be used
;; as map, filter, etc
(defn traverse [combine op seed]
  (fn [x] (if (empty? x) 
            seed
            (combine (op (first x)) ((traverse combine op seed) (rest x))))))

(def mapsquare (traverse cons #(* %1 %1) []))
(def sumlist (traverse + (fn [x] x) 0))



(deftest test-mapsquare 
  (is (= (mapsquare []) []))
  (is (= (mapsquare [2 3 4]) [4 9 16]))
)

(deftest test-sumlist
  (is (= (sumlist []) 0))
  (is (= (sumlist [1 2 3]) 6))
)

Problem 1 (12 points)

Using traverse, define and test the following functions:

Problem 2 (8 points)

Write a function nested-traverse that works just like traverse, except it traverses collections with sub-collections of arbitrary nesting, such as this one:


[2 [3 4] 1 [[4]]]

For simplicity you may assume that all your collections are vectors.

nested-traverse should be used exactly as traverse: when provided the functions combine and op and a seed, it returns a function that traverses the nested collection, applying op to every element, combining the results using combine, and returning seed for every empty collection.

Use the function coll? to check if an element is a collection.

Below are two examples of using nested-traverse that may be used as test cases (more test cases are needed).


(def nested-mapsquare (nested-traverse cons #(* %1 %1) []))

(deftest test-nested-mapsquare 
  (is (= (nested-mapsquare []) []))
  (is (= (nested-mapsquare [2 3 4]) [4 9 16]))
  (is (= (nested-mapsquare [2 [3 4] 1 [[4]]]) [4 [9 16] 1 [[16]]]))
)

(def nested-sumlist (nested-traverse + (fn [x] x) 0))

(deftest test-nested-sumlist
  (is (= (nested-sumlist []) 0))
  (is (= (nested-sumlist [1 2 3]) 6))
  (is (= (nested-sumlist [2 [3 4] 1 [[4]]]) 14))
)

Submit your function and all your test cases.

Problem 3 (9 points)

Using nested-traverse, define and test the following three functions:

Problem 4 (6 points)

Exercise 3.2 parts a,b p. 40-41.


UMM CSci 4651