Rename Clojure with clojure in asciidoctor codeblock attribute.

= Cats Documentation
Andrey Antukh & Alejandro Gómez
0.4.0-SNAPSHOT
:toc: left
:numbered:
:source-highlighter: pygments
:pygments-style: friendly

image:logo.png[cats logo]

== Introduction

Category Theory abstractions for Clojure.

=== Why another library?

Because the cats library:

- targets both of the most-used Clojure implementations:  *Clojure (jvm)* and *ClojureScript(js)*
- aims to have the simplest implementation of the 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)

== Project Maturity

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

== Install

This section covers installing _cats_.

=== 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.4.0-SNAPSHOT"]
----

=== 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.4.0-SNAPSHOT</version>
</dependency>
----

=== Get the Code

_cats_ is open source and can be found on link:https://github.com/funcool/cats[github].

You can clone the public repository with this command:

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

== User Guide

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

=== Functor

Let's start with the functor. The Functor represents some sort of "computational context", and the
abstraction consists of one unique function: *fmap*.

.Signature of *fmap* function
[source, clojure]
----
(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.

.One good example of a functor is the *Maybe* type:
[source, clojure]
----
(require '[cats.monad.maybe :as maybe])

;; `just` function is one of two constructors of Maybe

(maybe/just 2)
;; => #<Just [2]>
----

Let's see one example using *fmap* over *just* instance:

.Example using fmap over *just* instance.
[source, clojure]
----
(require '[cats.core :as m]
         '[cats.monad.maybe :refer [just]])

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

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

.Example using *from-maybe* to extract values wrapped by *just*.
[source, clojure]
----
(require '[cats.monad.maybe :refer [just from-maybe]])

(from-maybe (just 1))
;; => 1
(from-maybe (nothing))
;; => nil
(from-maybe (nothing) 42)
;; => 42
----

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:

.Example using fmap over *nothing*.
[source, clojure]
----
(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:

.Example using fmav over *vector*.
[source, clojure]
----
(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:

[source, clojure]
----
(type (map inc [1 2 3]))
;; => clojure.lang.LazySeq (cljs.core/LazySeq in ClojureScript)
----

But why can we pass vectors to fmap? Because some Clojure container types like vectors,
lists and sets also implement the functor abstraction.

=== Applicative

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

.Signature of *fapply* function
[source, clojure]
----
(fapply [af av])
----

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

[source, clojure]
----
(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:

[source, clojure]
----
(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:

[source, clojure]
----
(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:

[source, clojure]
----
(require '[cats.monad.maybe])
(require '[cats.monad.either])

(pure maybe/maybe-monad 5)
;; => #<Just [5]>

(pure either/either-monad :bar)
;; => #<Either [:bar :right]>
----

If you do not understand the purpose of the *pure* function, the next section
should clarify its purpose.

=== 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 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 function signature.
[source,clojure]
----
(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.

.Example usage of the bind higher-order function.
[source,clojure]
----
(bind (just 1)
      (fn [v] (just (inc v))))
----

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:

.Usage of return function in bind context.
[source,clojure]
----
(bind (just 1)
      (fn [v]
        (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:

.Composability example of bind function.
[source, clojure]
----
(bind (just 1)
      (fn [a]
        (bind (just (inc a))
              (fn [b]
                (return (* b 2))))))
----

This can quickly lead to callback hell. To solve this, _cats_ comes with a powerful
macro: *mlet*

.Previous example but using *mlet* macro.
[source, clojure]
----
(mlet [a (just 1)
       b (just (inc a))]
  (return (* b 2)))
----

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

[source, clojure]
----
(mlet [a (just 1)
       b (just (inc a))
       :let [z (+ a b)]]
  (return (* z 2)))
----

=== Monad Transformers

==== Motivation

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:

[source, clojure]
----
(ns functor.example
  (:require [cats.core :refer [fmap]]
            [cats.monad.maybe :refer [just]])
  (:use [cats.builtin]))

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

==== Using monad transformers

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:

[source, clojure]
----
(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.

Let's see it in action:

[source, clojure]
----
(defn any-char [s]
  "A function that takes an input string as an state and
  consumes one character yielding it as a the value. The
  new state is the input string with the character consumed.

  It fails when there isn't a character to consume."
  (if (Clojure.string/blank? s)
    (maybe/nothing)
    (maybe/just (data/pair (first s)
                              (.substring s 1)))))

(m/with-monad maybe-state
  (state/run-state any-char "Foo"))
;;=> #<Just [#<Pair [F oo]>]>

(def any-two-chars
  (m/with-monad maybe-state
    (m/mlet
      [a any-char
       b any-char]
      (m/return (str a b)))))

(m/with-monad maybe-state
  (state/run-state any-two-chars "Foo"))
;;=> #<Just [#<Pair [Fo o]>]>

(m/with-monad maybe-state
  (state/run-state any-two-chars "F"))
;;=> #<Nothing >

; We could have written `any-two-chars` more succinctly by using `cats.core/with-monad`,
; which is intended as syntactic sugar for transformer usage.
(def any-two-chars
  (m/with-monad maybe-state
    (m/mlet [a any-char
             b any-char]
      (m/return (str a b)))))

; We also define a function for applying parser to a given input
(defn parse [parser input]
  (m/with-monad maybe-state
    (let [parse-result (state/run-state parser input)]
      (maybe/from-maybe parse-result))))
----

== Monad types

In our examples we have seen two types that implement
the monad abstraction: Maybe and Either. But these are only two of the types
that implements the Monad abstraction. In this section, we will explain the different
monad types supported by _cats_ library.

=== Maybe

This is one of the two most used monad types (also named Optional in other 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.

.Usage example of *Maybe* constructors.
[source, clojure]
----
(require '[cats.monad.maybe :refer :all])
(just 1)
;; => #<Just [1]>
(nothing)
;; => #<Nothing >
----

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

.Usage example of *Either* constructors.
[source, clojure]
----
(require '[cats.monad.either :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.

=== Try

Also called Exception.

The `Try` type represents a computation that may either result in an exception
or return a successfully computed value. It's similar to, but semantically
different from, the `Either` type.

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.

.Usage example of *try-on* macro.
[source, clojure]
----
(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.

.Usage example of `try-or-else` macro.
[source, clojure]
----
(exc/try-or-else (+ 1 nil) 2)
;; => #<Success [2]>
----

.Usage example of `try-or-recover` macro.
[source, clojure]
----
(exc/try-or-recover (+ 1 nil)
                    (fn [e]
                      (cond
                        (instance? NullPointerException e) 0
                        :else 100)))
;; => #<Success [0]>
----

=== State

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.

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

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:

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

At the moment of evaluation in the previous expression, anything 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*.

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

.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` function works like any other seq in 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.

=== Channel

In asynchronous environments with clojure and clojurescript we tend to use core.async, because it
is a very powerfull abstraction.

It would be awesome to be able to work with channel as a monadic type, and combine it with error
monads for short-circuiting async computations that may fail.

Let's start using channel as a functor:
[source, clojure]
----
(require '[cljs.core.async :refer [chan put! <!!]])
(require '[cats.monad.channel :as channel])

;; Declare arbitrary channel with initial value
(def mychan (channel/with-value 2))

;; Use channel as a functor
(<!! (m/fmap inc mychan))
;; => 3
----

The channel type also fulfills the monad abstraction, let see it in action:

[source, clojure]
----
(def result (m/mlet [a (channel/with-value 2)
                     b (channel/with-value 3)]
              (m/return (+ a b))))
(<!! result)
;; => 5
----

But the best of all is coming: combine the channel monad with error monads. It allows to build very concise
and simple asynchronous APIs. Let see how you can use it your application:

[source, clojure]
----
(require '[cats.monad.either :as either])

;; Declare a monad transformer
(def either-chan-m
  (either/either-transformer channel/channel-monad))

;; A success example
(<!! (m/with-monad either-chan-m
       (m/mlet [a (channel/with-value (either/right 2))
                b (channel/with-value (either/right 3))]
         (m/return (+ a b)))))
;; => #<Right [5]>
----

As you can see, the code looks very similar to the previos example, with the exception that
the value in a channel is not a simple plain value, is an either instance.

Let's see what happens if some computation fails in the mlet composition:

[source, clojure]
----
(<!! (m/with-monad either-chan-m
       (m/mlet [a (channel/with-value (either/left "Some error"))
                b (channel/with-value (either/right 3))]
         (m/return (+ a b)))))
;; => #<Left [Some error]>
----

The result is the expected short-circuiting left, without unexpected nullpointer exceptions
or similar issues.

With this compositional power, you can model your asynchronous API with a complete
error handling using any error monad (in this case Either).

=== Reader

TODO

=== Writer

TODO

=== Continuation

TODO

=== Vector

TODO

== FAQ

=== What are the difference with other existing libraries?

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.

=== What Clojure types implements some of the Category Theory abstractions?

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

== How to Contribute?

=== Philosophy

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.

=== Procedure

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

=== License

[source,text]
----
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.
----

= Cats Documentation
Andrey Antukh & Alejandro Gómez
0.4.0-SNAPSHOT
:toc: left
:numbered:
:source-highlighter: pygments
:pygments-style: friendly

image:logo.png[cats logo]

== Introduction

Category Theory abstractions for Clojure.

=== Why another library?

Because the cats library:

- targets both of the most-used Clojure implementations:  *Clojure (jvm)* and *ClojureScript(js)*
- aims to have the simplest implementation of the 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)

== Project Maturity

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

== Install

This section covers installing _cats_.

=== 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.4.0-SNAPSHOT"]
----

=== 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.4.0-SNAPSHOT</version>
</dependency>
----

=== Get the Code

_cats_ is open source and can be found on link:https://github.com/funcool/cats[github].

You can clone the public repository with this command:

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

== User Guide

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

=== Functor

Let's start with the functor. The Functor represents some sort of "computational context", and the
abstraction consists of one unique function: *fmap*.

.Signature of *fmap* function
[source, Clojure]
----
(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.

.One good example of a functor is the *Maybe* type:
[source, Clojure]
----
(require '[cats.monad.maybe :as maybe])

;; `just` function is one of two constructors of Maybe

(maybe/just 2)
;; => #<Just [2]>
----

Let's see one example using *fmap* over *just* instance:

.Example using fmap over *just*.
[source, Clojure]
----
(require '[cats.core :as m]
         '[cats.monad.maybe :refer [just]])

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

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

.Example using *from-maybe* to extract values wrapped by *just*.
[source, Clojure]
----
(require '[cats.monad.maybe :refer [just from-maybe]])

(from-maybe (just 1))
;; => 1
(from-maybe (nothing))
;; => nil
(from-maybe (nothing) 42)
;; => 42
----

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:

.Example using fmap over *nothing*.
[source, Clojure]
----
(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:

.Example using fmav over *vector*.
[source, Clojure]
----
(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:

[source, Clojure]
----
(type (map inc [1 2 3]))
;; => clojure.lang.LazySeq (cljs.core/LazySeq in ClojureScript)
----

But why can we pass vectors to fmap? Because some Clojure container types like vectors,
lists and sets also implement the functor abstraction.

=== Applicative

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

.Signature of *fapply* function
[source, Clojure]
----
(fapply [af av])
----

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

[source, Clojure]
----
(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:

[source, Clojure]
----
(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:

[source, Clojure]
----
(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:

[source, Clojure]
----
(require '[cats.monad.maybe])
(require '[cats.monad.either])

(pure maybe/maybe-monad 5)
;; => #<Just [5]>

(pure either/either-monad :bar)
;; => #<Either [:bar :right]>
----

If you do not understand the purpose of the *pure* function, the next section
should clarify its purpose.

=== 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 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 function signature.
[source,Clojure]
----
(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.

.Example usage of the bind higher-order function.
[source,Clojure]
----
(bind (just 1)
      (fn [v] (just (inc v))))
----

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:

.Usage of return function in bind context.
[source,Clojure]
----
(bind (just 1)
      (fn [v]
        (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:

.Composability example of bind function.
[source, Clojure]
----
(bind (just 1)
      (fn [a]
        (bind (just (inc a))
              (fn [b]
                (return (* b 2))))))
----

This can quickly lead to callback hell. To solve this, _cats_ comes with a powerful
macro: *mlet*

.Previous example but using *mlet* macro.
[source, Clojure]
----
(mlet [a (just 1)
       b (just (inc a))]
  (return (* b 2)))
----

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

[source, Clojure]
----
(mlet [a (just 1)
       b (just (inc a))
       :let [z (+ a b)]]
  (return (* z 2)))
----

=== Monad Transformers

==== Motivation

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:

[source, Clojure]
----
(ns functor.example
  (:require [cats.core :refer [fmap]]
            [cats.monad.maybe :refer [just]])
  (:use [cats.builtin]))

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

==== Using monad transformers

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:

[source, Clojure]
----
(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.

Let's see it in action:

[source, Clojure]
----
(defn any-char [s]
  "A function that takes an input string as an state and
  consumes one character yielding it as a the value. The
  new state is the input string with the character consumed.

  It fails when there isn't a character to consume."
  (if (Clojure.string/blank? s)
    (maybe/nothing)
    (maybe/just (data/pair (first s)
                              (.substring s 1)))))

(m/with-monad maybe-state
  (state/run-state any-char "Foo"))
;;=> #<Just [#<Pair [F oo]>]>

(def any-two-chars
  (m/with-monad maybe-state
    (m/mlet
      [a any-char
       b any-char]
      (m/return (str a b)))))

(m/with-monad maybe-state
  (state/run-state any-two-chars "Foo"))
;;=> #<Just [#<Pair [Fo o]>]>

(m/with-monad maybe-state
  (state/run-state any-two-chars "F"))
;;=> #<Nothing >

; We could have written `any-two-chars` more succinctly by using `cats.core/with-monad`,
; which is intended as syntactic sugar for transformer usage.
(def any-two-chars
  (m/with-monad maybe-state
    (m/mlet [a any-char
             b any-char]
      (m/return (str a b)))))

; We also define a function for applying parser to a given input
(defn parse [parser input]
  (m/with-monad maybe-state
    (let [parse-result (state/run-state parser input)]
      (maybe/from-maybe parse-result))))
----

== Monad types

In our examples we have seen two types that implement
the monad abstraction: Maybe and Either. But these are only two of the types
that implements the Monad abstraction. In this section, we will explain the different
monad types supported by _cats_ library.

=== Maybe

This is one of the two most used monad types (also named Optional in other 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.

.Usage example of *Maybe* constructors.
[source, Clojure]
----
(require '[cats.monad.maybe :refer :all])
(just 1)
;; => #<Just [1]>
(nothing)
;; => #<Nothing >
----

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

.Usage example of *Either* constructors.
[source, Clojure]
----
(require '[cats.monad.either :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.

=== Try

Also called Exception.

The `Try` type represents a computation that may either result in an exception
or return a successfully computed value. It's similar to, but semantically
different from, the `Either` type.

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.

.Usage example of *try-on* macro.
[source, Clojure]
----
(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.

.Usage example of `try-or-else` macro.
[source, Clojure]
----
(exc/try-or-else (+ 1 nil) 2)
;; => #<Success [2]>
----

.Usage example of `try-or-recover` macro.
[source, Clojure]
----
(exc/try-or-recover (+ 1 nil)
                    (fn [e]
                      (cond
                        (instance? NullPointerException e) 0
                        :else 100)))
;; => #<Success [0]>
----

=== State

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.

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

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:

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

At the moment of evaluation in the previous expression, anything 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*.

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

.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` function works like any other seq in 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.

=== Channel

In asynchronous environments with clojure and clojurescript we tend to use core.async, because it
is a very powerfull abstraction.

It would be awesome to be able to work with channel as a monadic type, and combine it with error
monads for short-circuiting async computations that may fail.

Let's start using channel as a functor:
[source, clojure]
----
(require '[cljs.core.async :refer [chan put! <!!]])
(require '[cats.monad.channel :as channel])

;; Declare arbitrary channel with initial value
(def mychan (channel/with-value 2))

;; Use channel as a functor
(<!! (m/fmap inc mychan))
;; => 3
----

The channel type also fulfills the monad abstraction, let see it in action:

[source, clojure]
----
(def result (m/mlet [a (channel/with-value 2)
                     b (channel/with-value 3)]
              (m/return (+ a b))))
(<!! result)
;; => 5
----

But the best of all is coming: combine the channel monad with error monads. It allows to build very concise
and simple asynchronous APIs. Let see how you can use it your application:

[source, clojure]
----
(require '[cats.monad.either :as either])

;; Declare a monad transformer
(def either-chan-m
  (either/either-transformer channel/channel-monad))

;; A success example
(<!! (m/with-monad either-chan-m
       (m/mlet [a (channel/with-value (either/right 2))
                b (channel/with-value (either/right 3))]
         (m/return (+ a b)))))
;; => #<Right [5]>
----

As you can see, the code looks very similar to the previos example, with the exception that
the value in a channel is not a simple plain value, is an either instance.

Let's see what happens if some computation fails in the mlet composition:

[source, clojure]
----
(<!! (m/with-monad either-chan-m
       (m/mlet [a (channel/with-value (either/left "Some error"))
                b (channel/with-value (either/right 3))]
         (m/return (+ a b)))))
;; => #<Left [Some error]>
----

The result is the expected short-circuiting left, without unexpected nullpointer exceptions
or similar issues.

With this compositional power, you can model your asynchronous API with a complete
error handling using any error monad (in this case Either).

=== Reader

TODO

=== Writer

TODO

=== Continuation

TODO

=== Vector

TODO

== FAQ

=== What are the difference with other existing libraries?

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.

=== What Clojure types implements some of the Category Theory abstractions?

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

== How to Contribute?

=== Philosophy

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.

=== Procedure

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

=== License

[source,text]
----
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.
----


Update 2015-02-25-Tervetuloa.adoc

Update 2015-02-25-Tervetuloa.adoc

= Tervetuloa !

:hp-tags: Présentation, Introduction, Finlande, Laurea
:hp-image: https://TeksInHelsinki.github.com/images/helsinki-background.jpg

Nous sommes cinq étudiants d'Epitech - école d'expertise informatique française - et nous passerons notre quatrième année (2015/2016) en Finlande ! Plus précisément, nous avons été accepté à l'université de Laurea, à Espoo, près d'Helsinki. +
C'est pour cette raison que nous avons aujourd'hui décidé de faire un blog, dans un premier temps pour partager nos ressources sur la Finlande, sa culture etc., et plus tard pour raconter notre expérience, que ce soit au niveau des cours que nous suivrons ou de la vie sur place.

Les étudiants ayant été reçus à Laurea et tenant ce blog sont : Jérôme CAMPEAUX (Paris), Martin DONADIEU (Montpellier), link:https://github.com/ArmandDu[Armand DUPUIS] (Strasbourg), Benoît DURAND (Paris) et Coline MARION (Paris).

Bienvenue sur notre blog, nous espérons que vous l'apprécierez et qu'il vous sera utile !

= Tervetuloa !

:hp-tags: Présentation, Introduction, Finlande, Laurea
:hp-image: https://TeksInHelsinki.github.com/images/helsinki-background.jpg
:published_at: 2015-02-25

Nous sommes cinq étudiants d'Epitech - école d'expertise informatique française - et nous passerons notre quatrième année (2015/2016) en Finlande ! Plus précisément, nous avons été accepté à l'université de Laurea, à Espoo, près d'Helsinki. +
C'est pour cette raison que nous avons aujourd'hui décidé de faire un blog, dans un premier temps pour partager nos ressources sur la Finlande, sa culture etc., et plus tard pour raconter notre expérience, que ce soit au niveau des cours que nous suivrons ou de la vie sur place.

Les étudiants ayant été reçus à Laurea et tenant ce blog sont : Jérôme CAMPEAUX (Paris), Martin DONADIEU (Montpellier), link:https://github.com/ArmandDu[Armand DUPUIS] (Strasbourg), Benoît DURAND (Paris) et Coline MARION (Paris).

Bienvenue sur notre blog, nous espérons que vous l'apprécierez et qu'il vous sera utile !