Abhishek Kumar
Abhishek Kumar

Reputation: 769

What is problematic about below ocaml code?

let rec funli li k = match li with 
| [x] -> if k==1 then Some(x) else None
| x::ll -> funli ll k-1;;

utop shows Error: This expression has type 'a option but an expression was expected of type int

I see no reason for it to expect int. Please help me understand what is happening in this code. I am new to OCaml.

Upvotes: 0

Views: 75

Answers (2)

Eli Sadoff
Eli Sadoff

Reputation: 7308

There are a few problems with your code. First, you want to be explicit that k-1 is a parameter and that you're not trying to return (funli ll k)-1, which is what OCaml is interpreting that arm as. Additionally, == is not used to test equality in OCaml. This will work fine

let rec funli li k = match li with 
| [x] -> if k=1 then Some(x) else None
| x::ll -> funli ll (k-1);;

Upvotes: 1

sepp2k
sepp2k

Reputation: 370435

funli ll k-1 is parsed as (funli ll k)-1. So you're trying to subtract one from an option, leading to the error you got.

What you want is funli ll (k-1).

Upvotes: 0

Related Questions