0 people like it.

Minimal Adaptive Cells (fable compatible)

An implementation of minimal adaptive cells

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
type Cell<'T>(initial: 'T) =
    let mutable value = initial
    let mutable listeners : (unit -> unit) list = []  
    member _.Value = value
    member _.Set v =
        value <- v
        for l in listeners do l()
    
    member _.Subscribe(callback: unit -> unit) =
        listeners <- callback :: listeners

type RuleBuilder() =
    member _.Bind(cell: Cell<'T>, f: 'T -> unit) =
        f cell.Value
        cell.Subscribe(fun () -> f cell.Value)
    member _.Return(x) = x
    member _.Delay(f: unit -> unit) = f()
    member _.Zero() = () 

let rule = RuleBuilder()

// Define some reactive cells.
let a = Cell(3)
let b = Cell(4)
let sum = Cell(0)

// Create a reactive rule that computes the sum of a and b.
rule {
    let! va = a
    let! vb = b
    sum.Set (va + vb)
}

printfn "Initial sum: %d" sum.Value

// Changing 'a' will automatically update the computed sum.
a.Set 10
printfn "Updated sum: %d" sum.Value
Multiple items
type Cell<'T> =
  new : initial:'T -> Cell<'T>
  member Set : v:'T -> unit
  member Subscribe : callback:(unit -> unit) -> unit
  member Value : 'T

--------------------
new : initial:'T -> Cell<'T>
val initial : 'T
val mutable value : 'T
val mutable listeners : (unit -> unit) list
type unit = Unit
type 'T list = List<'T>
Multiple items
module Set

from Microsoft.FSharp.Collections

--------------------
type Set<'T (requires comparison)> =
  interface IReadOnlyCollection<'T>
  interface IComparable
  interface IEnumerable
  interface IEnumerable<'T>
  interface ICollection<'T>
  new : elements:seq<'T> -> Set<'T>
  member Add : value:'T -> Set<'T>
  member Contains : value:'T -> bool
  override Equals : obj -> bool
  member IsProperSubsetOf : otherSet:Set<'T> -> bool
  ...

--------------------
new : elements:seq<'T> -> Set<'T>
val v : 'T
val l : (unit -> unit)
val callback : (unit -> unit)
Multiple items
type RuleBuilder =
  new : unit -> RuleBuilder
  member Bind : cell:Cell<'T> * f:('T -> unit) -> unit
  member Delay : f:(unit -> unit) -> unit
  member Return : x:'a -> 'a
  member Zero : unit -> unit

--------------------
new : unit -> RuleBuilder
val cell : Cell<'T>
val f : ('T -> unit)
property Cell.Value: 'T with get
member Cell.Subscribe : callback:(unit -> unit) -> unit
val x : 'a
val f : (unit -> unit)
val rule : RuleBuilder
val a : Cell<int>
val b : Cell<int>
val sum : Cell<int>
val va : int
val vb : int
member Cell.Set : v:'T -> unit
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
property Cell.Value: int with get
Raw view Test code New version

More information

Link:http://fssnip.net/8aI
Posted:5 days ago
Author:Onur Gumus
Tags: computation expressions