<commit_before>Category Theory abstractions for Clojure
========================================
<NAME> & <NAME>
0.1.0, 2014-07-08

:toc:

image:static/logo/logo.png[cats logo]

Introduction
------------

Category Theory abstractions for Clojure.


Philosophy
~~~~~~~~~

Four most important rules:

- Beautiful is better than ugly
- Explicit is better than implicit
- Simple is better than complex
- Readability counts

Why another library?
~~~~~~~~~~~~~~~~~~~~

Because cats library:

- targets both most used clojure implementations:  *Clojure (jvm)* and *ClojureScript(js)*
- aims to have the most simple implementation for supported abstractions.
- aims to have more abstractions that are simple monads.
- has documentation as first class citizen.
- licensed under a permissive license (compared to other libraries): BSD (2-Clause)

This is an incomplete list of differences with other existing libraries:

- The official monads library `algo.monads` is very good, but its approach for modeling
  is slighty limited (e.g. you always need to specify what monad you want use instead of
  relying on the type). And obviously because it only has monads.
- Fluokitten is the best library that we found, but the future of it is uncertain. One big
  difference with fluokitten is that `cats` doesn't aim to extend every clojure type
  with monadic protocols, for the obvious reason that monad; functor and applicative represents
  context/wrapper types and it doesn't make sense to implement Functor protocol for `java.lang.String`.
- `bwo/monads` is the last monads library. It is completely undocumented and its implementation
  has much unnecesary complexity.


Project Maturity
~~~~~~~~~~~~~~~~

Since _cats_ is a young project there can be some link:codox/index.html#id[API]
breakage.


Install
-------

This section covers installing _cats_.


Requirements
~~~~~~~~~~~~

_cats_ supports:

- JDK7
- JDK8


Leiningen
~~~~~~~~~

The simplest way to use _cats_ in a Clojure project is by including
it as a dependency in your *_project.clj_*:

._in project.clj_
[source,clojure]
----
[cats "0.1.0"]
----

Maven
~~~~~

Also, you can use it with maven. First, add the clojars repository:

[source,xml]
----
<repository>
    <id>clojars.org</id>
    <url>http://clojars.org/repo</url>
</repository>
----

Then for cats:

[source,xml]
----
<dependency>
    <groupId>cats</groupId>
    <artifactId>cats</artifactId>
    <version>0.1.0</version>
</dependency>
----


Get the Code
~~~~~~~~~~~~

_cats_ is opensource and is entirely developed on link:https://github.com/niwibe/cats[github].

You can clone the public repository with this command:

[source,text]
----
git clone https://github.com/niwibe/cats
----

Protocols reference
-------------------

**In this section, we are using _Maybe_ type for all examples. You can read more about
it in the next section.**

Functor
~~~~~~~

The Functor represents some sort of "computational context".

.Functor protocol
[source, clojure]
----
(defprotocol Functor
  (fmap [fv f]
    "Applies function f to the value(s) inside
    the context of the functor fv."))
----

`fmap` takes one wrapped value in functor context fv (ex: `Just 2`) and a plain function,
unwraps the value and applies a function to the plain value returning it wrapped in a new context
of *the same type* as the first argument.

Some examples can explain it better:

[source, clojure]
----
(require '[cats.core :refer :all])
(require '[cats.types :refer :all])

(fmap inc (just 1))
;; => #<Just [2]>
----

Same example but applying function over **Nothing**:

[source, clojure]
----
(fmap inc (nothing))
;; => #<Nothing >
----

[NOTE]
====
The real fmap signature is `(a -> b) -> f a -> f b` that can be translated to clojure `[f fv]`.

The changed order of the protocol parameters definition is required because of clojure's protocols
limitation that only allow dispatching on the first argument.

You should never use a protocol function directly. Instead use `cats.core/fmap`. It has
the correct signature.

All examples in this documentation uses `cats.core/fmap` instead of a function defined in the
protocol.
====

Some of the native clojure types, like Vector, also implements the Functor protocol and can
work like a functor context/container:

[source, clojure]
----
(fmap inc [1 2 3])
;; => [2 3 4]
----

The main difference compared to the previous example with default clojure map, is that the clojure
map works with seqs and doesn't respect the input container:

[source, clojure]
----
(map inc [1 2 3])
;; => (2 3 4)
----


Applicative Functor
~~~~~~~~~~~~~~~~~~~

Represents an abstraction lying in between Functor and Monad in expressivity.

.Applicative protocol
[source, clojure]
----
(defprotocol Applicative
  (fapply [af av]
    "Applies the function(s) inside ag's context to the value(s)
     inside av's context while preserving the context.")
  (pure [ctx v]
    "Takes any context monadic value ctx and any value v, and puts
     the value v in the most minimal context of the same type of ctx"))
----

With the same idea of data inside a context (like `Functor`), what happens if a wrapped value is
one function/computation? Applicative functors works like plain functors but additionally
can apply a function wrapped in some context similar to input value.

Let see one example:

[source, clojure]
----
(defn make-greeter
  [^String lang]
  (condp = lang
    "es" (just (fn [name] (str "Hola " name)))
    "en" (just (fn [name] (str "Hello " name)))
    (nothing)))

(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 protocol comes with another function: `pure`. The main purpose of 
this function is, given any value in a context and new value, wrap the new value in a minimal context of the same
type as the first argument.

Examples:

[source, clojure]
----
(pure (just 1) 5)
;; => #<Just [5]>

(pure (right :foo) :bar)
;; => #<Either [:bar :right]>
----

You will understand the real purpose of this function when using a **Monad** abstraction.


Monad
~~~~~

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 context by unwrapping data, applying functions to it and
put new values in a completely different context.

.Monad protocol
[source, clojure]
----
(defprotocol Monad
  "Incomplete monad type definition."
  (bind [mv f] "Applies the function f to the value(s) inside mv's context."))
----

NOTE: As opposed to haskell type classes, _cats_ protocols only define one method: `bind`. Other
related methods like `return` are defined as auxiliar functions in `cats.core`.

`bind` function, takes a monadic value (any container that implements a `Monad` protocol) and one
function, applies the function with unwrapped value as first parameter and returns a result. In this
case, the function is responsible for wrapping the result in a corresponding context.

One of the key features of the bind function is that everything inside a monad context knows the context
type. Having this, if you apply some computation over a monad and you want to return the result
in the same container context but you don't know that container is it, you can use `return` or `pure`.

[source, clojure]
----
(bind (just 1) (fn [v] (return (inc v))))
;; => #<Just [2]>
----

`return` or `pure` function with one argument, try takes a context value from dynamic scope collected
internaly by `bind` function, so that, you can not use them with one argument out of `bind` context.

And finally, to make more powerful monadic compositions, _cats_ comes with the `mlet` macro that
if you are coming from haskell, represents a `do-syntax`:

[source, clojure]
----
(mlet [x (just 1)
       y (just 2)
       z (just (+ x y))]
  (return z))
;; => #<Just [3]>
----

If you want to use regular (non-monadic) let bindings inside a `mlet` block, you can do so using
`:let` and a bindings vector as a pair inside the mlet bindings:

[source, clojure]
----
(mlet [x (just 1)
       y (just 2)
       :let [z (+ x y)]]
  (return z))
;; => #<Just [3]>
----

MonadZero
~~~~~~~~~

The link:http://www.haskell.org/haskellwiki/MonadPlus_reform_proposal#MonadZero[MonadZero] protocol
represents a monad that has a notion of an identity element.

.MonadZero protocol
[source, clojure]
----
(defprotocol MonadZero
  "A `Monad` that supports the notion of an identity element."
  (mzero [ctx] "The identity element for `ctx`."))
----

The `bind` operation on the identity element satisfies Left Zero:

[source, clojure]
----
(mzero (just 1))
;; => #<Nothing >

(= (mzero (just 1))
   (>>= (mzero (just 1)) just))
;; => true
----

When a monad instance implements the MonadZero protocol, `:when` clauses can be used in `mlet`
bindings:

[source, clojure]
----
(mlet [i [1 2 3 4 5]
       :when (> i 2)]
      (return i))
;; => [3 4 5]

(mlet [i (t/just 2)
       :when (> i 2)]
      (m/return i))
;; => #<Nothing >
----

MonadPlus
~~~~~~~~~

The link:http://www.haskell.org/haskellwiki/MonadPlus_reform_proposal#MonadPlus[MonadPlus] protocol
represents a MonadZero wich has a plus operation.

.MonadPlus protocol
[source, clojure]
----
(defprotocol MonadPlus
  "A `MonadZero` that supports the notion of addition."
  (mplus [mv mv'] "An associative addition operation."))
----

`mplus` is an associative binary operation for which the value that `mzero` gives is the identity
element. The `mplus` version contained in the core namespace is variadic.

[source, clojure]
----
(require '[cats.types :refer [just nothing]])
(require '[cats.core :refer [mplus]])

(mplus [1 2 3] [4 5 6] [7 8])
;; => [1 2 3 4 5 6 7 8]

(mplus (nothing))
;; => #<Nothing >

(mplus (nothing) (just 42))
;; => #<Just [42]>

(mplus (nothing) (just 42) (just 3))
;; => #<Just [42]>
----


Data Types reference
--------------------

We talked about values in a context, but that is a context? Context per se is any value that
wraps an other value inside.

Maybe
~~~~~


This is one of the two most used monad types (commonly named Optional in non-functional programming
languages).

Maybe/Optional is a polymorphic type that 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 constructors:

- `(just v)`: represents just a value in a context.
- `(nothing)`: represents a failure or null.


[source, clojure]
----
(require '[cats.types :refer :all])
(just 1)
;; => #<Just [1]>
(nothing)
;; => #<Nothing >
----

NOTE: Maybe types are: Functors, Applicative Functors and Monads


Either
~~~~~~

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.

[source, clojure]
----
(require '[cats.types :refer :all])

(right :valid-value)
;; => #<Right [:valid-value :right]>

(left "Error message")
;; => #<Either [Error message :left]>
----

NOTE: Either is also (like Maybe) Functor, Applicative Functor and Monad.

Clojure Types
-------------

Besides the own types, some clojure types has implementations for previously explained
category theory abstractions.

NOTE: 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.


.Summary of clojure types and implemented protocols
[options="header"]
|=============================================================
| Name     | Implemented protocols
| vector   | Functor, Applicative, Monad, MonadZero, MonadPlus
| hash-set | Functor, Applicative, Monad, MonadZero, MonadPlus
| list     | Functor, Applicative, Monad, MonadZero, MonadPlus
| atom     | No one (in future)
|=============================================================


Special use cases of monads
--------------------------

State monad
~~~~~~~~~~~

State monad in one of the special use 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.

.Valid function for valid state monad
[source, clojure]
----
(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]))
----

Right, you just saw an example of the low level primitive of state monad but for basic usage
you do not need to build your own functions, just use some helpers that _cats_ gives you.

Let's look at one example before explaining the details:

.Lazy composition of computations
[source, clojure]
----
(m/mlet [state (m/get-state)
         _     (m/put-state (next state))]
  (return (first state)))
;;=> #<State cats.types.State@2eebabb6>
----

At the moment of evaluating the previous expression, anything that we have defined
is executed. Instead of the finished value of the computation, a strange/unknown object is returned of type *State*.

State is a simple wrapper for clojure functions, nothing more.

Now, it 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.

.This is what happens when we execute these three functions over previously generated `State` instance
[source, clojure]
----
(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)
----

NOTE: the pair instance returned by `run-state` functions works like any other seq of clojure, with
the difference that pairs can only have two slots.

This is a very basic example of the state monad, it has a lot of use cases and explaining all them
seems out of the scope of this document.

However, if you have better examples to explain the state monad, documentation for another monad or 
any other contribution is always welcome.

License
-------

[source,text]
----
Copyright (c) 2014, <NAME>
Copyright (c) 2014, <NAME>

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.
----
<commit_msg>Update cats.asciidoc<commit_after>Category Theory abstractions for Clojure
========================================
<NAME> & <NAME>
0.1.0, 2014-07-08

:toc:

image:static/logo/logo.png[cats logo]

Introduction
------------

Category Theory abstractions for Clojure.


Philosophy
~~~~~~~~~

Four most important rules:

- Beautiful is better than ugly
- Explicit is better than implicit
- Simple is better than complex
- Readability counts

Why another library?
~~~~~~~~~~~~~~~~~~~~

Because cats library:

- targets both most used clojure implementations:  *Clojure (jvm)* and *ClojureScript(js)*
- aims to have the most simple implementation for supported abstractions.
- aims to have more abstractions that are simple monads.
- has documentation as first class citizen.
- licensed under a permissive license (compared to other libraries): BSD (2-Clause)

This is an incomplete list of differences with other existing libraries:

- The official monads library `algo.monads` is very good, but its approach for modeling
  is slighty limited (e.g. you always need to specify what monad you want use instead of
  relying on the type). And obviously because it only has monads.
- Fluokitten is the best library that we found, but the future of it is uncertain. One big
  difference with fluokitten is that `cats` doesn't aim to extend every clojure type
  with monadic protocols, for the obvious reason that monad; functor and applicative represents
  context/wrapper types and it doesn't make sense to implement Functor protocol for `java.lang.String`.
- `bwo/monads` is the last monads library. It is completely undocumented and its implementation
  has much unnecesary complexity.


Project Maturity
~~~~~~~~~~~~~~~~

Since _cats_ is a young project there can be some link:codox/index.html#id[API]
breakage.


Install
-------

This section covers installing _cats_.


Requirements
~~~~~~~~~~~~

_cats_ supports:

- JDK7
- JDK8


Leiningen
~~~~~~~~~

The simplest way to use _cats_ in a Clojure project is by including
it as a dependency in your *_project.clj_*:

[source,clojure]
----
[cats "0.1.0"]
----

Maven
~~~~~

Also, you can use it with maven. First, add the clojars repository:

[source,xml]
----
<repository>
    <id>clojars.org</id>
    <url>http://clojars.org/repo</url>
</repository>
----

Then for cats:

[source,xml]
----
<dependency>
    <groupId>cats</groupId>
    <artifactId>cats</artifactId>
    <version>0.1.0</version>
</dependency>
----


Get the Code
~~~~~~~~~~~~

_cats_ is opensource and is entirely developed on link:https://github.com/niwibe/cats[github].

You can clone the public repository with this command:

[source,text]
----
git clone https://github.com/niwibe/cats
----

Protocols reference
-------------------

**In this section, we are using _Maybe_ type for all examples. You can read more about
it in the next section.**

Functor
~~~~~~~

The Functor represents some sort of "computational context".

.Functor protocol
[source, clojure]
----
(defprotocol Functor
  (fmap [fv f]
    "Applies function f to the value(s) inside
    the context of the functor fv."))
----

`fmap` takes one wrapped value in functor context fv (ex: `Just 2`) and a plain function,
unwraps the value and applies a function to the plain value returning it wrapped in a new context
of *the same type* as the first argument.

Some examples can explain it better:

[source, clojure]
----
(require '[cats.core :refer :all])
(require '[cats.types :refer :all])

(fmap inc (just 1))
;; => #<Just [2]>
----

Same example but applying function over **Nothing**:

[source, clojure]
----
(fmap inc (nothing))
;; => #<Nothing >
----

[NOTE]
====
The real fmap signature is `(a -> b) -> f a -> f b` that can be translated to clojure `[f fv]`.

The changed order of the protocol parameters definition is required because of clojure's protocols
limitation that only allow dispatching on the first argument.

You should never use a protocol function directly. Instead use `cats.core/fmap`. It has
the correct signature.

All examples in this documentation uses `cats.core/fmap` instead of a function defined in the
protocol.
====

Some of the native clojure types, like Vector, also implements the Functor protocol and can
work like a functor context/container:

[source, clojure]
----
(fmap inc [1 2 3])
;; => [2 3 4]
----

The main difference compared to the previous example with default clojure map, is that the clojure
map works with seqs and doesn't respect the input container:

[source, clojure]
----
(map inc [1 2 3])
;; => (2 3 4)
----


Applicative Functor
~~~~~~~~~~~~~~~~~~~

Represents an abstraction lying in between Functor and Monad in expressivity.

.Applicative protocol
[source, clojure]
----
(defprotocol Applicative
  (fapply [af av]
    "Applies the function(s) inside ag's context to the value(s)
     inside av's context while preserving the context.")
  (pure [ctx v]
    "Takes any context monadic value ctx and any value v, and puts
     the value v in the most minimal context of the same type of ctx"))
----

With the same idea of data inside a context (like `Functor`), what happens if a wrapped value is
one function/computation? Applicative functors works like plain functors but additionally
can apply a function wrapped in some context similar to input value.

Let see one example:

[source, clojure]
----
(defn make-greeter
  [^String lang]
  (condp = lang
    "es" (just (fn [name] (str "Hola " name)))
    "en" (just (fn [name] (str "Hello " name)))
    (nothing)))

(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 protocol comes with another function: `pure`. The main purpose of 
this function is, given any value in a context and new value, wrap the new value in a minimal context of the same
type as the first argument.

Examples:

[source, clojure]
----
(pure (just 1) 5)
;; => #<Just [5]>

(pure (right :foo) :bar)
;; => #<Either [:bar :right]>
----

You will understand the real purpose of this function when using a **Monad** abstraction.


Monad
~~~~~

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 context by unwrapping data, applying functions to it and
put new values in a completely different context.

.Monad protocol
[source, clojure]
----
(defprotocol Monad
  "Incomplete monad type definition."
  (bind [mv f] "Applies the function f to the value(s) inside mv's context."))
----

NOTE: As opposed to haskell type classes, _cats_ protocols only define one method: `bind`. Other
related methods like `return` are defined as auxiliar functions in `cats.core`.

`bind` function, takes a monadic value (any container that implements a `Monad` protocol) and one
function, applies the function with unwrapped value as first parameter and returns a result. In this
case, the function is responsible for wrapping the result in a corresponding context.

One of the key features of the bind function is that everything inside a monad context knows the context
type. Having this, if you apply some computation over a monad and you want to return the result
in the same container context but you don't know that container is it, you can use `return` or `pure`.

[source, clojure]
----
(bind (just 1) (fn [v] (return (inc v))))
;; => #<Just [2]>
----

`return` or `pure` function with one argument, try takes a context value from dynamic scope collected
internaly by `bind` function, so that, you can not use them with one argument out of `bind` context.

And finally, to make more powerful monadic compositions, _cats_ comes with the `mlet` macro that
if you are coming from haskell, represents a `do-syntax`:

[source, clojure]
----
(mlet [x (just 1)
       y (just 2)
       z (just (+ x y))]
  (return z))
;; => #<Just [3]>
----

If you want to use regular (non-monadic) let bindings inside a `mlet` block, you can do so using
`:let` and a bindings vector as a pair inside the mlet bindings:

[source, clojure]
----
(mlet [x (just 1)
       y (just 2)
       :let [z (+ x y)]]
  (return z))
;; => #<Just [3]>
----

MonadZero
~~~~~~~~~

The link:http://www.haskell.org/haskellwiki/MonadPlus_reform_proposal#MonadZero[MonadZero] protocol
represents a monad that has a notion of an identity element.

.MonadZero protocol
[source, clojure]
----
(defprotocol MonadZero
  "A `Monad` that supports the notion of an identity element."
  (mzero [ctx] "The identity element for `ctx`."))
----

The `bind` operation on the identity element satisfies Left Zero:

[source, clojure]
----
(mzero (just 1))
;; => #<Nothing >

(= (mzero (just 1))
   (>>= (mzero (just 1)) just))
;; => true
----

When a monad instance implements the MonadZero protocol, `:when` clauses can be used in `mlet`
bindings:

[source, clojure]
----
(mlet [i [1 2 3 4 5]
       :when (> i 2)]
      (return i))
;; => [3 4 5]

(mlet [i (t/just 2)
       :when (> i 2)]
      (m/return i))
;; => #<Nothing >
----

MonadPlus
~~~~~~~~~

The link:http://www.haskell.org/haskellwiki/MonadPlus_reform_proposal#MonadPlus[MonadPlus] protocol
represents a MonadZero wich has a plus operation.

.MonadPlus protocol
[source, clojure]
----
(defprotocol MonadPlus
  "A `MonadZero` that supports the notion of addition."
  (mplus [mv mv'] "An associative addition operation."))
----

`mplus` is an associative binary operation for which the value that `mzero` gives is the identity
element. The `mplus` version contained in the core namespace is variadic.

[source, clojure]
----
(require '[cats.types :refer [just nothing]])
(require '[cats.core :refer [mplus]])

(mplus [1 2 3] [4 5 6] [7 8])
;; => [1 2 3 4 5 6 7 8]

(mplus (nothing))
;; => #<Nothing >

(mplus (nothing) (just 42))
;; => #<Just [42]>

(mplus (nothing) (just 42) (just 3))
;; => #<Just [42]>
----


Data Types reference
--------------------

We talked about values in a context, but that is a context? Context per se is any value that
wraps an other value inside.

Maybe
~~~~~


This is one of the two most used monad types (commonly named Optional in non-functional programming
languages).

Maybe/Optional is a polymorphic type that 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 constructors:

- `(just v)`: represents just a value in a context.
- `(nothing)`: represents a failure or null.


[source, clojure]
----
(require '[cats.types :refer :all])
(just 1)
;; => #<Just [1]>
(nothing)
;; => #<Nothing >
----

NOTE: Maybe types are: Functors, Applicative Functors and Monads


Either
~~~~~~

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.

[source, clojure]
----
(require '[cats.types :refer :all])

(right :valid-value)
;; => #<Right [:valid-value :right]>

(left "Error message")
;; => #<Either [Error message :left]>
----

NOTE: Either is also (like Maybe) Functor, Applicative Functor and Monad.

Clojure Types
-------------

Besides the own types, some clojure types has implementations for previously explained
category theory abstractions.

NOTE: 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.


.Summary of clojure types and implemented protocols
[options="header"]
|=============================================================
| Name     | Implemented protocols
| vector   | Functor, Applicative, Monad, MonadZero, MonadPlus
| hash-set | Functor, Applicative, Monad, MonadZero, MonadPlus
| list     | Functor, Applicative, Monad, MonadZero, MonadPlus
| atom     | No one (in future)
|=============================================================


Special use cases of monads
--------------------------

State monad
~~~~~~~~~~~

State monad in one of the special use 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.

.Valid function for valid state monad
[source, clojure]
----
(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]))
----

Right, you just saw an example of the low level primitive of state monad but for basic usage
you do not need to build your own functions, just use some helpers that _cats_ gives you.

Let's look at one example before explaining the details:

.Lazy composition of computations
[source, clojure]
----
(m/mlet [state (m/get-state)
         _     (m/put-state (next state))]
  (return (first state)))
;;=> #<State cats.types.State@2eebabb6>
----

At the moment of evaluating the previous expression, anything that we have defined
is executed. Instead of the finished value of the computation, a strange/unknown object is returned of type *State*.

State is a simple wrapper for clojure functions, nothing more.

Now, it 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.

.This is what happens when we execute these three functions over previously generated `State` instance
[source, clojure]
----
(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)
----

NOTE: the pair instance returned by `run-state` functions works like any other seq of clojure, with
the difference that pairs can only have two slots.

This is a very basic example of the state monad, it has a lot of use cases and explaining all them
seems out of the scope of this document.

However, if you have better examples to explain the state monad, documentation for another monad or 
any other contribution is always welcome.

License
-------

[source,text]
----
Copyright (c) 2014, <NAME>
Copyright (c) 2014, <NAME>

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.
----

{'fraction_non_alphanumeric': 0.11827761076189608, 'fraction_numerical': 0.006802101363456925, 'mean_word_length': 3.8925865398900608, 'pattern_counts': {'":': 0, '<': 81, '<?xml version=': 0, '>': 151, 'https://': 4, 'lorem ipsum': 0, 'www.': 4, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3576858', 'n_tokens_mistral': 9942, 'n_tokens_neox': 9330, 'n_words': 4525}