Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - Converting nested for-loops to a functional style

I'm trying to convert my nested for-loops to a more functional style.

I've been messing around with pipelining, sequences, and arrays, but to no avail.

Here's what I have:

let allCarrierCodes = new List<string>()    
for result in getAllCarrierCodesResults do
        for carrierCode in result do
            allCarrierCodes.Add(carrierCode.ToString())
  • getAllCarrierCodesResults is a seq of type "obj list"

What's a nice functional way to re-write the nested loops?

Thanks.

like image 565
D. O Sullivan Avatar asked Mar 31 '16 14:03

D. O Sullivan


2 Answers

You can use Seq.collect:

let allCodes = Seq.collect id getAllCarrierCodesResults 
               |> Seq.map string)

or

let allCodes = Seq.collect (Seq.map string) getAllCarrierCodesResults

you can then convert the resulting seq<string> into the concrete collection you want.

like image 66
Lee Avatar answered Oct 19 '22 18:10

Lee


Lee's answer is better than this, but I just wanted to mention that you can totally just put those nested loops inside a list comprehension, and voila:

let allCarrierCodes =
  [for result in getAllCarrierCodesResults do
     for carrierCode in result do
       yield carrierCode.ToString()]

Looks kind of imperative-ish, but is really functional.

Also, you should use string carrierCode instead of carrierCode.ToString(). Protects you from NRE and looks more functional for added bonus :-)

like image 25
Fyodor Soikin Avatar answered Oct 19 '22 19:10

Fyodor Soikin