Reputation: 425
How do I read numbers from a file, sum them and print them in Haskell?
I've been trying the following: I can read the numbers, but can't get them to sum.
square x = do
return x
read_numbers = do
contents <- readFile "numbers.txt"
let linesOfFile = map (\x -> read x :: Integer) (lines $ contents)
return linesOfFile
f = do
map square read_numbers
Upvotes: 0
Views: 563
Reputation: 3218
Your problem is that you probably don't understand the concept of Monad and how Haskell use them to control side-effects in programs.
Since your objective is just to sum the read numbers, you can do the following:
f = do
xs <- read_numbers
return (sum xs)
where sum
has its obvious meaning and type:
sum :: (Num a, Foldable t) => t a -> a
EDIT: Answer to Rodrigo Stv commentary.
When you check map
type you get:
map :: (a -> b) -> [a] -> [b]
When you try to map your square function which has type
square :: Int -> IO Int
you got:
map square :: [Int] -> [IO Int].
That is a type from list of Int
to a list of I/O operations that can return an Int
and you cannot sum
I/O operations. :)
As I told you, the problem here is to understand how to work with monads.
Upvotes: 2
Reputation: 7403
There is sum in Data.List and the Prelude (http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:sum)
sum :: (Foldable t, Num a) => t a -> a Source
The sum function computes the sum of the numbers of a structure.
Upvotes: 2