haskell - 压缩和计算
问题描述
我正在寻找不使用递归的解决方案。我有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])
如果我想为爱丽丝计算它。
如何在不通过head
and遍历列表的情况下迭代列表tail
(因为不允许递归)?
解决方案
所以你要
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]
最后一个缺失的部分是
_ :: [ c ] -> [ b ] -> [( c , b )]
这样
_ (names :: [String]) :: [ b ] -> [(String, b )]