Tuesday, March 29, 2016

F# Yield Keyword

The yield keyword in F# is similar to the Return keyword in that it returns a value. The difference is yield is used within a sequence (or an enumeration) and it does not stop the enumeration.

Here is an example of filtering a list and returning a list of lists.
[3; 6; 8; 9]
|> List.filter(fun x -> x > 5)
|> List.map(fun x -> [x + 1])
Returns:
val it : int list list = [[7]; [9]; [10]]

To accomplish this task with for..in and yield we could do the following:
[for x in [3; 6; 8; 9] do
  if x > 5 then
    yield [x + 1]]
Returns:
val it : int list list = [[7]; [9]; [10]]

yield is similar to Return in that they both have counterparts like ReturnFrom (return!) and YieldFrom (yield!). Yield bang will do a collect and flatten the returned sequence. Here is the example using yield bang.
[for x in [3; 6; 8; 9] do
  if x > 5 then
    yield! [x + 1]]
Returns:
val it : int list = [7; 9; 10]

2 comments: