以下是树的代码。
import Control.Exception
import Control.Monad
import Control.DeepSeq
import qualified Data.List as List
import Test.HUnit
data Tree a = Empty
| Node a (Tree a) (Tree a)
deriving (Show, Eq)
insertTree :: ( Ord a, Show a ) => Tree a -> a -> Tree a
insertTree Empty x = Node x Empty Empty
insertTree ( Node v tLeft tRight ) x
| x == v = Node v tLeft tRight
| x < v = Node v (insertTree tLeft x) tRight
| x > v = Node v tLeft (insertTree tRight x)
createTree :: ( Ord a, Show a ) => [ a ] -> Tree a
createTree = foldl insertTree Empty
member:: ( Ord a, Show a ) => Tree a -> a -> Bool
member Empty x = False
member (Node v tLeft tRight ) x
| x == v = True
| x < v = member tLeft x
| x > v = member tRight x
intTree = createTree [ 9, 7, 2, 8, 6, 0, 5, 3, 1 ]
listTree = createTree ( List.permutations [ 0 .. 3 ] )
strTree = createTree [ "hello"
, "world"
, "lorem"
, "ipsum"
, "dolor"
, "sit"
, "amet"
]
我的代码基本上看看一个元素是否包含在树中。
当我运行我的代码
例如:ghci.> member 5 intTree
我得到一个错误没有实例(Ord(Tree a0))。
我想知道如何解决这个问题。任何帮助是极大的赞赏。
答案 0 :(得分:5)
no instance for ...
错误几乎总是因为你在错误的地方得到了你的论点。不幸的是,Possible fix: add an instance for...
建议通常是错误的。
在这种情况下,因为member:: ( Ord a, Show a ) => Tree a -> a -> Bool
,它首先想要树,然后是元素,所以你需要尝试member intTree 5
而不是member 5 intTree
。