F#列表转置列表列表?

时间:2015-02-27 05:44:28

标签: f#

在F#中,如何使列表转置函数与int列表列表兼容?

let rec transpose = 
   function
    | (_::_)::_ as M -> List.map List.head M :: transpose (List.map List.tail M)
    | _ -> []

看起来这只适用于int list list。但是,我进一步将最内层列表分组为int list list list

1 个答案:

答案 0 :(得分:2)

使用int列表列表,它取决于您要转置的矩阵:内部矩阵或外部矩阵或两者。在最后一种情况下,它将取决于转置顺序。

let rec transpose = function
| (_::_)::_ as M -> List.map List.head M :: transpose (List.map List.tail M)
| _ -> []

// (a (b (c))) -> (a (c (b)))
let transpose0 m = m |> List.map transpose

// (a (b (c))) -> (b (a (c)))
let transpose1 m = m |> transpose

// (a (b (c))) -> (b (c (a)))
let transpose2 m = m |> transpose |> List.map transpose

// (a (b (c))) -> (c (a (b)))  
let transpose3 m = m |> List.map transpose |> transpose

// (a (b (c))) -> (c (b (a)))  
let transpose4 m = m |> transpose |> List.map transpose |> transpose