Why do I get a type unit when I want to concatenate the element of the array with an empty list?

59 Views Asked by At

I am trying to make a list out of a given array and in my code it returns an empty list. I want to know why this is impossible to do with list. Is it because we are supposed to return something in the third line and the concatenation is not "saved" anywhere?

let arrayTOlist a = 
  let l = [] in
  for i = 0 to (Array.length a - 1) do 
    [a.(i)]::l      (*why does this have type unit?*) 
  done;
  l;;
2

There are 2 best solutions below

0
Jeffrey Scofield On BEST ANSWER

The value l in your code is immutable. So nothing can change it from the initial value of []. Thus the function will always return [].

The expression [a.(i)] :: l doesn't change l. It has a value that is a list of length 1 for every iteration. This value is then discarded (which leads to the warning that the value should have type unit).

There is already a function Array.to_list, so I assume this is a homework problem, and hence there's no point in reimplementing Array.to_list using other functions from the Array module.

The best way to proceed is probably with a recursive function that takes an array index as a parameter.

0
Nalin Ranjan On

If we try the following, it doesn't generate any warning..

let arrayTOlist a = let l =[] in [a.(0)] :: l;;
val arrayTOlist : 'a array -> 'a list list = <fun>

so I strongly think it's the for loop because of which that warning is getting generated.

We can find more information about that behavior by reading a section about for loop in the OCaml documentation.