我有一个定义的类型和这种类型的元素。这个元素有元组,我需要取3个该元组并取平均值。
type Name = String
type Subject = String
type Grade = Float
-- Definition of a type
type Student = (Name, Subject, Grade, Grade, Grade)
-- Elements of this type
student :: Int -> Student
student 1 = ("Rafael", "INE5416", 6.0, 5.0, 8.0)
-- now i need a function that can receive an Int as student ID, get this
-- student by ID and calculate her average grade.
getAverage :: Int -> Float
getAverage student x = ((_, _, c, d, e) / 3) -- Int is to get x student
main = do
print (getAverage(1)) -- passing student ID--
答案 0 :(得分:4)
您可以使用给定的ID号对student
进行调用,以进行模式匹配,然后获取您所关心的术语的平均值。
getAverage :: Int -> Float
getAverage studentId = (a + b + c) / 3
where (_, _, a, b, c) = student studentId
危险是student
功能不完整。目前评估student 2
会使程序崩溃。