[cats "0.4.0"]
Category Theory abstractions for Clojure.
The main motivations for writting this library are:
The existing libraries does not have support for ClojureScript.
We do not intend to write a little haskell inside the clojure. We have adopted a practical and clojure like approach, always with corectness in mind.
We do not like viral/copyleft like licenses and with difference with other libraries cats is licensed under BSD (2 clauses) license.
We do not intend implement only monads. Other category theory abstractions are also first class in cats.
Alternatives:
algo.monads: This is the clojure official library for monads. Its approach for modeling monads is slightly limited, only supports the monad abstraction and does not has support for ClojureScript.
fluokitten: Slightly unmaintaned by the original author. It is focused on to be very practictical without take care of corectness (as example, it extends clojure types with monadic abstractions that not make sense). Also does not has support for ClojureScript.
monads: is the most advanced monads library, supports also functors, applicatives and other related abstractions. It lacks of good and readable documentation, fucused on correctness, has haskell like sugar syntax (instead of clojure like syntax) and not has support for ClojureScript.
All listed alternatives are licensed with EPL or similar licenses.
Since cats is a young project, there can be some API breakage.
This section covers installing cats.
The simplest way to use cats in a Clojure project is by including it as a dependency in your project.clj:
[cats "0.4.0"]
cats is open source and can be found on github.
You can clone the public repository with this command:
git clone https://github.com/funcool/cats
This section introduces almost all the category theory abstractions that the cats library supports.
We will use the Maybe for the example snippets, because it has support for all the abstractions and it is very easy to understand. You can read more about it in the next section of this documentation.
Let’s start with the functor. The Functor represents some sort of "computational context", and the abstraction consists of one unique function: fmap.
(fmap [f fv])
The higher-order function fmap takes a plain function as the first parameter and value wrapped in a functor context as the second parameter. It extracts the inner value applies the function to it, and returns the result wrapped in same type as the second parameter.
But, what is the functor context? It sounds more complex than it is. A Functor
wrapper is any type that acts as "Box" and implements the Context
and Functor
protocols.
(require '[cats.monad.maybe :as maybe])
(maybe/just 2)
;; => #<Just [2]>
The just
function is a constructor of Just type that is part of Maybe monad.
Let’s see one example using fmap over just instance:
(require '[cats.core :as m])
(m/fmap inc (maybe/just 1))
;; => #<Just [2]>
The Maybe type also has another constructor: nothing
. It represents the absence of a value.
It is a safe substitute for nil
and may represent failure.
Let’s see what happens if we perform the same operation as the previous example over a nothing instance:
(m/fmap inc (nothing))
;; => #<Nothing >
Oh, awesome, instead of raising a NullPointerException
, it just returns nothing. Another
advantage of using the functor abstraction, is that it always returns a result
of the same type as its second argument.
Let’s see an example of applying fmap over a Clojure vector:
(m/fmap inc [1 2 3])
;; => [2 3 4]
The main difference compared to the previous example with Clojure’s map function, is that map returns lazy seqs no matter what collection we pass to it:
(type (map inc [1 2 3]))
;; => clojure.lang.LazySeq (cljs.core/LazySeq in ClojureScript)
But why can we pass vectors to fmap
function? Because some Clojure container types like vectors,
lists and sets, also implement the functor abstraction.
Let’s continue with applicative functors. The Applicative Functor represents some sort of "computational context" like a plain Functor, but with ability to execute a function wrapped in the same context.
The Applicative Functor abstraction consists of two functions: fapply and pure.
(fapply [af av])
the pure function will be explained later. |
The use case for Applicative Functors is much the same as plain Functors: safe evaluation of some computation in a context.
Let’s see an example to better understand the differences between functor and applicative functor:
Imagine you have some factory function that, depending on the language, returns a greeter function, and you only support a few languages.
(defn make-greeter
[^String lang]
(condp = lang
"es" (fn [name] (str "Hola " name))
"en" (fn [name] (str "Hello " name))
nil))
Now, before using the resulting greeter you should always defensively check if returned greeter is a valid function or is a nil value.
Let’s convert this factory to use Maybe type:
(defn make-greeter
[^String lang]
(condp = lang
"es" (just (fn [name] (str "Hola " name)))
"en" (just (fn [name] (str "Hello " name)))
(nothing)))
As you can see, this version of the factory differs only slightly from the original implementation. And this tiny change gives you a new superpower: you can apply the returned greeter to any value without a defensive nil check:
(fapply (make-greeter "es") (just "Alex"))
;; => #<Just [Hola Alex]>
(fapply (make-greeter "en") (just "Alex"))
;; => #<Just [Hello Alex]>
(fapply (make-greeter "it") (just "Alex"))
;; => #<Nothing >
Moreover, the applicative functor comes with pure function, and the main purpose of this function is to put some value in side-effect-free context of the current type.
Examples:
(require '[cats.monad.maybe :as maybe])
(pure maybe/maybe-monad 5)
;; => #<Just [5]>
If you do not understand the purpose of the pure function, the next section should clarify its purpose.
Monads are the most discussed programming concept to come from category theory. Like functors and applicatives, monads deal with data in contexts.
Additionaly, monads can also transform contexts by unwrapping data, applying functions to it and putting new values in a completely different context.
The monad abstraction consists of two functions: bind and return
(bind [mv f])
As you can see, bind works much like a Functor but with inverted arguments. The main difference is that in a monad, the function is a responsible for wrapping a returned value in a context.
(m/bind (maybe/just 1)
(fn [v] (maybe/just (inc v))))
;; => #<Just [2]>
One of the key features of the bind function is that any computation executed within the context of
bind (monad) knows the context type implicitly. With this, if you apply some computation over some
monadic value and you want to return the result in the same container context but don’t know
what that container is, you can use return
or pure
functions:
(m/bind (maybe/just 1)
(fn [v]
(m/return (inc v))))
;; => #<Just [2]>
The return
or pure
functions, when called with one argument, try to use the dynamic scope context
value that’s set internally by the bind
function. Therefore, you can’t use them with one argument outside of a bind
context.
We now can compose any number of computations using monad bind functions. But observe what happens when the number of computations increases:
(m/bind (maybe/just 1)
(fn [a]
(m/bind (maybe/just (inc a))
(fn [b]
(m/return (* b 2))))))
This can quickly lead to callback hell. To solve this, cats comes with a powerful macro: mlet
(m/mlet [a (maybe/just 1)
b (maybe/just (inc a))]
(m/return (* b 2)))
If you are coming from Haskell, mlet represents the do-syntax. |
If you want to use regular (non-monadic) let bindings inside an mlet
block, you can do so using
:let
and a binding vector inside the mlet bindings:
(m/mlet [a (maybe/just 1)
b (maybe/just (inc a))
:let [z (+ a b)]]
(m/return (* z 2)))
We can combine two functors and get a new one automatically. Given any two functors a and b,
we can implement a generic fmap
for the type a (b Any), we’ll call it fmap2:
(ns functor.example
(:require [cats.core :refer [fmap]]
[cats.builtin]
[cats.monad.maybe :refer [just]]))
(defn fmap2
[f fv]
(fmap (partial fmap f) fv))
; Here, 'a' is [] and 'b' is Maybe, so the type of the
; combined functor is a vector of Maybe values that could
; contain a value of any type.
(fmap2 inc [(maybe/just 1) (maybe/just 2)])
;;=> [#<Just [2]> #<Just [3]>]
However, monads don’t compose as nicely as functors do. We have to actually implement the composition ourselves.
In some circumstances we would like combine the effects of two monads into another one. We call the resulting monad a monad transformer, which is the composition of a "base" and a "inner" monad. A monad transformer is itself a monad.
Let’s combine the effects of two monads: State and Maybe. We’ll create the transformer
using State as the base monad since we want the resulting type to be a stateful computation
that may fail: s → Maybe (a, s)
.
Almost every monad implemented in cats has a monad transformer for combining it with any other monad. The transformer functions take a Monad as their argument and they return a reified MonadTrans:
(ns transformers.example
(:require [cats.core :as m]
[cats.data :as data]
[cats.monad.maybe :as maybe]
[cats.monad.state :as state]))
(def maybe-state
(state/state-transformer maybe/maybe-monad))
(m/with-monad maybe-state
(state/run-state (m/return 42) {}))
;; => #<Just [#<Pair [42 {}]>]>
As we can see in the example below, the return of the maybe-state
monad creates a stateful
function that yields a Maybe containing a pair (value, next state).
You probably noticed that we had to wrap the state function invocation with cats.core/with-monad
.
When working with monad transformers, we have to be explicit about what monad we are using to implement
the binding policy since there is no way to distinguish values from a transformer type from those of
a regular monad.
The maybe-state
monad combines the semantics of both State and Maybe.
This is one of the two most used monad types (also known as Optional in other programming languages).
Maybe monad represents encapsulation of an optional value; e.g. it is used as the return type of functions which may or may not return a meaningful value when they are applied. It consists of either an empty constructor (called None or Nothing), or a constructor encapsulating the original data type A (written Just A or Some A).
cats, implements two types:
Just
that represents just a value in a context.
Nothing
that represents the abscense of value.
Just
and Nothing
types(maybe/just 1)
;; => #<Just [1]>
(maybe/nothing)
;; => #<Nothing >
In the same ns, it there other usefull functions for work with maybe monad types. See the api documentation for see a full list of them. But here we will exaplain a little relevant subset of they.
We mentioned above that fmap extracts the value from the functor context. You will also want to extract values wrapped by just and you can do that with from-maybe.
The Just or Nothing instances as we said previously, acts like a wrappers and in some circumstances
you will want extract the plain value from them. For it, cats offers the from-maybe
function.
(maybe/from-maybe (maybe/just 1))
;; => 1
(maybe/from-maybe (maybe/nothing))
;; => nil
(maybe/from-maybe (maybe/nothing) 42)
;; => 42
The from-maybe
function is a specialized version more generic one: cats.core/extract
. The generic
version is a polymorphic function and will work also with different types of different monads.
Either is another type that represents a result of computation, but (in contrast with maybe) it can return some data with a failed computation result.
In cats it has two constructors:
(left v)
: represents a failure.
(right v)
: represents a successful result.
(require '[cats.monad.either :refer :all])
(right :valid-value)
;; => #<Right [:valid-value :right]>
(left "Error message")
;; => #<Either [Error message :left]>
Either is also (like Maybe) Functor, Applicative Functor and Monad. |
Also known as Try monad, popularized by Scala.
It represents a computation that may either result in an exception or return a successfully computed value. Is very similar to Either monad, but is semantically different.
It consists in two types: Success and Failure. The Success type is a simple wrapper like Right of Either monad. But the Failure type is slightly different from Left, because it is forced to wrap an instance of Throwable (or Error in cljs).
The most common use case of this monad is for wrap third party libraries that uses standard Exception based error handling. In normal circumstances you should use Either instead.
It is an analogue of the try-catch block: it replaces try-catch’s stack-based error handling with heap-based error handling. Instead of having an exception thrown and having to deal with it immediately in the same thread, it disconnects the error handling and recovery.
(require '[cats.monad.exception :as exc])
(exc/try-on 1)
;; => #<Success [1]>
(exc/try-on (+ 1 nil))
;; => #<Failure [#<NullPointerException java.lang.NullPointerException>]>
cats comes with other syntactic sugar macros: try-or-else
that returns a default value if a
computation fails, and try-or-recover
that lets you handle the return value when executing a
function with the exception as first parameter.
try-or-else
macro.(exc/try-or-else (+ 1 nil) 2)
;; => #<Success [2]>
try-or-recover
macro.(exc/try-or-recover (+ 1 nil)
(fn [e]
(cond
(instance? NullPointerException e) 0
:else 100)))
;; => #<Success [0]>
The types defined for Exception monad (Success and Failure) also implementes the clojure IDeref interface, which facilitates libraries developing using monadic composition without forcing a user of that library to use or understand monads.
That is because when you will dereference the failure instance, it will reraise the containing exception.
(def f (exc/try-on (+ 1 nil)))
@f
;; => NullPointerException clojure.lang.Numbers.ops (Numbers.java:961)
State monad in one of the special cases of monads most used in Haskell. It has different purposes including: lazy computation, composition, and maintaining state without explicit state.
The de-facto monadic type of the state monad is a plain function. Function represents a computation as is (without executing it). Obviously, a function should have some special characteristics to work in monad state composition.
(fn [state]
"Takes state as argument and return a vector
with first argument with procesed value and
second argument the transformed new state."
(let [newvalue (first state)
newstate (next state)]
[newvalue newstate]))
You just saw an example of the low-level primitive state monad. For basic usage you do not need to build your own functions, just use some helpers that cats provides.
Let’s look at one example before explaining the details:
(require '[cats.monad.state :as st])
(m/mlet [state (st/get-state)
_ (st/put-state (next state))]
(return (first state)))
;;=> #<State cats.monad.state.State@2eebabb6>
At the moment of evaluation in the previous expression, nothing of that we have defined is executed. But instead of returning the unadorned final value of the computation, a strange/unknown object is returned of type State.
The State type is simply a wrapper for Clojure functions, nothing more.
Now, it’s time to execute the composed computation. For this we can use one of the following
functions exposed by cats: run-state
, eval-state
and exec-state
.
run-state
function executes the composed computation and returns both the value and the
result state.
eval-state
function executes the composed computation and returns the resulting value
discarding the state.
exec-state
function executes the composed computation and return only the resulting
state, ignoring the resulting value.
(m/run-state s [1 2 3])
;;=> #<Pair [1 (2 3)]>
(m/eval-state s [1 2 3])
;;=> 1
(m/exec-state s [1 2 3])
;;=> (2 3)
The run-state
function returns an instance of Pair type. The Pair type acts like any other seq in
clojure with the exception that it only can contain two values.
TODO
TODO
TODO
TODO
Some monads are defined as separated package for avoid add additional and unnecesary dependencies to cats library.
Channel monad: https://github.com/funcool/cats-channel
In contrast to other similar libraries in Clojure, cats doesn’t intend to extend Clojure types that don’t act like containers. For example, Clojure keywords are values but can not be containers so they should not extend any of the previously explained protocols.
Name | Implemented protocols |
---|---|
vector | Functor, Applicative, Monad, MonadZero, MonadPlus |
hash-set | Functor, Applicative, Monad, MonadZero, MonadPlus |
list | Functor, Applicative, Monad, MonadZero, MonadPlus |
Five most important rules:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Readability counts.
All contributions to cats should keep these important rules in mind.
cats does not have many restrictions for contributions. Just follow these steps depending on the situation:
Bugfix:
Fork the GitHub repo.
Fix a bug/typo on a new branch.
Make a pull-request to master.
New feature:
Open new issue with the new feature proposal.
If it is accepted, follow the same steps as "bugfix".
Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.be>
Copyright (c) 2014-2015 Alejandro Gómez
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Can you improve this documentation? These fine people already did:
Andrey Antukh, Alejandro Gómez & Christian RomneyEdit on GitHub
cljdoc is a website building & hosting documentation for Clojure/Script libraries
× close