Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Is there an idiomatic way to replace for loops seq{} expressions? [duplicate]

Tags:

f#

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!

like image 326
Robert Sim Avatar asked Apr 13 '15 23:04

Robert Sim


2 Answers

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.

like image 55
scrwtp Avatar answered Nov 16 '22 06:11

scrwtp


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) }
like image 1
Daniel Fabian Avatar answered Nov 16 '22 07:11

Daniel Fabian