为什么“if”是我代码中的意外标记?

时间:2013-07-14 23:54:08

标签: ocaml

以下是我的代码的前三行:

let day_of_week (year: int) (month: int) (day: int): int =
    if year < 2010 || year > 2019 then failwith "year out of range"
    if month < 1 || month > 12 then failwith "invalid month"

我得到“意外令牌”如果“;错误:语法错误”为第二个if。怎么样?

1 个答案:

答案 0 :(得分:3)

一种可能性是:

let day_of_week (year: int) (month: int) (day: int): int =
      if year < 2010 || year > 2019 then failwith "year out of range" 
      else if month < 1 || month > 12 then failwith "invalid month" 
      else day ;;
val day_of_week : int -> int -> int -> int = <fun>

由于failwith函数引发了异常,因此您 不能使用if … then … else …,但如果您决定仅使用if … then …,则必须使用; {1}}表示新表达式何时开始:

# let day_of_week (year: int) (month: int) (day: int): int =
        if year < 2010 || year > 2019 then failwith "year out of range" ;
        if month < 1 || month > 12 then failwith "invalid month" ;
        day ;;
val day_of_week : int -> int -> int -> int = <fun>