module Main where
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x : xs) = qsort smaller ++ [x] ++ qsort larger
where
small
All functions within a do
block must match the monadic value being returned. You could instead write
main = do
print (qsort [1, 3, 2])
Because print
returns an IO
value. Similarly, if you were using the Maybe
monad, you would have to do something like
-- 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
This works because lookup
and listToMaybe
both return a Maybe
, which is the return value of the overall do
block as specified by the type signature of firstElementOf
.
Looking at the type of qsort
, it only returns [a]
, not IO something
, so it can't be used directly inside main
's do block. You could also assign it's returned value to a name using let
:
main = do
let result = qsort [1, 3, 2]
print result