Converting float[,] to list in f#?

人走茶凉 提交于 2019-12-11 02:55:00

问题


I have a function that works fine for lists however the input to the function comes as float[,] from external system / language.

I read this but when I apply this I get an error float[,] is not compatible with Seq<a'>. However this list is also only of floats.

List function:

let aggrArraysL data =
    data
    |> Seq.groupBy (fun (a, b, c) -> a)
    |> Seq.map (fun (key, group) ->
        group |> Seq.reduce (fun (a, b, c) (x, y, z) -> a, b + y, (b * c + y * z * 1.)/(b + y)))

Array attempt:

let aggrArrays (data2 : float[,]) =
    data2
    |> Seq.toList
    |> Seq.groupBy (fun (a, b, c) -> a)
    |> Seq.map (fun (key, group) ->
        group |> Seq.reduce (fun (a, b, c) (x, y, z) -> a, b + y, (b * c + y * z * 1.)/(b + y)))
    |> Seq.toArray

Where am I going wrong? thanks!


回答1:


2D arrays implement IEnumerable so you can just cast them using Seq.cast<T>:

let toList (data2: float[,]) = data2 |> Seq.cast<float> |> Seq.toList

You probably want to make it generic:

let toList<'a> (data2: 'a [,]) = data2 |> Seq.cast<'a> |> Seq.toList

EDIT: It looks like you want to map the array into a list of row elements instead of flattening it. In this case you could do:

let aggrArrays (data2:float[,])  =
    [0 .. (Array2D.length1 data2) - 1]
    |> List.map (fun i -> (data2.[i, 0], data2.[i, 1], data2.[i, 2]))
    |> Seq.groupBy id
    |> Seq.map (fun (key, group) -> group |> Seq.reduce (fun (a,b,c) (x, y, z) -> a, b+y , (b*c+y*z*1.)/(b+y)))
    |> Seq.toArray


来源:https://stackoverflow.com/questions/19348254/converting-float-to-list-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!