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]
I get the following error
Couldn't match expected type `IO t0' with actual type `[a0]'
In the expression: main
When checking the type of the function `main'
What am I doing wrong?
The use of the name main is important: main is defined to be the entry point of a Haskell program (similar to the main function in C), and must have an IO type, usually IO (). (The name main is special only in the module Main; we will have more to say about modules later.)
Functions can also be passed as arguments or returned (as we have seen). Their types are given in the type signature. *Main> :t map map :: (a -> b) -> [a] -> [b] *Main> :t filter filter :: (a -> Bool) -> [a] -> [a] flip_args :: (a -> b -> c) -> b -> a -> c flip_args f x y = f y x.
> In fact, in haskell, everything is a function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With