5

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))
gradbot
  • 13,732
  • 5
  • 36
  • 69

1 Answers1

10

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

EDIT: As Noldorin points out in a comment, this is even better:

let l = a2 |> Seq.cast<int> |> Seq.toList
Gebb
  • 6,371
  • 3
  • 44
  • 56
Brian
  • 117,631
  • 17
  • 236
  • 300
  • Good solution... I've just deleted mine, as it's slightly more complicated. However I might as well point out that the second line can be simplified to: let l = a2 |> Seq.cast |> Seq.to_list – Noldorin Mar 15 '09 at 18:13
  • Awesome thanks, I figured there was something I could do with IEnumerable but I didn't know how to do it. – gradbot Mar 15 '09 at 18:23
  • its `Seq.toList` not `Seq.to_list`.. (can't edit because SO says: `Edits must be at least 6 characters`, thank you very much SO.. :/ ) – Michelrandahl Apr 18 '16 at 21:40