-- Binary Search tree
data Tree a = Empty
| Node a (Tree a) (Tree a)
deriving (Eq, Ord, Show)
leaf :: a -> Tree a
leaf x = Node x Empty Empty
insert :: (Ord a) => Tree a -> a -> Tree a
insert Empty x = leaf x
insert (Node x l r) y = case compare y x of
GT -> Node x l (insert r y)
_ -> Node x (insert l y) r
t1 :: Tree Int
t1 = Node 4 (leaf 3) (Node 7 (leaf 5) (leaf 10))
main = do
insert t1 8
Run Code Online (Sandbox Code Playgroud)
错误信息:
{-
Couldn't match expected type `IO b0' with actual type `Tree a0'
In the return type of a call of `insert'
In a stmt of a 'do' block: insert t1 8
-}
Run Code Online (Sandbox Code Playgroud)
您的 main函数是类型,Tree Int而编译的Haskell程序必须具有Type IO a.
您可以将转换Tree Int值IO (Tree Int)与return :: a -> IO a(签名简化了您的情况):
main :: IO (Tree Int)
main = do
return (insert t1 8)
Run Code Online (Sandbox Code Playgroud)
但是,这不会向控制台打印任何内容,因为它只是将树作为值返回.要打印您可以使用的结果print :: Show a => a -> IO ()
main :: IO ()
main = do
print (insert t1 8)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1404 次 |
| 最近记录: |