Fl4m3Ph03n1x

Fl4m3Ph03n1x

How to chain Result Monads using Monadex?

Background

In my quest to learn more about Monadex I am trying to chain a Result Monad several times in a function.
I understand this is achieved via the fmap, a function which takes a function and a Monad and returns a Monad.

defmodule TestMonadex do
  use Monad.Operators

  import Monad.Result

  # This wont work
  def p2(x) do
    x
    |> success()
    <|> (&plus_1/1)
    <|> (&plus_1/1) 
  end

  defp plus_1(n), do: n + 1
end

Problem

The problem here is that according to the documentation, Result Monad does not implement the fmap:

Question

  • Why can’t my example work?
  • How can I chain the Result Monad?

Marked As Solved

dorgan

dorgan

I wrote an explanation of fmap vs bind but then I realized the problem here is that for some reason the function needs to be in the left hand side of the <|> operator.
Functor.fmap takes a value and then a function: MonadEx/lib/functor.ex at master · rob-brown/MonadEx · GitHub
But <|> reverses the order: MonadEx/lib/monad/operators.ex at master · rob-brown/MonadEx · GitHub

So I think your function should do (&plus_1/1) <|> (&plus_1/1) <|> success(x) instead?


The explanation I started to write in case you want it:

The way to chain monads is by using bind, not fmap.
bind’s signature is bind :: m a -> (a -> m b) -> m b where m is the monad(the context). What this tells you is that you start with a monad m with a type a, you give it a function that works with an a and returns a monad m with a type mb, and bind will give you back that last m b.
To illustrate it a bit better, if I have a value x and I apply it a function a -> m b, like something that returns a Maybe b, and I want to apply that a -> m b again, I would end up with Maybe (Maybe b). bind lets you do composition while avoiding that nesting.

fmap on the other hand is a way to lift a function to work in a context. It’s signature is fmap :: (a -> b) -> (f a -> f b), which means that you start with a function from a to b and get back a lifted function that works in a context f(the functor). This is essentially what you do with Enum.map, you give it an list and it takes care of using the function in every element of the list and returns back a list. If you have a Maybe, fmap would lift the function to be applied to the element inside the Just but skip the Nothing.

Monads are indeed Functors in the sense that you can define fmap in terms of bind and return(the functions in that monadex module):

fmap f m = m >>= (return . f)

The other altenative is defining bind in terms of join and fmap.

The definition of fmap doesn’t involve monads though, it’s just a way to lift a function to work in a particular context.

An fmap definition for a result tuple would look like this:

def fmap({:ok, x}, f) do
  {:ok, f.(x)}
end
def fmap({:error, x}, _) do
  {:error, x}
end

While a definition of bind would looke like this:

def bind({:ok, x}, f) do
  f.(x)
end
def bind({:error, x}, _) do
  {:error, x}
end

Notice that in fmap we extract the x from the tuple so it can work with f (the a -> f a lifting), and then it wraps the result of applying f to x in an ok tuple again (the b -> f b lifting), essentially making the function f work in the context of a result tuple. But in bind the f already returns a result tuple, so we don’t need to wrap it, otherwise it would result in nested result tuples.

More “correct” definitions would be curried functions, though, so fmap would be:

def fmap(f), do: fn
  {:ok, x} -> {:ok, f.(x)}
  {:error, x} -> {:error, x}
end

So fmap here returns a version of f that can work with result tuples. I think this is a better illustration of what lifting a function means.

Also Liked

dorgan

dorgan

I think this is correct.

I think the same, but I also think that the reason would be familiarity for functional programmers/mathematicians that are used to functional composition(which is essential to category theory).
If I have functions f and g, their composition g ∘ f (reads as g after f) could be visualized with this diagram:

     f             g
a───────────►b───────────►c
│                         ▲
└─────────────────────────┘
            g ∘ f

A lot of category theory constructs are built in this way, you have an a, a b and a c, you have an f that goes from a to b and a g that goes from b to c and you want to find the composition g ∘ f that goes directly from a to c. Note that the order of the operands of the composition is goes against the direction of the arrows, and I think that the order of operands in the <|> derives from this notation. If you look at it from this perspective, then it becomes the most intuitive/natural ordering, but I agree it’s hard to grasp at first.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48475 226
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31307 143
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New

We're in Beta

About us Mission Statement