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 / AsyncValue.fs
Last active October 11, 2018 20:45
Async Value
// An asynchronous value
let valAsync = async { return 42 }
@dbrattli
dbrattli / AsyncFunc.fs
Last active October 16, 2018 05:06
Asynchronoush Function
// An asynchronous function taking a long time before "returning" a value
let funcAsync () =
async {
do! Async.Sleep 5000
return 42
}
@dbrattli
dbrattli / Callback.fs
Last active October 7, 2018 09:40
Callback
// Callback handler
let myCallback x =
printfn "Got %A" x
// Asynchronous function taking a callback handler
let asyncFun x cb =
let result = x * 10
cb result
// Call function with provided callback handler
@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
@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 / 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 / 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 / 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 / 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 / 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