
Am Donnerstag, 12. Februar 2009 16:19 schrieb Alan Cameron:
I am baffled by what the correct solution to the exercises in Recursive type section of Chapter 3 should be. <Quote> 1. Write the converse of fromList for the List type: a function that takes a List a and generates a [a].
Follow the example of fromList, pattern match on the constructors of the List type and specify for each case what to do (there's only one sensible choice) toList (Cons x xs) = ... toList Nil = ...
2. Define a tree type that has only one constructor, like our Java example. Instead of the Empty constructor, use the Maybe type to refer to a node's children. </Quote>
You know the Maybe type: data Maybe a = Nothing | Just a , don't you? If the Java example is what I expect it to be, you just replace the null reference with Nothing and a non-null subtree with (Just subtree).
fromList is defined in listADT.hs thus
-- file: ch03/ListADT.hs fromList (x:xs) = Cons x (fromList xs) fromList [] = Nil
Tree is defined in Tree.hs thus
-- file: ch03/Tree.hs data Tree a = Node a (Tree a) (Tree a)
| Empty
deriving (Show)
At this point in the book I fail to find any previous examples which might lead me to my own solution and there are no "Answers to Exercises" as far as I can see. I have a feeling that this might be a fundamental piece of knowledge to assist me in further reading of the book.
Alan Cameron
I hope the above hints help you find the solutions yourself, if not, I could go into more detail. Cheers, Daniel