Real World Haskell Chapter 3 excercise: Binary Tree with 1 value constructor

这一生的挚爱 提交于 2020-01-14 07:51:09

问题


Chapter 3 defines the following recursive type to represent a binary tree:

data Tree a = Node a (Tree a) (Tree a)
            | Empty
              deriving (Show)

The exercise requires I implement the same type using a single value constructor, using the "Maybe" type to refer to child nodes:

(From Chapter 3 Exercise 2 on page 60)

"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."

The solution I came up with is the following:

data AltTree a = AltNode a (Maybe (AltTree a)) (Maybe (AltTree a))
                 deriving (Show)

However, this does not allow for a tree containing other empty trees, such as:

AltNode 1 (AltNode 2 Nothing Nothing) (AltNode 3 Nothing Nothing)

And I'm not sure why, is "Nothing" not a value constructor for the "Maybe" type?


回答1:


It's not the Nothing value constructor which causes your error. You two branches you pass to the top-level tree should have type Maybe (AltTree a), but both (AltNode 2 Nothing Nothing) and (AltNode 3 Nothing Nothing) have type AltTree Int. You have to use Just value constructor to create values of Maybe type from them. Like

AltNode 1 (Just (AltNode 2 Nothing Nothing)) (Just (AltNode 3 Nothing Nothing))


来源:https://stackoverflow.com/questions/6613871/real-world-haskell-chapter-3-excercise-binary-tree-with-1-value-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!