Function to create a recursive list. Type Errors

I have an Ocaml function that gives me errors.

What I'm trying to do:

Create a list of random numbers (0-2) of size "limit" recursively.

Here is what I have:

let rec carDoorNumbers = fun limit -> match limit with | [1] -> Random.int 3 | [] -> Random.int 3 :: carDoorNumbers (limit-1);; 

I get this error:

 Error: This expression has type 'a list but an expression was expected of type int 
+4
source share
2 answers

Think about what your function should do: given the limit, you need to create a list of numbers. So your type is similar to carDoorNumbers : int -> int list .

Looking at this, it seems you have two mistakes. First, you map the limit (which should be int ) to the list template. [1] -> ... matches a list containing only item 1 and [] that matches an empty list; you really want to match the number 1 and any other number n .

The second mistake is that you return two different types in your match statement. Remember that you must return a list. In the first case, you return Random.int 3 , which is an int , not an int list . What you really want to bring back here is like [Random.int 3] .

The error you received is a bit confusing. Since the first thing you returned was int , it expects your second thing to also be int . However, your second case was really correct: you are returning an int list ! However, the compiler does not know what you had in mind, so its error is reversed; instead of changing int list to int , you need to change int to int list .

+3
source

Your match expression treats the limit as a list. Both [1] and [] are lists. This is what the compiler tells you. But it seems that the limit should be an integer.

To match an integer, use the integer constant. No square brackets.

(As a side comment, you can be sure that the function works well when you pass it 0.)

+2
source

Source: https://habr.com/ru/post/1436471/


All Articles