Is there a more idiomatic way to express this pattern in F#:
seq {
for item1 in list1 do
for item2 in list2 do
yield f(item1,item2)
}
Thanks!
This pattern is as idiomatic as it gets.
Usually an alternative is to use a pipeline of higher-order functions like Seq.map
or Seq.filter
, but for your particular case - Cartesian product -
a sequence comprehension approach really shines and you won't get anything near that simple otherwise.
Utlimately it's a judgement call which style to use. I tend to prefer the pipeline approach, only to later realize how much clearer a sequence comprehension approach is.
As long, as you don't need anything complicated, like imperative features or flattening of sub-expressions (yield!
), you can use a slightly less verbose syntax:
seq { for item1 in list1 do
for item2 in list2 -> f(item1, item2) }
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