I want to convert a matrix(type matrix = float list list) into a list(so basically I’m writing a function to concatenate a list of lists, but I’m not allowed to use List.append, List.flatten, etc.).
So for example, into_list [[1.; 2.]; [3.; 4.] = [1.; 2.; 3.; 4.]. I wrote my helper function to append two lists together:
let rec append_list (a: float list) (b: float list): float list =
match a with
| [] -> b
| h :: t -> h :: append_list t b
right now, my into_list function looks like this:
let rec into_list (m : matrix): float list =
match m with
| [] -> []
| h1 :: h2 :: t -> append_list h1 h2 :: into_list t
I pretty sure | h1 :: h2 :: t -> append_list h1 h2 :: into_list t is wrong but I have no idea how to fix it, right now utop gives me the error message says "Unbound type constructor matrix".
>Solution :
It would appear matrix is simply:
type matrix = float list list
As such:
append_list h1 h2 :: into_list t
Would yield float list list because the type of :: is 'a -> ‘a list -> ‘a list`.
You’re looking for something like a fold, that continually appends the lists into a final float list.
let rec into_list m = List.fold_left append_list [] m
Of course, it doesn’t seem like you’re allowed to use List.fold_left. Replicate that functionality (shown many times here) and you’re good to go.