压缩并计算

我正在寻找不使用递归的解决方案。我有3个数据,例如:

names = ["Alice","Bob","Charlie","David"]

-- their grades:
grades :: [[Int]]
grades = [[3,2],[4,6],[2,3],[1,4]]

-- And the weights for a total note
weights :: [Float]
weights = [0.75,0.25]

这应该理解为:

Alice's grades:   3 and 2 -- The grade 3 weighted with 75% and the grade 2 with 25%
Bob's grades:     4 and 6 -- The grade 4 weighted with 75% and the grade 6 with 25%
Charlie's grades: 2 and 3 -- The grade 2 weighted with 75% and the grade 3 with 25%
David's grades:   1 and 4 -- The grade 1 weighted with 75% and the grade 4 with 25%

我编写了一个函数,用于为一个学生计算averageGrade

averageGrade :: [Float] -> [Int] -> Float

我必须根据这种类型完成一项功能:

allStudents :: [String] -> [[Int]] -> [Float] -> [(String,Float)]

此功能应为每个人的元组提供平均等级,例如:

[("Alice",2.75),("Bob",4.5),etc....]

计算由averageGrade (weights) ([Specific Grades])进行,例如

averageGrade (weights) ([3,2])

如果我想为Alice计算它。

如何在不通过headtail遍历列表的情况下进行遍历(因为不允许递归)?

jiabing305 回答:压缩并计算

所以你想要

allStudents  :: [String] -> [[Int]] -> [Float]            -> [(String,Float)]

没什么不同
allStudents2 :: [String] -> [Float] -> [[Int]]            -> [(String,Float)]

你有

averageGrade ::             [Float] ->  [Int]  ->  Float

如此

averageGrade (weights ::    [Float]) :: [Int]  ->  Float

并且自

map (foo ::                               a    ->   b      ) 
                           ::          [  a  ] -> [ b   ]

我们有

map (averageGrade weights) ::          [[Int]] -> [Float]

map (averageGrade weights) (grades :: [[Int]]) :: [Float]

the one last missing piece to the puzzle

_ ::            [ c    ]  ->                      [ b   ] -> [( c,b    )]

如此

_ (names ::     [String]) ::                      [ b   ] -> [(String,b    )]
,

如果禁止使用递归,则意味着您应该使用一些标准功能,例如foldlfoldrmapzip等。

由于您具有averageGrade功能来处理学生的成绩,因此可以使用map来处理此类成绩的列表:

map (averageGrade weights) grades

它将averageGrade weights函数逐一应用于列表的每个元素,并向您返回结果列表,即每个学生的平均成绩列表。

因此,现在,当您处理所有学生的数据时,只需将每个学生的姓名与适当的平均成绩配对即可。您可以使用zip函数:

allStudents :: [String] -> [[Int]] -> [Float] -> [(String,Float)]
allStudents names grades weights = zip names $ map (averageGrade weights) grades

您可以在这里进行测试:https://repl.it/@Yuri12358/so-zip

本文链接:https://www.f2er.com/3097622.html

大家都在问