0
votes
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.

2
Try it with funli ll (k-1) in the x:ll arm.Eli Sadoff
Also, k==1 is invalid syntax. You want k=1. == is not used to test equality in OCaml.Eli Sadoff
It's not invalid syntax. But not recommended for integers.camlspotter

2 Answers

1
votes

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);;
0
votes

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).