代码段中的错误

时间:2012-01-16 10:06:36

标签: haskell

有人可以在下面的代码片段中解释错误。在这段代码中,我试图在从用户那里获取输入时实现BST的inorder遍历

import System.IO

loop :: Int -> [Int] -> IO [Int]
loop 0 ls = return ls
loop n ls = do newNumber <- readLn
               loop (n-1) (newNumber:ls)

data Tree a = EmptyTree | Node a ( Tree a) ( Tree a) deriving ( Show,Read, Eq)

singleton :: a -> Tree a 
singleton x = Node x EmptyTree EmptyTree

treeInsert :: ( Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x ( Node a left right)
                    | x==a = Node x left right
                    | x<a = Node a (treeInsert x left) right
                    | x>a = Node a left (treeInsert x right)

inorder :: Tree a -> [a]
inorder EmptyTree = []
inorder (Node a left right) = inorder left ++ [a] ++ inorder right

main = do
   putStrLn " Please enter the number"
   number <- readLn :: IO Int
   putStrLn $ "The num is:" ++ show number
   xs <- loop number []
   let numtree = foldr treeInsert EmptyTree xs
   print numtree
   ys <- inorder numtree
   print ys

我得到的错误是:

Couldn't match expected type `IO t0' with actual type `[a0]'
In the return type of a call of `inorder'
In a stmt of a 'do' expression: ys <- inorder numtree
In the expression:
  do { putStrLn " Please enter the number";
       number <- readLn :: IO Int;
         putStrLn $ "The num is:" ++ show number;
       xs <- loop number [];
       .... }

1 个答案:

答案 0 :(得分:1)

我在代码中看到的一些问题是:

  1. 您正在调用未在任何地方定义或导入的loop函数
  2. 您没有缩进main
  3. 的内容
  4. 您写ys <- inorder numtree,这意味着inorder会返回IO something,但事实并非如此。您应该使用let代替。
  5. 您的do - 阻止以<-声明结尾 - 它应以表达式结尾。