F#将Array2转换为列表 [英] F# convert Array2 into a list
本文介绍了F#将Array2转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对函数式编程还是很陌生,所以如果我不知道该怎么做,我会恢复为程序样式.我找到了一种不必转换为列表的方法,但是我仍然想知道如何.
I'm still new to functional programming so if I can't figure out how to do something I revert back to procedural style. I found a way to get around having to convert to a list but I'd still like to know how.
这是我尝试将二维数组转换为列表的方法.
Here is my attempt to convert a two dimensional array to a list.
let board = Array2.init 10 20 (fun i j -> pull(i, j))
let mutable pieces = []
board
|> Array2.mapi (fun i j a -> transform(i, j, a))
|> Array2.iter (fun a -> (pieces <- a :: pieces))
推荐答案
显然,在.Net中,多维数组是IEnumerable(非通用)的,因此这行得通:
Apparently in .Net, multi-dimensional arrays are IEnumerable (non-generic), and thus this works:
let a2 = Array2.init 2 3 (fun x y -> (x+1)*(y+1))
let l = a2 |> Seq.cast<int> |> Seq.fold (fun l n -> n :: l) []
printfn "%A" l
正如Noldorin在评论中指出的那样,这甚至更好:
As Noldorin points out in a comment, this is even better:
let l = a2 |> Seq.cast<int> |> Seq.toList
这篇关于F#将Array2转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文