Skip to content

Instantly share code, notes, and snippets.

@isamert
Last active August 21, 2017 20:09
Show Gist options
  • Save isamert/35138ce507e33d430ca6cc3c1aac60ff to your computer and use it in GitHub Desktop.
Save isamert/35138ce507e33d430ca6cc3c1aac60ff to your computer and use it in GitHub Desktop.
Category Theory for Programmers (Exercise solutions)
//
// Category: The Essence of Composition
//
// id function
fun <T> id(a: T) = a
// compose function
fun <A, B, C> compose(a: (A) -> B, b: (B) -> C) = { x: A -> b(a(x)) }
// infix way of doing that
infix fun <A, B, C> ((A) -> B).then(b: (B) -> C) = { x: A -> b(this(x)) }
//
// Types and Functions
//
// memoize function
fun <A, B> ((A) -> B).memoize(): (A) -> B = object : (A) -> B {
private val map = mutableMapOf<A, B>()
override fun invoke(p1: A) = map.getOrPut(p1) { this@memoize(p1) }
}
// ::someFunction.memoize()(parameter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment