I have a problem compiling the following code on GHC 6.12.3 and I don’t understand why.
The purpose of function test2 is to return a function that uses an integer to get a string element from a list (the list is created from the first nodes from a pair-list).
The IO bits is needed as test2 is used by another function using IO.
type PairList = [(String, String)]
test1 :: [String] -> Int -> String
test1 list x = list !! x
test2 :: PairList -> IO (Int -> String)
test2 pl = do
f <- [fst x | x <- pl] :: IO [String]
return test1 f
GHC gives me this error:
Test.hs:8:6:
Couln't match expected type 'IO [String]'
against inferred type '[a]'
In a stmt of a 'do' expression:
f <- [fst x | x <- pl] :: IO [String]
In the expression:
do { f <- [fst x | x <- pl] :: IO [String];
return test1 f }
...
Edit:
If you want to do this directly (you need extra IO while computing
test2), you can do something likeYour original code didn’t work because when you did
f <- [...], you were using the list monad as if it were the IO monad.Purely as an example, you can use that like this:
Which would give you behaviour like
Original answer:
I don’t think you need the
IObits:This compiles fine, and gives results like
If you want to use it in IO, you could use it like this:
Or you could write