应用于Haskell中列表中的所有元素

应用于Haskell中列表中的所有元素,haskell,Haskell,我试图计算列表元素的平均值。 给定一个txt,其中我有名称,然后是计算平均值的数字: Bob 5 6 9 10 5 Alice 10 3 5 6 8 Kate 2 4 我使用words函数获取输入文件的列表,以便处理它 我试图构造一个元组列表,然后用composeList函数计算平均值,但我只得到第一个元素: [("Bob",[5.0,6.0,9.0,10.0,5.0])] 我不知道如何得到元组列表,然后计算平均值,得到 [(“鲍勃”,7.0),(“爱丽丝”,6.5),“

我试图计算列表元素的平均值。 给定一个txt,其中我有名称,然后是计算平均值的数字:

Bob 5 6 9 10 5
Alice 10 3 5 6 8
Kate 2 4
我使用words函数获取输入文件的列表,以便处理它

我试图构造一个元组列表,然后用composeList函数计算平均值,但我只得到第一个元素:

[("Bob",[5.0,6.0,9.0,10.0,5.0])]
我不知道如何得到元组列表,然后计算平均值,得到

[(“鲍勃”,7.0),(“爱丽丝”,6.5),“凯特”,7.75)]

以下是我到目前为止的情况:

import qualified Data.Text    as Text
import qualified Data.Text.IO as Text
import Data.String



readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile 

calculateMean :: [Double] -> Double
calculateMean [] = 0
calculateMean (a) = sum a / fromIntegral(length a)


--calculateMeanList :: [String] -> (String,[Double])
--calculateMeanList (a) = (head $ words $ head a, calculateMean $ convertNumeric $ tail $ words $ head $ a)

convertNumeric :: [String] -> [Double]
convertNumeric = map read


composeList :: [String] -> [(String, [Double])]
composeList (a) = [(head $ words $ head $ a, convertNumeric $ tail $ words $ head $ a)]


main = do
    
    ls <- readLines "puntuaciones.txt"
    
  
    print $ words $ head $ ls

    print $ composeList ls
导入符合条件的数据。文本作为文本
将限定数据.Text.IO导入为文本
导入数据.String
readLines::FilePath->IO[字符串]
读线=fmap线。读取文件
calculateMean::[Double]->Double
calculateMean[]=0
calculateMean(a)=和a/fromIntegral(长度a)
--calculateMeanList::[String]->(String,[Double])
--calculateMeanList(a)=(head$words$head a,calculateMean$convertNumeric$tail$words$head$a)
convertNumeric::[String]->[Double]
convertNumeric=地图读取
组合列表::[String]->[(String,[Double])]
组合列表(a)=[(head$words$head$a,convertNumeric$tail$words$head$a)]
main=do

ls你只接受
头的单词,所以你当然只得到第一个元素。您应该跨行映射
words
函数:

导入符合条件的数据。文本作为文本
将限定的Data.Text.IO作为文本导入
导入数据.String
readLines::FilePath->IO[字符串]
读线=fmap线。读取文件
calculateMean::[Double]->Double
calculateMean[]=0
calculateMean(a)=和a/fromIntegral(长度a)
convertNumeric::[String]->[Double]
convertNumeric=地图读取
组合列表::[String]->[(String,[Double])]
--可以用地图书写,但列表理解更清晰

composelista=[(head curWords,convertNumeric$tail curWords)| curWords首先编写一个函数,可以将一对
(“Bob”、[5.0,6.0,9.0,10.0,5.0])
转换为想要的
(“Bob”,7.0)
。类似于
foo(名称、值)=(…,…)
应该可以。然后将它映射到成对列表上。好的,我知道我做错了什么。谢谢!我正试图为此创建一个函数,并替换您创建的lambda函数,但我猜我也做错了:
calculateMeanList2::(String,[Double])->(String,Double)calculateMeanList2(a,b)=map(\l->((a,calculateMean b)l)
另外,lambda是错误的,因为您需要在映射之外维护元组的第一个元素,然后只取列表的平均值,因此它看起来像
calculateMean列表2(a,b)=(a,calculateMean b)
但是有没有方法调用该函数calculateMeanList2上的映射?我正在尝试将所有这些都封装在函数中。
calculateMeanList2
只在元组上工作。然后,您可以只
映射calculateMeanList2组合
来修改完整列表。