Skip to content

Commit

Permalink
categories firs implementation and Fn instance
Browse files Browse the repository at this point in the history
  • Loading branch information
antoniogarrote committed Nov 18, 2010
1 parent acfb55f commit d119f0b
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/clj_control/category.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
(ns clj-control.category)

(defprotocol Category
"class Category cat where
id ::cat a a
(.) :: cat b c -> cat a b -> cat a c"
(c-id [this])
(c-comp [this c]))


(defn >>>
"(>>>) :: Category cat => cat a b -> cat b c -> cat a c
Left-to-right composition "
([cab cbc]
(c-comp cab cbc))
([cab cbc & args]
(if (empty? args)
(c-comp cab cbc)
(apply >>> (cons (c-comp cab cbc) args)))))


(defn <<<
"(<<<) :: Category cat => cat b c -> cat a b -> cat a c
Right-to-left composition"
([cbc cab]
(c-comp cab cbc))
([cbc cab & args]
(apply >>> (reverse (flatten (list [cbc cab] args))))))
7 changes: 6 additions & 1 deletion src/clj_control/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
(:use [clj-control.functor]
[clj-control.applicative]
[clj-control.monad]
[clj-control.monoid]))
[clj-control.monoid]
[clj-control.category]))

;; Functions

Expand Down Expand Up @@ -40,6 +41,10 @@
(m->> [this m]
(default-m->> this m)))

(extend-type clojure.lang.Fn
Category
(c-id [this] this)
(c-comp [this c] (comp c this)))

;; Vectors

Expand Down
3 changes: 3 additions & 0 deletions test/clj_control/test/applicative.clj
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@
(repeat '())
(let [xs (first matrix)
xss (rest matrix)]
;; (-> (repeat (count xs) (curry 2 cons))
;; (af-* xs)
;; (af-* (take (count xs) (transpose xss))))))))
(af-*
(af-* (repeat (count xs) (curry 2 cons)) xs)
(take (count xs) (transpose xss)))))))
Expand Down
14 changes: 14 additions & 0 deletions test/clj_control/test/category.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
(ns clj-control.test.category
(:use [clj-control.category] :reload)
(:use [clj-control.core] :reload)
(:use [clj-control.utils] :reload)
(:use [clojure.test]))


(deftest functions-should-work-with-the->>>-combinator
(is (= ((>>> inc inc (partial * 2) inc inc inc (partial * 3)) 3)
39)))

(deftest functions-should-work-with-the-<<<-combinator
(is (= ((<<< inc inc (partial * 2) inc inc inc (partial * 3)) 3)
26)))

0 comments on commit d119f0b

Please sign in to comment.