Combining a column of lists in OCaml

前端 未结 2 928
梦如初夏
梦如初夏 2021-01-23 20:18

I want to essentially transpose a matrix in OCaml (without using recursion or any sort of looping)

For example, if I have the following matrix: [[1;2];[3;4]]

2条回答
  •  忘了有多久
    2021-01-23 20:39

    I question whether your separate function separates the matrix into columns. Here's what I see:

    # let separate li = List.map (fun x -> [x]) li;;
    val separate : 'a list -> 'a list list = 
    # List.map separate [[1;2];[3;4]];;
    - : int list list list = [[[1]; [2]]; [[3]; [4]]]
    

    I don't see columns, I just see that you've put each matrix element into its own list.

    To get the first column you could try this:

    # List.map List.hd [[1;2]; [3;4]];;
    - : int list = [1; 3]
    

    If you use List.tl rather than List.hd you get the remainders of the rows. Maybe you can use a fold to apply this repeatedly and collect up the results.

提交回复
热议问题