Skip to content

Instantly share code, notes, and snippets.

View dbrattli's full-sized avatar
👨‍💻
Python ❤️ F#

Dag Brattli dbrattli

👨‍💻
Python ❤️ F#
View GitHub Profile
@dbrattli
dbrattli / PromiseTimer.fs
Created October 14, 2018 12:45
Promise Timer
module Promise =
let sleep msecs =
let promise = Promise<unit> ()
let timer = new System.Timers.Timer (float msecs)
timer.AutoReset <- false
let eventHandler ev =
promise.Resolve ()
timer.Elapsed.Add eventHandler
@dbrattli
dbrattli / PromiseReject.fs
Created October 14, 2018 12:36
Promise reject
let pr = Promise ()
pr.Catch (fun err -> printfn "Got Exception: %A" (err.ToString ())) |> ignore
pr.Reject (Exception "error")
@dbrattli
dbrattli / PromiseResolve.fs
Created October 14, 2018 12:25
Promise resolve
let pr = Promise ()
pr.Then (fun x -> printfn "Got value: %A" x) |> ignore
pr.Resolve 42
@dbrattli
dbrattli / Promise.fs
Last active January 3, 2019 09:10
Promise
type Promise<'a> () =
let mutable result : Result<'a, exn> option = None
let thenCbs = List<Callback<'a>> ()
let catchCbs = List<Callback<exn>> ()
member this.Resolve (value: 'a) =
result <- Some <| Ok value
for cb in thenCbs do
cb value
@dbrattli
dbrattli / Times10CpsCurried.fs
Last active October 7, 2018 19:46
Times 10 Curried Continuation
// Return a function that takes a callback that takes the result.
let times10 (x: int) : ((int -> unit) -> unit) =
let thenDo (cb : int -> unit) =
cb (x * 10)
thenDo
let cb result =
printfn "%A" result
let thenDo = times10 42
@dbrattli
dbrattli / times10Cps.fs
Last active October 16, 2018 04:59
Times10 CPS
let times10 (x : int) (cont : int -> unit) : unit =
cont (x * 10)
let cb result =
printfn "%A" result
do times10 42 cb
@dbrattli
dbrattli / PythagorasCPSUnindented.fs
Last active October 15, 2018 09:17
Pythagoras CPS Unindented
// Unindented Pythagoras CPS
let pythagorasCps a b return' : unit =
squareCps a (fun aa ->
squareCps b (fun bb ->
addCps aa bb (fun aabb ->
sqrtCps aabb (fun result ->
return' result))))
@dbrattli
dbrattli / PythagorasLet.fs
Last active October 15, 2018 09:17
Pythagoras With Let Statements
// Pythagoras rewritten using 'let' statements
let pythagoras a b =
let aa = square a
let bb = square b
let aabb = add aa bb
let result = sqrt aabb
result
@dbrattli
dbrattli / PythagorasCPS.fs
Created October 7, 2018 10:42
Pythagoras CPS
let addCps a b cont : unit =
cont (a + b)
let squareCps x cont : unit =
cont (x * x)
let sqrtCps x cont : unit =
cont (sqrt x)
// Pythagoras rewritten in CPS
@dbrattli
dbrattli / Pythagoras.fs
Created October 7, 2018 10:38
Pythagoras
let add a b = a + b
let square x = x * x
let pythagoras a b = sqrt (add (square a) (square b))
let result = pythagoras 10.0 20.0