0

I am new to Haskell, and I have a little question about function type declaration. Suppose there are bunch of integers, we need to sum it and print it out. I am aware this works:

main = do a <- fmap (map read . words) getContents :: IO [Int] print $ sum a

buta <- fmap (map (read :: Int) . words) getContentsfailed. Why it failed? We know getContents is IO String, then words is dealing with String and return [String] to map (read :: Int), I thought it may goes fine, because we declared it to read an Int, but it failed.

Is it impossible to use type declaration inside a line of code, or I use it the wrong way. Thanks.

1 Answer 1

4

The problem is that read doesn't have the type Int, it has the type String -> Int (for your purposes). The map function only accepts a function as its first argument, and you're trying to say that read has type Int, which would mean it's not a function. There's also no way you can coerce the type Read a => String -> a to Int, so it would error on both of these problems.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks very much! I change it to fmap (map (read :: String -> Int) . words) getContents, and it runs ok.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.