[英]Haskell - Couldn't match type [] with IO
I am new at Haskell. 我是Haskell的新人。 Why am I getting the error message 为什么我收到错误消息
(Couldn't match type '[]' with 'IO' — Haskell) in folowing code. (无法在下面的代码中将类型'[]'与'IO' - Haskell匹配。
In main I only need time of algorithm running without the result. 在主要方面,我只需要运行算法的时间而没有结果。
Only want to measure algorithm time. 只想测量算法时间。
qsort1 :: Ord a => [a] -> [a]
qsort1 [] = []
qsort1 (p:xs) = qsort1 lesser ++ [p] ++ qsort1 greater
where
lesser = [ y | y <- xs, y < p ]
greater = [ y | y <- xs, y >= p ]
main = do
start <- getCurrentTime
qsort1 (take 1000000 $ randomRs (1, 100000) (mkStdGen 42))
end <- getCurrentTime
print (diffUTCTime end start)
Your main
function isn't right. 你的main
功能是不对的。 Unless qsort1
is an IO
action you cannot perform it in an IO monad. 除非qsort1
是IO
操作,否则无法在IO monad中执行它。 Instead you can put it in the let binding: 相反,你可以把它放在let绑定中:
main = do
start <- getCurrentTime
let x = qsort1 (take 1000000 $ randomRs ((1 :: Int), 100000) (mkStdGen 42))
end <- getCurrentTime
print (diffUTCTime end start)
Also note that I have explicitly given a type annotation for 1
to avoid some compile errors. 另请注意,我已明确给出了1
的类型注释,以避免一些编译错误。
But that being said you cannot actually find the the total time taken to do the sorting because of lazy evaluation. 但话虽如此,由于懒惰的评估,你实际上无法找到进行排序所需的总时间。 x
will never be computed because it's never used in the program. x
将永远不会被计算,因为它从未在程序中使用过。 If you run main
, it give you this output which is definetly wrong: 如果你运行main
,它会给你这个绝对错误的输出:
λ> main
0.000001s
Instead you can use this to calculate the computation: 相反,您可以使用它来计算计算:
main = do
start <- getCurrentTime
let x = qsort1 (take 1000000 $ randomRs ((1 :: Int), 100000) (mkStdGen 42))
print x
end <- getCurrentTime
print (diffUTCTime end start)
Instead of printing, you can also use the BangPatterns
extension to force the computation of qsort1
:您也可以使用 BangPatterns
扩展来强制计算qsort1
,而不是打印:
main = do start <- getCurrentTime let !x = qsort1 (take 1000000 $ randomRs ((1 :: Int), 100000) (mkStdGen 42)) end <- getCurrentTime print (diffUTCTime end start)
BangPatterns
will not lead to full evaluation as @kosmikus points out. BangPatterns
不会导致全面的评估为@kosmikus指出。 Instead use a library like criterion
which has been specially made for benchnmarking. 而是使用像专门用于技术标记的criterion
库。
I used method below and it works fine: 我使用下面的方法,它工作正常:
main = do
let arr = take 1000000 $ randomRs ((1 :: Int), 10000000) (mkStdGen 59)
defaultMain [
bgroup "qs" [ bench "1" $ nf quickSort arr ]
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.