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]

4 comments:

  1. Thank you
    Wow !!! It’s amazing
    play game for relax and win get money
    PG Slot

    ReplyDelete
  2. Thanks for fantastic information I was looking for this information for my mission.
    play game for relax and win get moneyy
    PG SLOT

    ReplyDelete