Reputation: 11
A ternary tree type is defined as:
datatype ’a tree =
Leaf of ’a
| Node of ’a tree * ’a tree * ’a tree
I need to modify functions map & foldl to match the ternary tree...
fun tree_map (f : ’a -> ’b) (t : ’a tree) : ’b tree =
f,nil) = nil
| map (f,x::xs) = f(x) :: (map (f,xs))
fun tree_foldl (f : ’a * ’a -> ’a) (n: ’a) (t : ’a tree) : ’a =
(f,ie,nil) = ie
| foldl (f,ie,x::xs) = foldl (f, f(x,ie), xs);
I know this is probably a simple modification, but I can't seem to wrap my head around the logic. I don't understand how it would be different for a binary tree...any pointers?
Upvotes: 1
Views: 207
Reputation: 66371
A good starting point when defining a function over an algebraic data type is to have one "match pattern" for each case.
I would start like this, since the base cases are (fairly) obvious:
fun tree_map f (Leaf x) = Leaf (f x)
| tree_map f (Node (t1, t2, t3)) = Node (something involving t1, t2, and t3)
fun tree_foldl f ie (Leaf x) = f(ie, x)
| tree_foldl f ie (Node (t1, t2, t3)) = ... something involving t1, t2, and t3 ...
The interesting bits are left as an exercise.
Upvotes: 4