2

I have a program that takes a text file with values for example:

20 30
23 5
200 3

And I convert it to a list and add each line to create a subtotal and then a sum.

import System.IO  
import Control.Monad

f :: [String] -> [Int]
f = map read

subsum :: [Int] -> [Int]
subsum [] = []
subsum [x] = []
subsum (x:(y:xs)) = (x+y) : (subsum xs)

calc fromf = do  
        let list = []  
        let list2 = []
        handle <- openFile fromf ReadMode
        contents <- hGetContents handle
        let singlewords = words contents
            list = f singlewords
            list2 = subsum list
            result = sum list2
        print list2
        print result
        hClose handle  

How would I change this code to take in a text file of different numbers ex:

10 9 29 40
1 34 2
1 2 55 89

Create a list of subtotals of each line and then a total.

1
  • 1
    Your list = [] and list2 = [] statements are unnecessary. These are not mutable variables (as is the case with other languages), so you're not accomplishing anything like initialization, as you may imagine. Commented Oct 24, 2011 at 1:43

1 Answer 1

2

How about

import System.IO
import Control.Monad

subtotals :: String -> [Int]
subtotals c = map sum (map (map readInt) (map words (lines c)))
    where
        readInt = read :: String -> Int

calc fname = do
    contents <- readFile fname
    print $ subtotals contents
    print $ sum (subtotals contents)
Sign up to request clarification or add additional context in comments.

1 Comment

readInt is undefined on my stock GHC 7.10.2. I replaced it with my own function " readInt :: [String] -> [Int]; readInt = map read"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.