2012-01-16 139 views
-2

有人可以請解釋在下面的代碼片段中的錯誤。在此代碼中,我試圖執行BST的序遍歷,同時從用戶以輸入錯誤的代碼片段

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 []; 
     .... } 
+3

如果編譯器給你一個錯誤,添加錯誤消息的問題。如果不是,請解釋您希望代碼執行的內容以及實際執行的內容。 – interjay 2012-01-16 10:08:03

+1

請不要問(幾乎)在同一個問題又一遍。你能指望什麼? SO不是一個由人類提供支持的分佈式編譯器。有人可以關閉這個問題嗎? – Andre 2012-01-16 10:21:43

回答

1

一些問題,我的代碼看到的是:

  1. 你調用一個函數loop你沒有定義或進口任何地方
  2. 你沒有縮進的的內容
  3. 你寫ys <- inorder numtree,這意味着inorder返回IO something,但它不。您應該使用let
  4. do - 嵌段與<- assignemnt結束 - 它應該用表達結束。
+3

@ user1145428:你怎麼能指望我們來回答如果代碼是不完整的,你甚至不會告訴我們什麼是錯的? – interjay 2012-01-16 10:18:30

+1

對不起所有人..下次我會明確提出整個問題 – 2012-01-16 10:23:29