Haskell - Couldn't match type [] with IO -


i new @ haskell. why getting error message

(couldn't match type '[]' 'io' — haskell) in folowing code.

in main need time of algorithm running without result.

only want measure algorithm time.

qsort1 :: ord => [a] -> [a] qsort1 []     = [] qsort1 (p:xs) = qsort1 lesser ++ [p] ++ qsort1 greater             lesser  = [ y | y <- xs, y < p ]         greater = [ y | y <- xs, y >= p ]  main =     start <- getcurrenttime     qsort1 (take 1000000 $ randomrs (1, 100000) (mkstdgen 42))     end <- getcurrenttime     print (diffutctime end start)  

your main function isn't right. unless qsort1 io action cannot perform in io monad. instead can put in let binding:

main =     start <- getcurrenttime     let x = qsort1 (take 1000000 $ randomrs ((1 :: int), 100000) (mkstdgen 42))     end <- getcurrenttime     print (diffutctime end start)  

also note have explicitly given type annotation 1 avoid compile errors.

but being said cannot find the total time taken sorting because of lazy evaluation. x never computed because it's never used in program. if run main, give output definetly wrong:

λ> main 0.000001s 

instead can use calculate computation:

main =     start <- getcurrenttime     let x = qsort1 (take 1000000 $ randomrs ((1 :: int), 100000) (mkstdgen 42))     print x     end <- getcurrenttime     print (diffutctime end start)   

instead of printing, can use bangpatterns extension force computation of qsort1:

main =     start <- getcurrenttime     let !x = qsort1 (take 1000000 $ randomrs ((1 :: int), 100000) (mkstdgen 42))     end <- getcurrenttime     print (diffutctime end start)    

bangpatterns not lead full evaluation @kosmikus points out. instead use library criterion has been specially made benchnmarking.


Comments