Haskell大于或等于

时间:2015-03-24 03:22:54

标签: haskell recursion

我正在尝试将整数列表转换为字符列表以类似于成绩。这是我在Haskell中的代码:

grade :: [int] -> [char]

grade array = if 90 <= head array then ['A'] ++ grade(tail array)
          else if 80 <= head array then ['B'] ++ grade(tail array)
          else if 70 <= head array then ['C'] ++ grade(tail array)
          else if 60 <= head array then ['D'] ++ grade(tail array)
          else if 60 > head array then ['F'] ++ grade(tail array)
          else [] array

编译器GHCi给了我这个错误:

 Couldn't match expected type ‘[int] -> [char]’
            with actual type ‘[t0]’
Relevant bindings include
  array :: [int] (bound at grade.hs:3:7)
  grade :: [int] -> [char] (bound at grade.hs:3:1)
The function ‘[]’ is applied to one argument,
but its type ‘[t0]’ has none
In the expression: [] array
In the expression:
  if 60 > head array then ['F'] ++ grade (tail array) else [] array

我不确定'[t0]'是什么意思

提前致谢

我将代码更改为:

grade :: [Int] -> [Char]

grade array = if 90 <= head array then ['A'] ++ grade(tail array)
          else if 80 <= head array then ['B'] ++ grade(tail array)
          else if 70 <= head array then ['C'] ++ grade(tail array)
          else if 60 <= head array then ['D'] ++ grade(tail array)
          else if 60 > head array then ['F'] ++ grade(tail array)
          else [] = array

感谢您的推荐,但现在它在'='处给我一个解析错误?我不确定现在有什么问题

1 个答案:

答案 0 :(得分:4)

实现目标的最佳方法是使用模式匹配:

grade [] = []
grade array = if 90 <= head array then ['A'] ++ grade(tail array)
          else if 80 <= head array then ['B'] ++ grade(tail array)
          else if 70 <= head array then ['C'] ++ grade(tail array)
          else if 60 <= head array then ['D'] ++ grade(tail array)
          else ['F'] ++ grade(tail array)

此外,您可以使用模式匹配来摆脱重复的head / tail来电:

grade [] = []
grade (x:xs) = if 90 <= x then ['A'] ++ grade xs
          else if 80 <= x then ['B'] ++ grade xs
          else if 70 <= x then ['C'] ++ grade xs
          else if 60 <= x then ['D'] ++ grade xs 
          else ['F'] ++ grade(xs)

编辑:要进一步使用haskellize,你可以使用警卫:

grade [] = []
grade (x:xs)
    | 90 <= x   = ['A'] ++ grade xs
    | 80 <= x   = ['B'] ++ grade xs
    | 70 <= x   = ['C'] ++ grade xs
    | 60 <= x   = ['D'] ++ grade xs
    | otherwise = ['F'] ++ grade xs

编辑#2:删除grade旁边的括号,按@ rampion的评论。