Home > Software design >  Implementing Array.make in OCaml
Implementing Array.make in OCaml

Time:07-30

I am trying to implement Array.make of the OCaml Array module. However I'm not getting the values right, my implementation:

 let make_diy s v = 
         let rec aux s v = 
           if s = 0 then [| |]
           else Array.append v ( aux (s-1) v )
       in aux s v;;

...has the value: val make_diy : int -> 'a array -> 'a array = <fun>instead of: int -> 'a -> 'a array. It only creates an array if v is already in an array:

make_diy 10 [|3|];;
- : int array = [|3; 3; 3; 3; 3; 3; 3; 3; 3; 3|]

make_diy 10 3;;
Error: This expression has type int but an expression was expected of type
         'a array

I also tried to make it with an accumulator, but it has the same result:

let make_diy s v = 
         let rec aux s v acc =  
           if s=0 then acc
           else append v ( aux (s-1) v acc  )
       in aux s v [| |];;

EDIT: (typo) append instead of add

CodePudding user response:

The problem seems to be that Array.append expects two arrays. If you want to use it with just an element, you need to wrap the first argument into an array:

Array.append [| v |] (aux (s - 1) v)

Note that this isn't a particularly efficient way to build up an array. Each iteration will allocate a new, slightly larger array. But presumably this is just a learning exercise.

  • Related