Home > Mobile >  What is wrong with this code for creating lists in OCaml?
What is wrong with this code for creating lists in OCaml?

Time:08-07

I am trying to create a program in OCaml [randlist len max], which would generate an int list of length len with integers smaller than max.

I am wondering what is wrong with the following code:

let randlist dolzina maksimum =
  let rec aux dolz maks acc =
    match (List.length acc) with
    | dolz -> acc
    | _ -> aux dolz maks ((Random.int maks) :: acc)
  in
  aux dolzina maksimum []

This always returns an empty list and I do not understand why.

Another thing that confuses me is what goes wrong with the following code:

let randlist dolzina maksimum =
  Random.self_init ()
  let rec aux dolz maks acc =
    match (List.length acc) with
    | dolz -> acc
    | _ -> aux dolz maks ((Random.int maks) :: acc)
  in
  aux dolzina maksimum []

As soon as I add the Random.self init () the whole code crashes. What exactly does Random.self_init do, when and how do I use it?

CodePudding user response:

You are using match as if it is going to compare two integer values, but that's not how it works. This match:

Match List.length acc with
| dolz -> ...

Will always match the first case. The name dolz is a new variable that is bound to the length of the list. The outer definition of dolz is not relevant here, a pattern introduces new names.

If you want to compare two integer values, you should use if:

if List.length acc = dolz then
    ...
else
    ...

CodePudding user response:

Pattern matching deconstructs values that match a pattern into smaller parts, it doesn't test equality. In other words, your first case

match List.length acc with
| dolz -> acc

reads: take the value returned by List.length acc, name it dolz in the right hand side of the arrow ->, and run the code after ->. Notice that this means that dolz matches any values. This is why the compiler warns you that the second case

| _ -> aux dolz maks ((Random.int maks) :: acc)

is never used.

For your second question, the code cannot crash, since your code is not well-typed and thus cannot compile. Random.self_init initialize the seed of the PRNG. You should call it once in your program, and not at every calls of randlist.

  • Related