Hello there. I have one question with an example regarding permuting matrices.
I’m aiming to permute/rearrange a matrix and the elements in it, matrix in this case being a list of lists.
The function and the parameters should look something like this:
permute [[1;2;3]; [4;5;6]; [7;8;9]] [2;3;1;] [1;3;2];;
int = [[4;6;5]; [7;9;8]; [1;3;2]]
The first parameter is the list of lists, the second one is how the lists inside should be rearranged and the third one is how the elements within each list should be rearranged.
I am fresh to OCaml, any help is greatly appreciated, and sorry if I addressed something very obvious.
Hey there! I suggest changing your input-list from a list of lists to an array of arrays. Those support random access, and then your problem gets easier to solve:
let permute list p_o p_i =
(* create an array of the list, so you can access its elements randomly *)
let array = Array.of_list (List.map Array.of_list list) in
(* map over the inner permutation-indices and directly access the elements *)
let permute_inner inner = List.map (fun i -> inner.(i-1)) p_i in
(* map over the outer permutation-indices and directly access the arrays *)
List.map (fun i -> permute_inner array.(i-1) ) p_o
let result = permute [[1;2;3]; [4;5;6]; [7;8;9]] [2;3;1] [1;3;2]
I think it’s worth thinking about how to decompose this problem and solve it while still staying purely-functional. [I’m the last guy to argue for purely-functional code, but hey, mostly-functional code is where it’s at for sure, and the only way to learn how to do that, is to write purely-functional code first … as the FP koan teaches.]
First, you need a function that permutes a list.
Then, you need to apply that function to each row (with the column-permuter spec)
and then you need to apply it to the rows (with the row-permuter spec).
Or, hey, you can do the last two steps in the opposite order.
let permute1 spec l = <to be implemented later>
let permute ll rowpspec colpspec =
(List.map (permute1 colpspec) ll)
So now you’re down to permuting a list of values, based on a spec (list of integers). Here’s a hint (
# List.nth [1;2;3] 1;;
- : int = 2
Can you see how to implement permute1 ?
That looks a lot nicer than mine. Thank you, learned something