delta
delta

Reputation: 3818

Can I use type declaration inside Haskell code

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.

Upvotes: 0

Views: 52

Answers (1)

bheklilr
bheklilr

Reputation: 54078

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.

Upvotes: 4

Related Questions