haskell if else语句有多个条件

时间:2017-01-21 11:37:19

标签: haskell

目标是编写一个函数,给定1到12之间的整数评估相关月份的名称(1-> 1月等)。否则,它可以评估为"不正确的月份数& #34 ;. 这是我的代码:

list = ["Jan","Feb","Mar","April", "May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
month x = if x<13 && x>0
          then x = list !! (x-1)
          else "Not a month"

这是输入错误msg:解析错误&#34; =&#34;

非常感谢你的帮助

4 个答案:

答案 0 :(得分:4)

只需删除x =即可。 (你为什么写这个?)

list = ["Jan","Feb","Mar","April","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
month x = if x<13 && x>0
          then list !! (x-1)
          else "Not a month"

答案 1 :(得分:3)

使用警卫是最好的策略:

month x | x > 0 && x < 13      = list !! (x - 1)
        |otherwise             = "Error"

您还可以使用Maybe进行此类操作:

mylist = ["Jan","Feb","Mar","April", "May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec"]

exampleFunc :: [String] -> Int -> Maybe String
exampleFunc li int
   | int > 0 && int < 13    = Just (li !! (int - 1))
   | otherwise              = Nothing

使用Maybe可以在Nothing条件下返回标准值(otherwise)。

答案 2 :(得分:2)

你好写道:

month x = if x0
          then x = list !! (x-1)
          else "Not a month"

您可能习惯于命令式世界(C ++,Java,...),其中有变量可以设置并设置为其他值。在函数和范围声明性语言中,变量只设置一次。

此外,无需将x设置为某个值,您只需返回list!!(x-1)即可:

month x = if x<13 && x>0
          then list !! (x-1)
          else "Not a month"

应该有用。

An - 在我看来 - 更优雅的方式来写这个但是使用警卫:

month x | x > 0 && x < 13 = list !! (x-1)
        | otherwise = "not a month"

答案 3 :(得分:1)

您也可以这样写:

month = ["Jan","Feb","Mar","April", "May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
getMonth k = lookup k $ zip [1..] month