list list transpose
Sun, Dec 7 2008 11:40
| Permalink
I’ve written the following lili (’a list list) transpose for my perp system:
let transpose lili = List.map (fun n -> List.map (fun li -> List.nth li n) lili) (range0 ((List.length (List.hd lili))-1))
The range0 function generates an integer list [0;1;...;n-1] and is quite trivial:
let range ?(from=1) upto =
let rec go from upto acc =
if from > upto then acc else go from (upto-1) (upto::acc)
in
go from upto []
let range0 = range ~from:0
-- it can be further simplified with F#-like |>.
But OlegFink’s solution is simply
let rec transpose = function []::_ -> [] | list -> List.map List.hd list :: transpose (List.map List.tl list)
let transpose lili = List.map (fun n -> List.map (fun li -> List.nth li n) lili) (range0 ((List.length (List.hd lili))-1))
The range0 function generates an integer list [0;1;...;n-1] and is quite trivial:
let range ?(from=1) upto =
let rec go from upto acc =
if from > upto then acc else go from (upto-1) (upto::acc)
in
go from upto []
let range0 = range ~from:0
-- it can be further simplified with F#-like |>.
But OlegFink’s solution is simply
let rec transpose = function []::_ -> [] | list -> List.map List.hd list :: transpose (List.map List.tl list)
Comments