I have an Ocaml function that is giving me errors.
What I am trying to do:
Recursively create a List of random numbers (0-2) of size “limit”.
Here’s what I have:
let rec carDoorNumbers = fun limit ->
match limit with
| [1] -> Random.int 3
| [] -> Random.int 3 :: carDoorNumbers (limit-1);;
I am getting this error:
Error: This expression has type 'a list
but an expression was expected of type int
Think about what your function has to do: given a limit, you have to create a list of numbers. So your type is something like
carDoorNumbers : int -> int list.Looking at that, it seems you have two errors. First, you’re matching
limit(which should be anint) against a list pattern.[1] -> ...matches a list containing only the element1and[]matches the empty list; you really want to match against the number1and any other numbern.The second error is that you return two different types in your
matchstatement. Remember that you are supposed to be returning a list. In the first case, you are returningRandom.int 3, which is anintrather than anint list. What you really want to return here is something like[Random.int 3].The error you got is a little confusing. Since the first thing you returned was an
int, it expects your second thing to also be anint. However, your second case was actually correct: you do return anint list! However, the compiler does not know what you meant, so its error is backwards; rather than changing theint listto anint, you need to change theintto anint list.