OCaml初学者需要帮助:出了什么问题?

时间:2010-03-17 21:45:22

标签: ocaml

代码:

let rec get_val (x, n) = match x with
    [] -> -1
  | if (n=0) then (h::_) -> h 
    else (_::t) -> get_val(t, n-1)
;;

错误讯息:

Characters 55-57:
| if (n=0) then (h::_) -> h 
  ^^
Error: Syntax error

2 个答案:

答案 0 :(得分:8)

我认为问题是你试图将if表达式放入模式匹配语句中。每个->的左侧需要与x的有效模式相对应。

试试这个:

let rec get_val (x, n) = match x with

    [] -> -1

  | h::t -> if (n=0) then h 
                     else get_val(t, n-1)

;;

答案 1 :(得分:7)

你不能将if和match混合起来,你必须在模式之后使用if,如已经提出的那样,或者使用保护模式,如:

let rec get_val x n = 
  match x with
    [] -> -1
  | h::_ when n=0 -> h 
  | _::t ->  get_val t (n-1)
;;

另请注意,ocaml是curry,并且通常不会在函数的参数周围加上括号