arrayslistconcatenationocamlimperative-programming

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


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;;

Solution

  • 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.