Beginning Haskell - getting “not in scope: data constructor” error

后端 未结 3 1652
半阙折子戏
半阙折子戏 2021-02-05 06:17

I\'m going through the problems in the Haskell O\'Reilly book. The problem I am working on is

Using the binary tree type that we defined earlier in this chapter         


        
3条回答
  •  甜味超标
    2021-02-05 06:25

    Your code is wrong, on several levels. It looks like you misunderstood algebraic data types.

    • The type signature is wrong, a Tree is always a Tree of a specific type - which you called a in its declaration, and which may be any type (since you didn't constraint it). So heigth has to take a Tree of some type - a Tree SomeType, too. You can and should use the most generic type for SomeType, i.e. a type variable like a.
    • When pattern matching, you name a specific constructor - Node a (Tree a) (Tree a) or Empty - to match against, not against the type as a whole. So height (Node ...) would match a Node, height (Empty) would match a Empty, and height (Tree ...) would try to match a constructor named Tree, but there is none. That's the error message you recieve.
    • You never ever compare (via ==) with a Constructor. It would actually work if you wrote deriving (Show, Eq). But you should use pattern matching to determine if you reached an Empty
    • Which leads to: You're only matching Node, not Empty - you should add a clause for Empty.
    • Also, your function still returns 0 for all inputs if you fix all the above issues. You never return anything but 0 or the max of the childrens' height - which can, in turn, only return 0 or the max of their childrens' height, etc ad infinitum. You have to increment the result at each level ;)

提交回复
热议问题