Due: Friday, November 22, 2013
Read the first part of Chapter 8 of the text through the section on recursive data structures.
Create a Haskell module that defines and exports a data type Expression
with
value constructors Add
, Subtract
, Multiply
, and Divide
.
These value constructors should be parameterized to take two Expressions. You should also
define a value constructor that wraps a simple integer (call it Constant
). For
example:
Add Expression Expression | Constant Int
Your module should export a function evaluate
of type Expression ->
Int
that takes an expression and returns the integer result of evaluating it. For
example:
evaluate (Divide (Add (Constant 1) (Constant 2)) (Subtract (Constant 3) (Constant 4)))
should return -3 since (1 + 2)/(3 - 4) = -3. HINT: Use pattern matching to consider each of the possible value constructors. Your function will have to be recursive to evaluate nested structures. Your function should be able to easily handle expressions of arbitrary complexity made up of nested applications of the value constructors.
Create a Haskell module that defines and exports a data type Distance
with
parameterless value constructors Feet
, Meters
, and
Furlongs
. Your module should also export the data type
data Dimensioned = Dimensioned (Double, Distance) deriving(Show)
Your module should export three functions toFeet
, toMeters
, and
toFurlongs
that take a Dimensioned value and return the appropriately converted
result. For example:
toFeet (Dimensioned (10.0, Meters))
Should evaluate to Dimensioned (32.8, Feet)
Define a type constructor Box
that holds a single item of type
a
. Write a function boxmap
of type (a -> b) -> Box a -> Box
b
. The function should apply the given function to the item in the box and return a
new box containing the transformed result. For example:
boxmap length (Box "Hello")
Should evaluate to Box 5
Last Revised: 2024-12-17
© Copyright 2024 by Peter Chapin <peter.chapin@vermontstate.edu>