Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File Haskell文件读取和添加数字_File_Haskell - Fatal编程技术网

File Haskell文件读取和添加数字

File Haskell文件读取和添加数字,file,haskell,File,Haskell,我有一个程序,它采用一个带有值的文本文件,例如: 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) : (subs

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

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  
创建每行小计的列表,然后创建总计。

如何

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)
import System.IO
进口管制
小计::字符串->[Int]
小计c=映射和(映射(映射读取)(映射字(行c)))
哪里
readInt=read::String->Int
calc fname=do

内容您的
list=[]
list2=[]
语句是不必要的。这些是不可变的变量(与其他语言一样),因此您可能无法完成初始化之类的操作。readInt在我的股票GHC 7.10.2中未定义。我用自己的函数“readInt::[String]->[Int];readInt=map read”替换了它
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)