Я рассматриваю проблемы в книге Хаскелла О'Рейли. Проблема, над которой я работаю, заключается в том, что
Using the binary tree type that we defined earlier in this chapter,
write a function that will determine the height of the tree. The height
is the largest number of hops from the root to an Empty. For example, the
tree Empty has height zero; Node "x" Empty Empty has height one;
Node "x" Empty (Node "y" Empty Empty) has height two; and so on.
я пишу свой код в файл с именем ch3.hs. Вот мой код:
36 data Tree a = Node a (Tree a) (Tree a)
37 | Empty
38 deriving (Show)
39
40 --problem 9:Determine the height of a tree
41 height :: Tree -> Int
42 height (Tree node left right) = if (left == Empty && right == Empty) then 0 else max (height left) (height right)
, открыв ghci в терминале и набрав: load ch3.hs. Когда я это делаю, я получаю следующую ошибку:
Prelude> :load ch3.hs
[1 of 1] Compiling Main ( ch3.hs, interpreted )
ch3.hs:42:7: Not in scope: data constructor `Tree'
Failed, modules loaded: none.
Я ожидаю, что конструктор данных Tree должен быть там, потому что я определил его в строках над методом height. Но когда я пытаюсь загрузить файл, мне говорят, что конструктор данных не находится в области видимости. Я ценю вашу помощь и объяснение, почему возникает эта ошибка. Спасибо, Кевин
Вы сопоставляете шаблон с конструкторами, т.е. случаями вашего Дерева
АТД. Дерево
— это то, что их объединяет.
Это намного проще, и, главное, правильно:
height Empty = 0
height (Node _ l r) = 1 + max (height l) (height r)