0

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;;
tacocat
  • 23
  • 4

2 Answers2

2

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.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
-1

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.

Nalin Ranjan
  • 1,728
  • 2
  • 9
  • 10