我有一个程序,它带有一个带有值的文本文件,例如:
20 30
23 5
200 3
我将其转换为列表并添加每一行以创建小计,然后是总和。
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
如何更改此代码以获取不同数字的文本文件ex:
10 9 29 40
1 34 2
1 2 55 89
创建每行的小计列表,然后创建总计。
答案 0 :(得分:2)
怎么样
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)