Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a matrix into a list by flattening it ocaml

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading