有人可以在下面的代码片段中解释错误。在这段代码中,我试图在从用户那里获取输入时实现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 [];
.... }
答案 0 :(得分:1)
我在代码中看到的一些问题是:
loop
函数main
ys <- inorder numtree
,这意味着inorder
会返回IO something
,但事实并非如此。您应该使用let
代替。do
- 阻止以<-
声明结尾 - 它应以表达式结尾。