Я играю с красно-черным деревом:
-- Taken from Okasaki 1999
module RedBlackTree where
--node coloring data
--a node is R (red) or B (black)
data Color = R | B
--tree constructor
--a RBT can be E (empty) or be T (a non empty tree)
data RBT e = E | T Color (RBT e) e (RBT e)
--set operations on tree
type Set a = RBT a
--define an empty set
empty :: Set e
empty = E
--define a member of a set
--Sees if an item of type e is
--in a set if type e elements
member :: (Ord e) => e -> Set e -> Bool
member x E = False
member x (T _ a y b) | x < y = member x a -- if less, go left
| x == y = True
| x > y = member x b -- if more, go right
--tree operations
--Insert an element
insert :: (Ord e) => e -> Set e -> Set e
insert x s = makeBlack (ins s)
where ins E = T R E x E --basically the typical BST insert
ins (T color a y b) | x < y = balance color (ins a) y b
| x == y = T color a y b
| x > y = balance color a y (ins b)
makeBlack (T _ a y b) = T B a y b --inserts a black node
-- balance operations
--case 1:
balance B (T R (T R a x b) y c) z d = T R (T B a x b) y (T B c z d)
--case 2:
balance B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d)
--case 3:
balance B a x (T R (T R b y c) z d) = T R (T B a x b) y (T B c z d)
--case 4:
balance B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d)
--generic balancing operation
balance color a x b = T color a x b
Если я выполню следующий оператор в GHCi:
> RedBlackTree.insert ('b') (RedBlackTree.T R E ('a') E)
Следующее сообщение об ошибке говорит мне, что нет экземпляра шоу для Set Char
:
<interactive>:116:1:
No instance for (Show (Set Char)) arising from a use of `print'
Possible fix: add an instance declaration for (Show (Set Char))
In a stmt of an interactive GHCi command: print it
Я знаю, что дерево работает, потому что при вызове member 'b' ...
, где ...
— ранее выполненный оператор, возвращается значение True
. Я читал другие сообщения SO по этой проблеме, но для них были найдены решения (например: Haskell: вывод Show для пользовательского типа) не работает.
Например, добавив:
instance Show Set where:
show (Set Char) = show Char
Я получаю следующее сообщение об ошибке, когда пытаюсь загрузить с помощью :l
:
:l red-black-tree.hs [1 из 1] Компиляция RedBlackTree (red-black-tree.hs, интерпретируется)
red-black-tree.hs:54:11: Not in scope: data constructor `Set'
red-black-tree.hs:54:15: Not in scope: data constructor `Char'
red-black-tree.hs:54:28: Not in scope: data constructor `Char'
Failed, modules loaded: none.
Я думаю, что есть несколько проблем с тем, что я пытаюсь сделать, но я не могу понять это из доступной документации.
data Tree a = ... deriving (Show)
- person bheklilr   schedule 29.08.2013deriving (Show)
в конецdata RBT...
дает мне следующее сообщение об ошибке:No instance for (Show Color) arising from the 'deriving' clause of a data type declaration
- person Joe   schedule 29.08.2013deriving (Show)
в конецdata Color = R | B
- person nponeccop   schedule 29.08.2013