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.
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.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With