Haskell 文件读取和数字相加

发布于 2024-12-12 02:24:50 字数 784 浏览 0 评论 0原文

我有一个程序,它采用带有值的文本文件,例如:

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  

我将如何更改此代码以接受不同数字的文本文件,例如:

10 9 29 40
1 34 2
1 2 55 89

创建每行的小计列表,然后创建总计。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虚拟世界 2024-12-19 02:24:50

怎么样

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文