开发者

OCaml beginner needs help: What is wrong?

Code:

let rec get_val (x, n) = match x with
    [] -> -1
  | if (n=0) then (h::_) -&开发者_运维知识库gt; h 
    else (_::t) -> get_val(t, n-1)
;;

Error message:

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


I think the problem is that you are trying to put an if expression into a pattern-matching statement. The left-hand side of each -> needs to correspond to a valid pattern for x.

Try this:

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

    [] -> -1

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

;;


You can't mix if and match like that, you must either use the if after the pattern, as already proposed, or use guarded patter as in:

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

note also that ocaml is curried, and you don't usually put parenthesis around function's arguments

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜