2014-02-05 41 views
1

我想将Vector3 list展平为float32 list将载体列表展平为带有折叠列表的浮点列表

[Vector(1.,2.,3.);Vector(1.,2.,3.)] to [1.;2.;3.;1.;2.;3.] 

我已经用下面的函数

let rec convert_vec3 (v: Vector3 list) acc = 
    match v with 
    | [] -> acc 
    | x :: xs-> convert_vec3 xs [x.X; x.Y;x.Z] @ acc 

这将如何寻找与List.fold做成功了吗?

回答

4

convert_vec3功能的等效是

List.fold (fun acc (v:Vector) -> [v.X; v.Y; v.Z] @ acc) [] input 

但是,正如mydogisbox提到,List.collect可能会更好,因为这将使你在列表中正确的顺序,你的convert_vec3功能和List.fold等效不会。

List.collect (fun (v:Vector) -> [v.X;v.Y;v.Z]) input 
2

我想你想要的是List.collectList.fold

> List.collect (fun x->x |> List.map (float32)) [[1.0];[2.0];[3.0]];; 
val it : float32 list = [1.0f; 2.0f; 3.0f]] 

与和您的向量之间的映射为载体

3

@mydogisbox的答案是产生值列表更换(fun x->x |> List.map (float32))良好且有效,但您也可以使用List.fold。请注意您的递归函数以相反的顺序收集值。为了避免这种情况,我真的建议List.foldBack

([Vector(1.,2.,3.);Vector(1.,2.,3.)], []) 
||> List.foldBack (fun v acc -> v.X :: v.Y :: v.Z :: acc) 
// val it : float list = [1.0; 2.0; 3.0; 1.0; 2.0; 3.0]