Note: late submissions will not be accepted for this assignment.
For this assignment, you will modify and add to functions that are provided for you in hw5.clj. Download this file, rename it LASTNAME-hw5.clj
and enter your name in the comment at the top. Be careful to name your functions exactly as defined in the exercises, and be sure to comment each function as to its behavior.
This map is defined in the downloaded hw5.clj file. Add the following definitions to the file.
molecular-weight1
, rename it molecular-weight2
, and modify it to handle lists in which an element may be followed by a number. For example, (molecular-weight2 '(:H 2 :O)) should evaluate to 18.0154. molecular-weight2
, rename it molecular-weight3
, and modify it to handle nested lists. For example, (molecular-weight3 '((:C :H 3) 2 :C :H :O :H)) should evaluate to 60.0964. In class, we discussed how structured lists could be used to represent binary trees. For example, the following lists represent a tree of animal names (strings) and a tree of numbers, respectively.
Several utility functions (root
, left-subtree
,
and right-subtree
) are provided for you in hw5.clj. Add the following functions for manipulating arbitrary binary trees.
count-keywords
that takes one input, a list
representing a binary tree, and returns the number of keywords that are stored in the tree.
For example, (count-keywords ANIMALS)
should
evaluate to 6
.count-func
that generalizes the count-keywords
function by adding a second input: a predicate function (i.e., one that returns true/false). The count-func
function should return a count of how many items in the tree evaluate to true using the predicate function. For example, (count-func keyword? ANIMALS)
should behave the same as count-keywords
from the previous exercise. Similarly, (count-func pos? NUMBERS)
should return 2.map
function takes a function and maps it to a list of values. For example, (map inc '(1 3 5))
would evaluate to (2 4 6)
. Define a a function named tree-map
that similar maps a function to a tree structure. For example, the call (tree-map inc NUMBERS)
would produce the tree (3 (0 () ()) (4 () ()))
. In class, we discussed how Clojure allows for the definition of classes via protocols and type definitions. For example, consider the following definitions for implementing a Coin class (also in hw5.clj).
For example:
count-heads
function from the lectures to utilize the above "class." Recall that this function takes one input, the number of flips, and returns the number of heads obtained. For example, (count-heads 1000)
should return a number close to 500. As before, this function must utilize tail-recursion. Note: a single coin object should be created and used appropriately for the repeated flips. flip-until-heads
that simulates repeated flips of a coin until heads is obtained, prints the value of each flip, and returns the number of flips. For example, (flip-until-heads)
might produce the following: