3
votes
let rec getElement list index = match list with
| [] -> raise OutOfBoundException
| first::elems -> if index = 0 then first else getElement elems index-1;;

I don't understand why this function has type (int list -> int -> int) instead ('a list -> int -> 'a). I need to write function that returns nth element in the list, that has generic type (has type exp defined by user: http://pastebin.com/UefshcLa).

How can I write that function? And why Ocaml inferences that list is int list instead 'a list?

1
You also can have a look to the function nth which do the same job of your function.alifirat

1 Answers

10
votes

OCaml interprets (getElement elems index) - 1, because function application is stronger than -.

let rec getElement list index = match list with
| [] -> raise OutOfBoundException
| first::elems -> if index = 0 then first else getElement elems (index-1);;