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))
)
Using traverse, define and test the following functions:
count
to count the elements in a collection (make sure to test it on non-integers)remove5
to remove all 5s from a collection of numbers, return a vector.countChars
to take a collection of strings and return a vector of lengths of these strings.reverse
to reverse a collection; return a vector.
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.
Using nested-traverse
, define and test the following three
functions:
nested-reverse
that reverses every collection, but
otherwise preserves the nested structure. For instance, for the
nested [2 [3 4] 1 [[4]]]
it returns [[[4]] 1 [4
3] 2]
nested-flatten
that returns a one-dimensional vector
of all elements in a nested structure in the order in which they are
encountered. For the same example the result is [2 3 4 1
4]
.nested-reverse-flatten
that flattens the collection
into a vector while reversing the order of the elements. The result
for the above example is [4 1 4 3 2]
.Exercise 3.2 parts a,b p. 40-41.