1 people like it.

Semicoroutines

The simplest F# semicoroutines via seq. comprehensions http://en.wikipedia.org/wiki/Coroutine Replaced a custom function with the pipeline operator.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
open System
let randGen = new Random()

let producer = 
    Seq.initInfinite (fun _ -> randGen.Next())

let consumer =
    Seq.initInfinite (fun _ -> (printfn "got %i"))
    
let combine producer consumer = 
    Seq.map2 (fun p c -> c p) producer consumer
    
combine producer consumer |> Seq.take 100 |> Seq.toArray |> ignore
namespace System
val randGen : Random

Full name: Script.randGen
Multiple items
type Random =
  new : unit -> Random + 1 overload
  member Next : unit -> int + 2 overloads
  member NextBytes : buffer:byte[] -> unit
  member NextDouble : unit -> float

Full name: System.Random

--------------------
Random() : unit
Random(Seed: int) : unit
val producer : seq<int>

Full name: Script.producer
module Seq

from Microsoft.FSharp.Collections
val initInfinite : initializer:(int -> 'T) -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.initInfinite
Random.Next() : int
Random.Next(maxValue: int) : int
Random.Next(minValue: int, maxValue: int) : int
val consumer : seq<(int -> unit)>

Full name: Script.consumer
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val combine : producer:seq<'a> -> consumer:seq<('a -> 'b)> -> seq<'b>

Full name: Script.combine
val producer : seq<'a>
val consumer : seq<('a -> 'b)>
val map2 : mapping:('T1 -> 'T2 -> 'U) -> source1:seq<'T1> -> source2:seq<'T2> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map2
val p : 'a
val c : ('a -> 'b)
val take : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.take
val toArray : source:seq<'T> -> 'T []

Full name: Microsoft.FSharp.Collections.Seq.toArray
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/iX
Posted:10 years ago
Author:Lakret
Tags: semicoroutines , coroutines