rob-brown / MonadEx

Upgrade your pipelines with monads.
MIT License
306 stars 13 forks source link

bind operator #8

Closed maarek closed 7 years ago

maarek commented 7 years ago

I was wondering if it would still be idiomatic to pipe the monad's value to the right hand side function similar to the pipe operator upon a successful result monad instead of calling the fn closure and passing the value?

def my_func(value), do: IO.puts value

success(value) ~>> my_func

instead of

success(value) ~>> fn value -> my_func(value) end

rob-brown commented 7 years ago

Yes, you can do that. Though your function needs to return a monad. Here's an example you can drop in iex:

import Monad.Result

defmodule Math do
  def double(value) do
     success value * 2
  end
end

use Monad.Operators
success(42) ~>> &Math.double/1

If you want your function to take and return non-monad values, you can use Functor.fmap. It looks like this:

import Monad.Result

defmodule Math do
  def double(value) do
     value * 2
  end
end

success(42) |> Functor.fmap(&Math.double/1)

# or

import Curry
use Monad.Operators
curry(&Math.double/1) <|> success(42)