Created
May 2, 2014 12:21
-
-
Save tcsavage/c52524729a3741bc988a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; F-Algebra recursion schemes: | |
(defprotocol Functor | |
"Functor" | |
(fmap [xs f])) | |
(defn cata [alg f] (alg (fmap f (partial cata alg)))) | |
(defn ana [coalg a] (fmap (coalg a) (partial ana coalg))) | |
(defn hylo [alg coalg a] (cata alg (ana coalg a))) | |
;; Factorial via ListF example: | |
(deftype ListFCons [value rec] | |
Functor | |
(fmap [this f] (ListFCons. value (f rec)))) | |
(deftype ListFNull [] | |
Functor | |
(fmap [this f] (ListFNull.))) | |
;; Product algebra. Equivalent to (reduce * 1) but for a single step only | |
(defmulti productAlg class) | |
(defmethod productAlg ListFCons [l] (* (.value l) (.rec l))) | |
(defmethod productAlg ListFNull [_] 1) | |
;; [1..n] coalgebra. Equivalent to (comp (partial range 1) (partial + 1)) but for a single step only | |
(defn oneToNCoalg [n] (if (= n 0) (ListFNull.) (ListFCons. n (- n 1)))) | |
(def factorial (partial hylo productAlg oneToNCoalg)) | |
(factorial 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment