Skip to content

Instantly share code, notes, and snippets.

@c2d7fa
c2d7fa / generator.scm
Last active August 21, 2021 18:31
Generators in terms of call/cc
(define (generator p)
(set! gc #f) ; Continuation in generator
(lambda ()
(call/cc (lambda (return)
(if gc
(gc #f)
(p (lambda (value)
(call/cc (lambda (cgc)
(set! gc cgc)
(return value))))))))))
@c2d7fa
c2d7fa / 01-free-monad-state.ts
Last active March 5, 2024 06:27
Expressing a specific instance of the free monad in TypeScript
// https://underscore.io/blog/posts/2015/04/23/deriving-the-free-monad.html
// Example of implementing a specific instance of a free monad (for getting and
// setting an integer value) in TypeScript. The type system is not expressive
// enough to express free monads in general, but we can express a specific
// instance.
type AtomicOperation<T> = ["get", (x: number) => T] | ["set", number, T];
type Program<T> = ["return", T] | ["suspend", AtomicOperation<Program<T>>];