简体   繁体   中英

How to form a matrix list of list using OCaml List Modules only?

I was wondering how to form a matrix using O'Caml

I've formed a normal list from a list of tuples that indicate the index and the element via:

  List.map (fun (idx, x) -> x ) list

I wanted to do this for a matrix without using recursion or loops. Just higher-order functions and List.module

(Context: I'm trying to transpose a matrix given a matrix)

I think your approach will work, though it might not be the fastest method.

There's no simple function to construct a list (or a list of lists) from a set of indices and elements. It's hard to make a clean and simple definition of a function like that because of all the values the indices could have (duplicates, missing values, out of order, etc.).

I'd say the missing step would be to sort the list of triples into the desired order. Since there's a sort function in the List module, this is presumably allowed by your limitations.

In essence, the original order sorts by the first index then the second. So to get the transpose you want to sort by the second index then the first.

After you have the right order you can use List.fold_left or List.fold_right to assemble your final list of lists.

Here's a function that reformats a list into groups of threes using List.fold_left. This isn't the function you want, but it might be close:

let bythrees l =
    let iby (cur, prev, n) x =
        if n mod 3 = 2 then ([], (x :: cur) :: prev, n + 1)
        else (x :: cur, prev, n + 1)
    in
    let (_, res, _) = List.fold_left iby ([], [], 0) l in
    res

Here's how it looks when you run it:

# bythrees [1;2;3;4;5;6;7;8;9];;
- : int list list = [[9; 8; 7]; [6; 5; 4]; [3; 2; 1]]

The output still needs some work, but this shows you can make a list of lists this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM