1
:t interact
interact :: (String -> String) -> IO ()

This is treated as part of the program

1
words "foo bar baz"
["foo","bar","baz"]

Convert strings to numbers

You must also specify the type.

1
(read "5") :: Int
5

Use map

It applies a function to a list and results in a new list.

1
:t map
map :: (a -> b) -> [a] -> [b]

The result should be list of integer

1
(map read $ words "1 2") :: [Int]
[1,2]

Without specifying the result, read will not work.

1
(map read $ words "1 2")
[*** Exception: Prelude.read: no parse

map and read

1
:t map read
map read :: Read b => [String] -> [b]
1
:t sum . map read
sum . map read :: (Num c, Read c) => [String] -> c

sum

I guess it’s hard to make sense of types when I don’t use parentheses.

1
map read $ words "1 2" :: [Int]
[1,2]
1
sum $ map read $ words "1 2" :: Int
3
1
(sum $ map read $ words "1 2") :: Int
3

Since sum already specifies a number, we don’t have to specify a return type.

1
sum $ map read $ words "1 2"
3
1
show $ sum $ map read $ words "1 2"
"3"

1
1 2

1
main = interact $ show . sum . map read . words
3