It turns out you can. Simply start SBT in debug mode:

`sbt --debug`

Then rerun your command and watch all the information fly by about what SBT is up to.

]]>I’m really enjoying having moved to the Xiaomi Mi A1 from my iPhone 6. For $A250 that’s an absolute steal. One issue that has plague this phone is that the hotspot does not work as advertised. This has been an issue until recently when I stumbled across a fix that worked for me:

Got to

*Settings*>*Network & Internet*>*Mobile Network*>*Advanced*>*Access Point Names*>*Telstra Internet*Change

**APN**Type from:

`default, supl`

to

`default,supl,dun`

And that should be about it. Happy hotspotting! :)

]]>`git pull`

automatically? And now you can with another simple configuration option:
`git config --global --bool pull.rebase true`

]]>`git push`

and then follow with:

`git push --tags`

Wouldn’t it be nice if you could push the commits and tags in one go? Well now you can by setting one simple config option:

`git config --global push.followTags true`

From the git documentation:

push.followTags If set to true enable –follow-tags option by default. You may override this configuration at time of push by specifying –no-follow-tags.

–follow-tags Push all the refs that would be pushed without this option, and also push annotated tags in refs/tags that are missing from the remote but are pointing at commit-ish that are reachable from the refs being pushed.

References:

]]>`git show-ref --tags`

which yields something like:

```
ee02aa7363f9988af700ab136a219c455cab4b5f refs/tags/v.0.4.0
2d5befba5bc80a69c6308d2a5da965488e6bf9d7 refs/tags/v.0.4.1
0099c11405a3ace8ee14b0881f9677bfc1e30f5e refs/tags/v0.4.1
```

To only list the commit hash for a particular tag use:

`git show-ref tag_name`

for example, to list the commit hash for v0.4.1 use:

`git show-ref v0.4.1`

which gives you a single hash:

`0099c11405a3ace8ee14b0881f9677bfc1e30f5e refs/tags/v0.4.1`

To display the contents of a hash use:

`git show hash`

]]>Start by setting Ghci into multiline mode with:

`:set +m`

You can start a multiline block with `:{`

and end it with `:}`

.

Function definitions must be preceded with `let`

. This has tripped me up many times.

For example, to define a function that pauses for a given delay before printing out “done”:

```
:{
let printAfter :: Int -> IO ()
printAfter delay =
do putStrLn $ (\d -> "waiting for " ++ d ++ " microseconds") $ show delay
threadDelay delay
putStrLn "done"
:}
```

To unset multiline mode use:

`:unset +m`

References: Multi-line commands in GHCi, How to define a function in ghci across multiple lines?

]]>`stack ghci --package [package-name1] --package [package-name2]`

For example to load the transformers package:

`stack ghci --package transformers`

And now we have transformers loaded in GHCi:

```
*Main Lib> import Control.Monad.
Control.Monad.Fail Control.Monad.Trans.Except
Control.Monad.Fix Control.Monad.Trans.Identity
Control.Monad.IO.Class Control.Monad.Trans.List
Control.Monad.Instances Control.Monad.Trans.Maybe
Control.Monad.ST Control.Monad.Trans.RWS
Control.Monad.ST.Lazy Control.Monad.Trans.RWS.Lazy
Control.Monad.ST.Lazy.Safe Control.Monad.Trans.RWS.Strict
Control.Monad.ST.Lazy.Unsafe Control.Monad.Trans.Reader
Control.Monad.ST.Safe Control.Monad.Trans.State
Control.Monad.ST.Strict Control.Monad.Trans.State.Lazy
Control.Monad.ST.Unsafe Control.Monad.Trans.State.Strict
Control.Monad.Signatures Control.Monad.Trans.Writer
Control.Monad.Trans.Class Control.Monad.Trans.Writer.Lazy
Control.Monad.Trans.Cont Control.Monad.Trans.Writer.Strict
Control.Monad.Trans.Error Control.Monad.Zip
*Main Lib> import Control.Monad.Trans.Writer.Lazy
```

]]>`filter :: (a -> Bool) -> [a] -> [a]`

and then at filterM:

`filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]`

A side-by-side comparison:

```
filter :: (a -> Bool) -> [a] -> [a]
filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
```

By comparing the type signatures of **filter** and **filterM** we can see that **filterM** is just **filter** where the conditional expression yields a **Bool** within a context **m** and where the matching results are aggregated in the **m** context.

The implementation of **filterM** in GCH base is as follows:

```
filterM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterM p = foldr (\x -> liftA2 (\flg -> if flg then (x:) else id) (p x)) (pure [])
```

From the above definition it looks like whenever the monadic filter function `(a -> m Bool)`

returns a `m True`

, the value in the supplied list is prepended to an accumulator, and if it doesn’t match the existing accumulator is left unchanged.

Although this sound very simple, I found the usage of **filterM** to be somewhat difficult to understand - at least at first. Let’s start investigating its usage by looking at some example instances for **m**.

Given a list of numbers:

```
numbers :: [Int]
numbers = [1,2,3,4,5]
```

and an **isEven** function:

```
isEven :: Int -> Bool
isEven n = n `mod` 2 == 0
```

we can use **filterM** to filter the list of numbers that are even and return the results in a **Maybe**:

`filterM (Just . isEven) numbers`

which results in:

`Just [2,4]`

That seems pretty easy. Using **filter** on **numbers**:

`filter isEven numbers`

we get:

`[2,4]`

The only difference between the results being that the **filterM** variant has the results in the **Maybe** Monad.

What happens when **filterM** takes a function that can return **Nothing** in some instances?

Given the following function:

```
isDivisibleByThree :: Int -> Bool
isDivisibleByThree n = n `mod` 3 == 0
```

Let’s filter our list of numbers so that they contain even numbers, but if we encounter a number that is divisible by three, we want to bail on the result:

`filterM (\n -> if isDivisibleByThree n then Nothing else Just (isEven n)) numbers`

this results in:

`Nothing`

Now, this might be a little surprising. What happened to all the matches until we encountered a three, such as two? Recall that the **filterM** implementation:

`filterM p = foldr (\x -> liftA2 (\flg -> if flg then (x:) else id) (p x)) (pure [])`

uses **liftA2**:

`liftA2 :: (a -> b -> c) -> f a -> f b -> f c`

to run a binary function over the Applicative instances. With two **Maybe** instances, the result is always **Nothing**, if one of them is **Nothing** as you can’t run the function without both inputs:

```
liftA2 (+) (Just 1) (Just 2) = Just 3
liftA2 (+) (Just 1) Nothing = Nothing
liftA2 (+) Nothing (Just 2) = Nothing
liftA2 (+) Nothing Nothing = Nothing
```

What this demonstrates is that if we ever receive a **Nothing** value while using **filterM** all results up until that point are discarded. This highlights one key difference between **filter** and **filterM**; in addition to filtering on the **Bool** result, **filterM** also combines the results using its Applicative properties.

Let’s run the **filterM** code once again, but this time, we’ll leave out any multiples of three:

`filterM (\n -> if isDivisibleByThree n then Nothing else Just (isEven n)) [1,2,4,5,7,8]`

and this time the answer is:

`Just [2,4,8]`

Let’s try filtering only even numbers using the **IO** Monad:

```
ioFilterM (pure . isEven) numbers
= [2, 4] -- IO [Int]
```

That works as expected. Now let’s introduce a failure in **IO** Monad when a number is divisible by three:

```
filterM (\n -> if isDivisibleByThree n then ioError (userError "boom!") else pure (isEven n)) numbers
= *** Exception: user error (boom!) -- IO [Int]
```

The above discards any results collected once it reaches an **IO** error. This functionality is very similar to how the **Maybe** Monad filtered when it received a **Nothing**. This is quite useful when filtering only valid results and failing on the first failure.

And if we remove any numbers divisible by three:

```
filterM (\n -> if isDivisibleByThree n then ioError (userError "boom!") else pure (isEven n)) [1,2,4,5,7,8]
= [2,4,8] -- IO [Int]
```

we get back the expected results.

With List, things get more interesting. Consider the following:

`filterM (\n -> [True, False]) numbers`

What do you reckon the answer would be? Probably not a powerset:

```
[[1,2,3,4,5],[1,2,3,4],[1,2,3,5],[1,2,3],[1,2,4,5],[1,2,4],[1,2,5],[1,2],
[1,3,4,5],[1,3,4],[1,3,5],[1,3],[1,4,5],[1,4],[1,5],[1],[2,3,4,5],[2,3,4]
,[2,3,5],[2,3],[2,4,5],[2,4],[2,5],[2],[3,4,5],[3,4],[3,5],[3],[4,5],[4],
[5],[]]
```

Remember that **filterM** is defined as:

`filterM p = foldr (\x -> liftA2 (\flg -> if flg then (x:) else id) (p x)) (pure [])`

How does this work with List? If we use **liftA2** with List:

```
liftA2 (+) [1,2,3] [4,5,6]
= [5,6,7,6,7,8,7,8,9]
```

we see that we get a Cartesian product of values (all combinations). List is a non-deterministic Monad and as such it produces results of every possible combination.

Let’s start by expanding out the point-free implementation of **filterM**:

```
filterM p =
foldr (\x acc -> liftA2 (\flg1 accx -> if flg1 then (x:accx) else accx) (p x) acc) (pure [])
```

**accx** is the accumulator value passed to **liftA2**. The values passed will be the Cartesian product of **[True, False]** and the accumulator of list **acc**, which is initially **[[]]**.

There are two main expansions happening in the implementation of **filterM**:

**liftA2**is creating a Cartesian product of the flags**[True, False]**and the accumulator**acc**and combining them with supplied function, which prepends the current value of the list**x**to the accumulator**accx**if the flag is True or returns the existing accumulator**accx**if it is False.- All the combinations returned from
**listA2**are then returned into**foldr**as the new value of the accumulator**acc**.

Because **filterM** is implemented using **foldr** the accumulated values are used from last to first.

Given the following legend:

```
x -- element in the list
acc -- value of accumulator
accx -- value of accumulator at current combination
flg1 -- value of flag at current combination
result -- value of accx after applying flg1
newacc -- value of acc returned to foldr
```

Let’s start from the end of the list at 5 and follow it up to 1.

For the value of 5:

```
x = 5
acc = [[]]
flags = [True, False]
--------------------
accx []
flg1 True
result = 5:[] => [5]
--------------------
accx []
flg1 False
result => []
--------------------
newacc = [[5], []]
```

For the value of 4:

```
x = 4
acc = [[5], []]
flags = [True, False]
--------------------
accx [5]
flg1 True
result = 4:[5] => [4,5]
--------------------
accx []
flg1 True
result = 4:[] => [4]
--------------------
accx [5]
flg1 False
result => [5]
--------------------
accx []
flg1 False
result => []
--------------------
newacc = [[4,5],[4],[5], []]
```

For the value of 3:

```
x = 3
acc = [[4,5],[4],[5], []]
flags = [True, False]
--------------------
accx [4,5]
flg1 True
result = 3:[4,5] => [3,4,5]
--------------------
accx [4]
flg1 True
result = 3:[4] => [3,4]
--------------------
accx [5]
flg1 True
result = 3:[5] => [3,5]
--------------------
accx []
flg1 True
result = 3:[] => [3]
--------------------
accx [4,5]
flg1 False
result => [4,5]
--------------------
accx [4]
flg1 False
result => [4]
--------------------
accx [5]
flg1 False
result => [5]
--------------------
accx []
flg1 False
result => []
--------------------
newacc = [[3,4,5],[3,4],[3,5],[3],[4,5],[4],[5],[]]
```

For the value of 2:

```
x = 2
acc = [[3,4,5],[3,4],[3,5],[3],[4,5],[4],[5],[]]
flags = [True, False]
--------------------
accx [3,4,5]
flg1 True
result = 2:[3,4,5] => [2,3,4,5]
--------------------
accx [3,4]
flg1 True
result = 2:[3,4] => [2,3,4]
--------------------
accx [3,5]
flg1 True
result = 2:[3,5] => [2,3,5]
--------------------
accx [3]
flg1 True
result = 2:[3] => [2,3]
--------------------
accx [4,5]
flg1 True
result = 2:[4,5] => [2,4,5]
--------------------
accx [4]
flg1 True
result = 2:[4] => [2,4]
--------------------
accx [5]
flg1 True
result = 2:[5] => [2,5]
--------------------
accx []
flg1 True
result = 2:[] => [2]
--------------------
accx [3,4,5]
flg1 False
result => [3,4,5]
--------------------
accx [3,4]
flg1 False
result => [3,4]
--------------------
accx [3,5]
flg1 False
result => [3,5]
--------------------
accx [3]
flg1 False
result => [3]
--------------------
accx [4,5]
flg1 False
result => [4,5]
--------------------
accx [4]
flg1 False
result => [4]
--------------------
accx [5]
flg1 False
result => [5]
--------------------
accx []
flg1 False
result => []
--------------------
newacc = [[2,3,4,5],[2,3,4],[2,3,5],[2,3],[2,4,5],[2,4],[2,5],[2],[3,4,5],[3,4],[3,5],[3],[4,5],[4],[5],[]]
```

For the value of 1:

```
x = 1
acc = [[2,3,4,5],[2,3,4],[2,3,5],[2,3],[2,4,5],[2,4],[2,5],[2],[3,4,5],[3,4],[3,5],[3],[4,5],[4],[5],[]]
flags = [True, False]
--------------------
accx [2,3,4,5]
flg1 True
result = 1:[2,3,4,5] => [1,2,3,4,5]
--------------------
accx [2,3,4]
flg1 True
result = 1:[2,3,4] => [1,2,3,4]
--------------------
accx [2,3,5]
flg1 True
result = 1:[2,3,5] => [1,2,3,5]
--------------------
accx [2,3]
flg1 True
result = 1:[2,3] => [1,2,3]
--------------------
accx [2,4,5]
flg1 True
result = 1:[2,4,5] => [1,2,4,5]
--------------------
accx [2,4]
flg1 True
result = 1:[2,4] => [1,2,4]
--------------------
accx [2,5]
flg1 True
result = 1:[2,5] => [1,2,5]
--------------------
accx [2]
flg1 True
result = 1:[2] => [1,2]
--------------------
accx [3,4,5]
flg1 True
result = 1:[3,4,5] => [1,3,4,5]
--------------------
accx [3,4]
flg1 True
result = 1:[3,4] => [1,3,4]
--------------------
accx [3,5]
flg1 True
result = 1:[3,5] => [1,3,5]
--------------------
accx [3]
flg1 True
result = 1:[3] => [1,3]
--------------------
accx [4,5]
flg1 True
result = 1:[4,5] => [1,4,5]
--------------------
accx [4]
flg1 True
result = 1:[4] => [1,4]
--------------------
accx [5]
flg1 True
result = 1:[5] => [1,5]
--------------------
accx []
flg1 True
result = 1:[] => [1]
-------------------- *
accx [2,3,4,5]
flg1 False
result => [2,3,4,5]
--------------------
accx [2,3,4]
flg1 False
result => [2,3,4]
--------------------
accx [2,3,5]
flg1 False
result => [2,3,5]
--------------------
accx [2,3]
flg1 False
result => [2,3]
--------------------
accx [2,4,5]
flg1 False
result => [2,4,5]
--------------------
accx [2,4]
flg1 False
result => [2,4]
--------------------
accx [2,5]
flg1 False
result => [2,5]
--------------------
accx [2]
flg1 False
result => [2]
--------------------
accx [3,4,5]
flg1 False
result => [3,4,5]
--------------------
accx [3,4]
flg1 False
result => [3,4]
--------------------
accx [3,5]
flg1 False
result => [3,5]
--------------------
accx [3]
flg1 False
result => [3]
--------------------
accx [4,5]
flg1 False
result => [4,5]
--------------------
accx [4]
flg1 False
result => [4]
--------------------
accx [5]
flg1 False
result => [5]
--------------------
accx []
flg1 False
result => []
--------------------
newacc = [[1,2,3,4,5],[1,2,3,4],[1,2,3,5],[1,2,3],[1,2,4,5],[1,2,4],[1,2,5],[1,2],[1,3,4,5],[1,3,4],[1,3,5],[1,3],[1,4,5],[1,4],[1,5],[1],[2,3,4,5],[2,3,4],[2,3,5],[2,3],[2,4,5],[2,4],[2,5],[2],[3,4,5],[3,4],[3,5],[3],[4,5],[4],[5],[]]
```

That was a bit harder than necessary!

Using **filterM** with **Either** is pretty much the same as a **Maybe**:

```
let e1 = filterM (\x -> if x == 11 then Left "You gave me eleven" else Right (isEven x))
-- e1 :: :: Integral a => [a] -> Either [Char] [a]
e1 [1 .. 10]
= Right [2,4,6,8,10] -- only even numbers
e1 [1 .. 11]
= Left "You gave me eleven" -- drops all results on a Left
```

Now let’s use a Monad that has two type holes which are both used together. The State Monad allows us to return a value and thread through some state we are interested in at the same time. Let’s use our **isEven** method to filter in all the even inputs and use a list to record all the values inspected along the way:

```
let x1 = filterM (\x -> state (\s -> (isEven(x), s ++ [x]))) [1 .. 10]
-- x1 :: (Integral a, Monad m) => StateT [a] m [a]
evalState x1 [] -- get value
= [2,4,6,8,10] -- only even numbers
execState x1 [] -- get state
= [1,2,3,4,5,6,7,8,9,10] -- the state - all inspected values
```

The interesting thing to note is that given **x1**’s type:

`x1 :: (Integral a, Monad m) => StateT [a] m [a]`

The **m** in **filterM**:

`filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]`

is:

`StateT [a] m`

which is why we can return a Bool in the value position and have it filter the inputs for us.

Hopefully that was somewhat easier to understand. You can find alternate explanations to this problem here and here.

]]>- The validity of an idea or action is determined not by whether it is widely believed or widely reviled but by whether it obeys the rules of logic.
- A statement is true if it cannot be disproved.
- The Socratic Method:
- Locate a statement confidently described as common sense.
- Imagine for a moment that, despite the confidence of the person proposing it, the statement is false.
- Search for situations or contexts where the statement would not be true.
- If an exception is found, the definition must be false or at least imprecise.
- The initial statement must be nuanced to take the exception into account.

- It is by finding out what something is not that one comes closest to understanding what it is.
- We acquire a misplaced respect for others when we concentrate solely on their conclusions – which is why Socrates urged us to dwell on the logic they used to reach them.
- The value of criticism will depend on the thought processes of critics, not on their number or rank.
- We are making vases, we should listen to the advice of those who know about turning glaze into Fe3O4 at 800 ° C; when we are making a ship, it is the verdict of those who construct triremes that should worry us.
- We should not look to Socrates for advice on escaping a death sentence; we should look to him as an extreme example of how to maintain confidence in an intelligent position which has met with illogical opposition.
- Just as medicine confers no benefit if it does not drive away physical illness, so philosophy is useless if it does not drive away the suffering of the mind.
- Before you eat or drink anything, consider carefully who you eat or drink with rather than what you eat or drink: for feeding without a friend is the life of a lion or a wolf.
- Nothing satisfies the man who is not satisfied with a little.
- Could one possess the desired object but not be happy? Could one be happy but not have the desired object?
- We aren’t overwhelmed by anger whenever we are denied an object we desire, only when we believe ourselves entitled to obtain it.
- No, he who has said ‘a day’ has granted too long a postponement to swift misfortune; an hour, an instant of time, suffices for the overthrow of empires.
- We need metaphors to derive a sense of what cannot be seen or touched, or else we will forget.
- The wise man can lose nothing. He has everything invested in himself. The wise man is self-sufficient. If he loses a hand through disease or war, or if some accident puts out one or both of his eyes, he will be satisfied with what is left.
- To calm us down in noisy streets, we should trust that those making a noise know nothing of us.
- Wisdom lies in correctly discerning where we are free to mould reality according to our wishes and where we must accept the unalterable with tranquillity.
- We are like dogs who have been tied to an unpredictable cart.
- We may be powerless to alter certain events, but we remain free to choose our attitude towards them, and it is in our spontaneous acceptance of necessity that we find our distinctive freedom
- That which you cannot reform, it is best to endure.

Upon the highest throne in the world, we are seated, still, upon our arses

Montaigne

- Every man may bear the whole form of the human condition, but it seems that no single country can tolerate the complexity of this condition.
- Friendship is a minor conspiracy against what other people think of as reasonable.

I have seen in my time hundreds of craftsmen and ploughmen wiser and happier than university rectors.

Montaigne

- What reads easily is rarely so written.
- The prudent man strives for freedom from pain, not pleasure.
- What if pleasure and displeasure were so tied together that whoever wanted to have as much as possible of one must also have as much as possible of the other?
- In the mountains of truth you will never climb in vain: either you will get up higher today or you will exercise your strength so as to be able to get up higher tomorrow.

How can anyone become a thinker if he does not spend at least a third of the day without passions, people and books?

Nietzsche

- Not everything which makes us feel better is good for us. Not everything which hurts may be bad.

I’d like to analyse how the Reader instances are derived for each of **Functor**, **Applicative** and **Monad** and test it against some examples to gain some intuition. Also note that (-> r) and (r ->) can be used interchangeably. Thanks to Brian McKenna for that useful titbit.

A functor typeclass is defined as:

```
class Functor f where
fmap, (<$>) :: (a -> b) -> f a -> f b
```

**fmap** or **<$>** basically runs a function (**a -> b**), on a value within some context **f a** and returns the context with the function applied to its value as an **f b**.

```
(a -> b) -- f', a function that requires an 'a' to create a 'b'
f a -- Functor with an 'a'
f (f'(a)) -- apply f' to the 'a'
f b -- the final result of a 'b'
```

Let’s take a look at the **Functor** instance for Maybe:

```
instance Functor Maybe where
-- fmap :: (a -> b) -> f a -> f b
fmap f (Just a) = Just (f a)
fmap _ Nothing = Nothing
```

With **Maybe**, the function **f**, is applied to a value within a **Just** or not applied if the value is a **Nothing**.

When we hear that (-> r) is also a Functor it can boggle our minds a little. How do we define an instance for that?

```
instance Functor (-> r) where
fmap f = -- what goes here?
```

We need a function that takes some resource **r** and returns some other value. Let’s have a crack at deriving the implementation for Functor:

```
instance Functor (r -> ) where
-- fmap :: (a -> b) -> f a -> f b
fmap fab f a = f b -- refer to (a -> b) as fab
fmap fab (\r -> a) = (\r -> b) -- given that the Functor is (r ->), replace 'f' with (r ->)
fmap fab fra = (\r -> b) -- refer to (r -> a) as fra so we can use it
fmap fab fra = (\r -> ??? (fra r)) -- we have an 'r' and we have something that needs an 'r' and returns an 'a'.
fmap fab fra = (\r -> fab (fra r)) -- We have an 'a' and something that needs an 'a' to return a 'b'
fmap fab fra = fab . fra -- we can simplify this to composing fab and fra
```

We are applying the function **fab** to the result of **fra**. It looks like **fmap** takes two functions are composes them.

Compose (.) is defined as:

`(.) :: (b -> c) -> (a -> b) -> a -> c`

or in our case:

`(.) :: (a -> b) -> (r -> a) -> r -> b`

And we can implement the Functor for (r ->) with compose alone:

```
instance Functor (r -> ) where
fmap = (.)
```

This gives us the intuition that fmap over functions is just composition.

Let’s use it on an example:

`fmap (*3) (+100) 1`

What is the result of the above?

Let’s use function composition to get the answer:

```
fmap (*3) (+100) 1
= (\r -> (r + 100) * 3) -- expanding Functor
= ((1 + 100) * 3) -- substituting 1 for 'r'
= 303
```

The Applicative typeclass is defined as:

```
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
```

The **pure** function lifts some value **a** into the **Applicative**, **f**. Also note that **f** is also a **Functor**. The **<$>** function sequences a function from (**a -> b**) within an **Applicative** context, with the value of **a** supplied in another **Applicative** context to produce the result **b** in a third **Applicative** context.

Note the similarities between **<$>** and <*>:

```
fmap, (<$>) :: (a -> b) -> f a -> f b
(<*>) :: f (a -> b) -> f a -> f b
```

The only difference is that with <*> the function is within a context **f**.

```
f (a -> b) -- f', a function within a context 'f', requires an 'a' to create a 'b'
f a -- Applicative Functor with an 'a'
f (f'(a)) -- apply f' to the 'a' within 'f'
f b -- the final result of a 'b'
```

Let’s take a look at the **Applicative** instance for **Maybe**:

```
instance Applicative Maybe where
-- pure :: a -> f a
pure = Just
-- (<*>) :: f (a -> b) -> f a -> f b
(<*>) (Just f) other = fmap f other
(<*>) Nothing _ = Nothing
```

For **Maybe**, **pure** simply creates an instance of **Just** with the supplied value. With <*> the function **f** is within a **Maybe** context. If the context is a **Just**, the function is applied to the other **Maybe** context using **fmap** from the **Functor** typeclass. If the context is a **Nothing**, no function application takes place and a **Nothing** is returned.

How do we define an **Applicative** instance for (r ->) ?

```
instance Applicative (r -> ) where
-- pure :: a -> f a
pure a = \r -> a
-- (<*>) :: f (a -> b) -> f a -> f b
(<*>) f g = \r -> f r (g r) -- f is (\r -> (a -> b)), g is (\r -> a)
```

Apply the input **r** to **g** to return an **a** and also apply **r** to **f**, to return the function from (**a -> b**). Then apply the function (**a -> b**) to **a** to return a **b**.

Let’s use it on an example:

```
(+) <$> (+3) <*> (*100) 5
= (+) <$> (\r -> r + 3) <*> (\r -> r * 100) 5 -- expanding Applicative
= (+) <$> (5 + 3) (5 * 100) -- substituting 5 for 'r'
= 8 + 500 -- combining with (+)
= 508
```

You may also notice that this gives you the same answer as **liftA2**:

```
liftA2 :: (a -> b -> c) -> f a -> f b -> f c
liftA2 (+) (+3) (*100) 5
= 508
```

The intuition here is that, we can supply the input to each **Applicative** context, and then combine them with a function either through **<$>** or **liftA2**.

And here’s one more example which may seem a little hairy:

```
(\x y z -> [x,y,z]) <$> (+3) <*> (*2) <*> (/2) $ 5
= (\x y z -> [x,y,z]) <$> (\r -> r +3) <*> (\r -> *2) <*> (\r -> /2) $ 5 -- expand Applicative
= (\x y z -> [x,y,z]) <$> (5 + 3) <*> (5 * 2) <*> (5 / 2) -- replace 'r' with 5
= (\x y z -> [x,y,z]) <$> (8.0) <*> (10.0) <*> (2.5)
= [8.0, 10.0, 2.5] -- combine with (\x y z -> [x,y,z])
```

The same result can be achieved with **liftA3**:

```
liftA3 (\x y z -> [x,y,z]) (+3) (*2) (/2) $ 5
= [8.0,10.0,2.5]
```

The **Monad** typeclass is defined as:

```
class Applicative m => Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
```

The **return** function lifts a value **a** into the **Monad** **m**. Bind or (**>>=**) sequentially composes two actions, passing any value produced by the first as an argument to the second.

Let’s take a look at the **Monad** instance for **Maybe** :

```
instance Monad Maybe where
-- (>>=) :: m a -> (a -> m b) -> m b
(Just a) >>= k = k a
Nothing >>= _ = Nothing
```

If the first **Maybe** context is a **Just**, then apply the function **k** to produce a new **Maybe** context. If the first **Maybe** context is a **Nothing**, then return **Nothing**.

How do we define an **Monad** instance for (r ->) ?

```
instance Monad (r ->) where
-- return :: a -> m a
return = pure
-- (>>=) :: m a -> (a -> m b) -> m b
f >>= g = \r -> g (f r) r -- f is (\r -> a), g is (\a -> \r -> b)
```

The **return** function is derived from **pure**, since all **Monads** are also **Applicatives**. The bind function (**>>=**) first applies the input **r** to **f** to give an **a**. It then applies the **a** to **g** to return a function from (**r -> b**). The input **r** is then applied to this function to return the final **b**.

The intuition here is that we supply the input resource **r** to **f** and use that result as the first input to **g** followed by **r** as the second input.

Let’s use it in an example:

```
(+3) >>= (*) $ 5
= (\r -> r + 3) >>= (\a -> \r -> a * r) 5 -- expanding the Monad for 'r'
= (5 + 3) >>= (\a -> a * 5) -- replace 'r' with 5
= (8) >>= (\a -> a * 5)
= (8 * 5) -- replace 'a' with 8
= 40
```

or simply:

```
(+3) >>= (*) $ 5
= ((5+3) * 5)
= (8 * 5)
= 40
```

We can also use the do syntax to solve the above:

```
let z1 = do
x <- (+3)
(x *)
z1 5
= 40
```

The **join** function flattens nested **Monads** and is defined as:

```
join :: (Monad m) => m (m a) -> m a
join x = x >>= id
```

Given the following:

`join (+) 10`

armed with the what we know about **Monads**, what is its result?

```
join (+) 10
-- m (m a) -> m a
= (\r -> (\r -> r + r)) 10 -- expanding the Monad for 'r'
= (10 + 10) -- replacing 'r' with 10
= 20
```

We can also use the do syntax to solve the above:

```
let z2 = do
x <- (+)
x
z2 10
= 20
```