module Main where
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x : xs) = qsort smaller ++ [x] ++ qsort larger
where
smaller = [a | a <- xs , a <= x]
larger = [a | a <- xs , a > x]
main = do qsort [1,3,2]
我收到以下错误
Couldn't match expected type `IO t0' with actual type `[a0]'
In the expression: main
When checking the type of the function `main'
我做错了什么?
答案 0 :(得分:22)
do
块中的所有函数必须与返回的monadic值匹配。你可以改为写
main = do
print (qsort [1, 3, 2])
因为print
返回IO
值。同样,如果您使用Maybe
monad,则必须执行类似
-- lookup :: Eq k => k -> [(k, v)] -> Maybe v
-- listToMaybe :: [a] -> Maybe a
firstElementOf :: Eq q => k -> [(k, [v])] -> Maybe v
firstElementOf key assocMap = do
v <- lookup key assocMap
first <- listToMaybe v
return first
这是有效的,因为lookup
和listToMaybe
都返回Maybe
,这是do
块的返回值,由{{1}的类型签名指定}}
查看firstElementOf
的类型,它只会返回qsort
,而不是[a]
,因此无法直接在IO something
的do块中使用。您还可以使用main
:
let