• Home
  • Textbooks
  • Programming in Haskell
  • Declaring types and classes

Programming in Haskell

Graham Hutton

Chapter 8

Declaring types and classes - all with Video Answers

Educators


Chapter Questions

01:41

Problem 1

In a similar manner to the function add, define a recursive multiplication function mult :: Nat $\rightarrow$ Nat $\rightarrow$ Nat for the recursive type of natural numbers:
Hint: make use of add in your definition.

Prathan Jarupoonphol
Prathan Jarupoonphol
Numerade Educator

Problem 2

Although not included in appendix $B$, the standard prelude defines
data Ordering $=$ LT $\mid$ EQ $\mid$ GT
together with a function
compare :: ord a $\Rightarrow$ a $\rightarrow$ a $->$ ordering
that decides if one value in an ordered type is less than ( $\mathrm{LT})$, equal to $(\mathrm{EQ})$, or greater than (GT) another value. Using this function, redefine the function occurs :: ord $a \Rightarrow a \rightarrow$ Tree a $\rightarrow$ Bool for search trees. Why is this new definition more efficient than the original version?

Check back soon!

Problem 3

Consider the following type of binary trees:
data Tree a = Leaf a | Node (Tree a) (Tree a)
Let us say that such a tree is balanced if the number of leaves in the left and right subtree of every node differs by at most one, with leaves themselves being trivially balanced. Define a function balanced : : Tree a $\rightarrow$ Bool that decides if a binary tree is balanced or not.

Check back soon!

Problem 4

Define a function balance :: [a] $\rightarrow$ Tree a that converts a non-empty list into a balanced tree. Hint: first define a function that splits a list into two halves whose length differs by at most one.

Check back soon!
06:18

Problem 5

Given the type declaration
data Expr = Val Int I Add Expr Expr
define a higher-order function
folde $::($ Int $\rightarrow$ a) $\rightarrow(a->a->a)-\operatorname{Expr}-$
$>a$
folde :: (Int $\rightarrow$ a) $\rightarrow(a->a->a)->$ Expr -
$>a$
such that folde $\mathrm{f} g$ replaces each val constructor in an expression by the function $f$, and each Add constructor by the function $g$.

Chris Trentman
Chris Trentman
Numerade Educator
06:18

Problem 6

Using folde, define a function eval :: Expr $\rightarrow$ Int that evaluates an expression to an integer value, and a function size :: Expr $\rightarrow$ Int that calculates the number of values in an expression.

Chris Trentman
Chris Trentman
Numerade Educator
00:16

Problem 7

Complete the following instance declarations:
instance Eq a $=$ Eq (Maybe a) where
...
instance Eq a $=>$ Eq [a] where

Brandon Fox
Brandon Fox
Numerade Educator

Problem 8

Extend the tautology checker to support the use of logical disjunction $(\vee)$ and equivalence $(\Leftrightarrow)$ in propositions.

Check back soon!
00:40

Problem 9

Extend the abstract machine to support the use of multiplication.

Sheryl Ezze
Sheryl Ezze
Numerade Educator