├── TODO ├── test ├── test_helper.exs └── rop_test.exs ├── .gitignore ├── mix.lock ├── .travis.yml ├── LICENCE ├── config └── config.exs ├── mix.exs ├── lib └── rop.ex └── README.md /TODO: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /cover 3 | /deps 4 | erl_crash.dump 5 | *.ez 6 | doc/* 7 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{"earmark": {:hex, :earmark, "0.2.0"}, 2 | "ex_doc": {:hex, :ex_doc, "0.11.3"}, 3 | "ex_spec": {:hex, :ex_spec, "1.0.0"}} 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: elixir 2 | elixir: 1.6.0 3 | notifications: 4 | recipients: 5 | - roman.heinrich@gmail.comm 6 | otp_release: 7 | - 18.0 8 | script: "MIX_ENV=test mix local.hex --force && MIX_ENV=test mix do deps.get, test" 9 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Roman Heinrich 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | use Mix.Config 4 | 5 | # This configuration is loaded before any dependency and is restricted 6 | # to this project. If another project depends on this project, this 7 | # file won't be loaded nor affect the parent project. For this reason, 8 | # if you want to provide default values for your application for 9 | # 3rd-party users, it should be done in your "mix.exs" file. 10 | 11 | # You can configure for your application as: 12 | # 13 | # config :rop, key: :value 14 | # 15 | # And access this configuration in your application as: 16 | # 17 | # Application.get_env(:rop, :key) 18 | # 19 | # Or configure a 3rd-party app: 20 | # 21 | # config :logger, level: :info 22 | # 23 | 24 | # It is also possible to import configuration files, relative to this 25 | # directory. For example, you can emulate configuration per environment 26 | # by uncommenting the line below and defining dev.exs, test.exs and such. 27 | # Configuration from the imported file will override the ones defined 28 | # here (which is why it is important to import them last). 29 | # 30 | # import_config "#{Mix.env}.exs" 31 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Rop.Mixfile do 2 | use Mix.Project 3 | 4 | @version "0.5.2" 5 | 6 | def project do 7 | [app: :rop, 8 | version: @version, 9 | elixir: "~> 1.0", 10 | build_embedded: Mix.env == :prod, 11 | start_permanent: Mix.env == :prod, 12 | package: package(), 13 | docs: [extras: ["README.md"]], 14 | deps: deps()] 15 | end 16 | 17 | # Configuration for the OTP application 18 | # 19 | # Type "mix help compile.app" for more information 20 | def application do 21 | [applications: [:logger]] 22 | end 23 | 24 | # Dependencies can be Hex packages: 25 | # 26 | # {:mydep, "~> 0.3.0"} 27 | # 28 | # Or git/path repositories: 29 | # 30 | # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} 31 | # 32 | # Type "mix help deps" for more examples and options 33 | defp deps do 34 | [ 35 | {:ex_spec, "~> 1.0", only: :test}, 36 | {:earmark, "~> 0.2", only: :dev}, 37 | {:ex_doc, "~> 0.11", only: :dev} 38 | ] 39 | end 40 | 41 | 42 | defp package do 43 | [ 44 | maintainers: ["Roman Heinrich", "Remigiusz Jackowski", "Zohaib Rauf"], 45 | licenses: ["MIT License"], 46 | description: "Some convenient macros to enable railsway-oriented programming in Elixir", 47 | links: %{ 48 | github: "https://github.com/ruby2elixir/rop", 49 | docs: "http://hexdocs.pm/rop/#{@version}/" 50 | } 51 | ] 52 | end 53 | 54 | end 55 | -------------------------------------------------------------------------------- /test/rop_test.exs: -------------------------------------------------------------------------------- 1 | defmodule RopTest do 2 | use ExSpec, async: true 3 | import ExUnit.CaptureIO 4 | use Rop 5 | doctest Rop 6 | 7 | 8 | ExSpec.describe ">>> macro" do 9 | test "returns the piped value in case of happy path" do 10 | assert (0 |> inc >>> inc >>> inc) == {:ok, 3} 11 | end 12 | 13 | test "returns the value of first error" do 14 | assert (0 |> inc >>> error) == {:error, "Error at 1"} 15 | end 16 | 17 | test "propagates the error" do 18 | assert (0 |> inc >>> error >>> inc >>> inc) == {:error, "Error at 1"} 19 | end 20 | 21 | test "propagates the correct error message" do 22 | assert (0 |> inc >>> inc >>> error >>> error >>> inc) == {:error, "Error at 2"} 23 | end 24 | end 25 | 26 | ExSpec.describe "try_catch macro" do 27 | test "catches and returns raised errors in a tagged tupple { :error, %SomeError{} } if something breaks" do 28 | assert (:raise |> try_catch(arithmetic_error)) == {:error, %ArithmeticError{}} 29 | end 30 | 31 | test "returns the value otherwise" do 32 | assert (:pass |> try_catch(arithmetic_error)) == 1 33 | end 34 | end 35 | 36 | ExSpec.describe "tee" do 37 | test "passes the arguments through after executing them in the function" do 38 | a = (fn -> 39 | 0 |> simple_inc |> simple_inc |> tee(simple_sideeffect) 40 | end) 41 | 42 | assert a.() == {:ok, 2} 43 | end 44 | 45 | test "the sideeffect in the function is executed" do 46 | a = (fn -> 47 | 0 |> simple_inc |> simple_inc |> tee(simple_sideeffect) 48 | end) 49 | assert capture_io(a) == "2\n" 50 | end 51 | end 52 | 53 | ExSpec.describe "bind" do 54 | test "wraps a function to return a tagged tuple `{:ok, result}` from the returned value" do 55 | a = 0 |> simple_inc |> bind(simple_inc) 56 | assert a == {:ok, 2} 57 | end 58 | end 59 | 60 | # returns an unrelated to passed-in arguments value + has a side-effect (logging) 61 | defp simple_sideeffect(a) do 62 | IO.inspect a 63 | :unrelated 64 | end 65 | 66 | defp inc(cnt) do 67 | {:ok, simple_inc(cnt)} 68 | end 69 | 70 | defp simple_inc(cnt) do 71 | cnt + 1 72 | end 73 | 74 | defp error(v) do 75 | {:error, "Error at #{v}"} 76 | end 77 | 78 | defp arithmetic_error(:pass) do 79 | 1 80 | end 81 | 82 | defp arithmetic_error(:raise) do 83 | 1 / 0 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /lib/rop.ex: -------------------------------------------------------------------------------- 1 | # https://gist.github.com/zabirauf/17ced02bdf9829b6956e 2 | # https://github.com/remiq/railway-oriented-programming-elixir 3 | 4 | defmodule Rop do 5 | defmacro __using__(_) do 6 | quote do 7 | import Rop 8 | end 9 | end 10 | 11 | 12 | @doc ~s""" 13 | Extracts the value from a tagged tuple like {:ok, value} 14 | Raises the value from a tagged tuple like {:error, value} 15 | Raise the arguments else 16 | 17 | For example: 18 | iex> ok({:ok, 1}) 19 | 1 20 | 21 | iex> ok({:error, "some"}) 22 | ** (RuntimeError) some 23 | 24 | iex> ok({:anything, "some"}) 25 | ** (ArgumentError) raise/1 and reraise/2 expect a module name, string or exception as the first argument, got: {:anything, \"some\"} 26 | """ 27 | def ok({:ok, x}), do: x 28 | def ok({:error, x}), do: raise x 29 | def ok(x), do: raise x 30 | 31 | 32 | @doc ~s""" 33 | No need to stop pipelining in case of an error somewhere in the middle 34 | 35 | Example: 36 | iex> inc = fn(x)-> {:ok, x+1} end 37 | iex> 1 |> (inc).() >>> (inc).() 38 | {:ok, 3} 39 | """ 40 | defmacro left >>> right do 41 | quote do 42 | (fn -> 43 | case unquote(left) do 44 | {:ok, x} -> x |> unquote(right) 45 | {:error, _} = expr -> expr 46 | end 47 | end).() 48 | end 49 | end 50 | 51 | @doc ~s""" 52 | Wraps a simple function to return a tagged tuple with `:ok` to comply to the protocol `{:ok, result}` 53 | 54 | Example: 55 | iex> 1 |> Integer.to_string 56 | "1" 57 | iex> 1 |> bind(Integer.to_string) 58 | {:ok, "1"} 59 | 60 | 61 | iex> inc = fn(x)-> x+1 end 62 | iex> 1 |> bind((inc).()) >>> (inc).() 63 | 3 64 | iex> 1 |> bind((inc).()) >>> bind((inc).()) 65 | {:ok, 3} 66 | """ 67 | defmacro bind(args, func) do 68 | quote do 69 | (fn -> 70 | result = unquote(args) |> unquote(func) 71 | {:ok, result} 72 | end).() 73 | end 74 | end 75 | 76 | @doc ~s""" 77 | Wraps raising functions to return a tagged tuple `{:error, ErrorMessage}` to comply with the protocol 78 | 79 | Example: 80 | iex> r = fn(_)-> raise "some" end 81 | iex> inc = fn(x)-> x + 1 end 82 | iex> 1 |> bind((inc).()) >>> try_catch((r).()) >>> bind((inc).()) 83 | {:error, %RuntimeError{message: "some"}} 84 | """ 85 | defmacro try_catch(args, func) do 86 | quote do 87 | (fn -> 88 | try do 89 | unquote(args) |> unquote(func) 90 | rescue 91 | e -> {:error, e} 92 | end 93 | end).() 94 | end 95 | end 96 | 97 | 98 | 99 | @doc ~s""" 100 | Like a similar Unix utility it does some work and returns the input. 101 | See [tee (command), Unix](https://en.wikipedia.org/wiki/Tee_(command)). 102 | 103 | Example: 104 | iex> inc = fn(x)-> IO.inspect(x); {:ok, x + 1} end 105 | iex> 1 |> tee((inc).()) >>> tee((inc).()) >>> tee((inc).()) 106 | {:ok, 1} 107 | """ 108 | defmacro tee(args, func) do 109 | quote do 110 | (fn -> 111 | unquoted_args = unquote(args) 112 | unquoted_args |> unquote(func) 113 | {:ok, unquoted_args} 114 | end).() 115 | end 116 | end 117 | end 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ROP - Railway Oriented Programming in Elixir 2 | 3 | 4 | [![Build status](https://travis-ci.org/ruby2elixir/rop.svg "Build status")](https://travis-ci.org/ruby2elixir/rop) 5 | [![Hex version](https://img.shields.io/hexpm/v/rop.svg "Hex version")](https://hex.pm/packages/rop) 6 | ![Hex downloads](https://img.shields.io/hexpm/dt/rop.svg "Hex downloads") 7 | 8 | ---- 9 | 10 | Some macros to enable railsway-oriented programming in Elixir. 11 | Collected from code snippets and wrapped into a simple library for your convenience. 12 | 13 | 14 | For more examples please check the tests here: 15 | - [Examples](https://github.com/ruby2elixir/rop/blob/master/test/rop_test.exs) 16 | 17 | 18 | ## Sources for inspiration + copying 19 | - https://github.com/remiq/railway-oriented-programming-elixir 20 | - https://gist.github.com/zabirauf/17ced02bdf9829b6956e (Railway Oriented Programming macros in Elixir) 21 | 22 | 23 | ## Installation 24 | If [available in Hex](https://hex.pm/docs/publish), the package can be installed as: 25 | 26 | 1. Add rop to your list of dependencies in `mix.exs`: 27 | ```elixir 28 | def deps do 29 | [{:rop, "~> 0.5"}] 30 | end 31 | ``` 32 | 33 | 34 | 35 | ## Usage 36 | Call 37 | 38 | ```elixir 39 | use Rop 40 | ``` 41 | 42 | in your module. That will give you access to following macros/functions: 43 | 44 | ### `>>>` 45 | No need to stop pipelining in case of an error somewhere in the middle 46 | 47 | 48 | used like: `1 |> fn1 >>> fn2 >>> fn3 >>> fn4` 49 | 50 | ```elixir 51 | defmodule TripleArrowExample do 52 | use Rop 53 | def tagged_inc(v) do 54 | IO.puts "inc for #{v}" # sideeffect for demonstration 55 | {:ok, v + 1} 56 | end 57 | 58 | def error_fn(_) do 59 | {:error, "I'm a bad fn!"} 60 | end 61 | 62 | def raising_fn(_) do 63 | raise "I'm raising!" 64 | end 65 | 66 | def result do 67 | 1 |> tagged_inc >>> tagged_inc >>> tagged_inc 68 | end 69 | 70 | def error_result do 71 | 1 |> tagged_inc >>> tagged_inc >>> error_fn >>> tagged_inc 72 | end 73 | 74 | def raising_result do 75 | 1 |> tagged_inc >>> tagged_inc >>> raising_fn >>> tagged_inc 76 | end 77 | end 78 | 79 | iex> TripleArrowExample.result 80 | inc for 1 81 | inc for 2 82 | inc for 3 83 | {:ok, 4} 84 | 85 | ### increases twice, errors and tries to increase again 86 | ### notice that after errored result we don't execute any function anymore in the pipeline, 87 | ### e.g. only tagged_inc before error_fn were executed. 88 | iex> TripleArrowExample.error_result 89 | inc for 1 90 | inc for 2 91 | {:error, "I'm a bad fn!"} 92 | 93 | ### raises... We'll fix it in a later example for try_catch! 94 | iex> TripleArrowExample.raising_result 95 | inc for 1 96 | inc for 2 97 | ** (RuntimeError) I'm raising! 98 | ``` 99 | 100 | 101 | ### `bind` 102 | Wraps a simple function to return a tagged tuple with `:ok` to comply to the protocol `{:ok, result}`: e.g. 103 | 104 | ```elixir 105 | defmodule BindExample do 106 | use Rop 107 | def inc(v) do 108 | v + 1 109 | end 110 | 111 | def only_last_pipe_tagged_result(v) do 112 | v |> inc |> bind(inc) 113 | end 114 | 115 | def result_fully_tagged(v) do 116 | v |> bind(inc) >>> bind(inc) >>> bind(inc) 117 | end 118 | end 119 | iex> BindExample.only_last_pipe_tagged_result(2) 120 | {:ok, 4} 121 | 122 | iex> BindExample.result_fully_tagged(2) 123 | {:ok, 5} 124 | ``` 125 | 126 | 127 | ### `try_catch` 128 | 129 | Wraps raising functions to return a tagged tuple `{:error, ErrorMessage}` to comply with the protocol 130 | 131 | ```elixir 132 | # modified example from TripleArrowExample to handle raising functions 133 | defmodule TryCatchExample do 134 | use Rop 135 | def tagged_inc(v) do 136 | IO.puts "inc for #{v}" # sideeffect for demonstration 137 | {:ok, v + 1} 138 | end 139 | 140 | def raising_fn(_) do 141 | raise "I'm raising!" 142 | end 143 | 144 | def result do 145 | 1 |> tagged_inc >>> tagged_inc >>> tagged_inc 146 | end 147 | 148 | def raising_result_wrapped(v) do 149 | v |> tagged_inc >>> tagged_inc >>> try_catch(raising_fn) >>> tagged_inc 150 | end 151 | end 152 | 153 | iex> TryCatchExample.raising_result_wrapped(1) 154 | inc for 1 155 | inc for 2 156 | {:error, %RuntimeError{message: "I'm raising!"}} 157 | ``` 158 | 159 | 160 | #### `tee` 161 | 162 | Like a similar Unix utility it does some work and returns the input. See [tee (command), Unix](https://en.wikipedia.org/wiki/Tee_(command)). 163 | 164 | 165 | 166 | ```elixir 167 | defmodule TeeExample do 168 | use Rop 169 | def tagged_inc(v) do 170 | IO.puts "inc for #{v}" # sideeffect for demonstration 171 | {:ok, v + 1} 172 | end 173 | 174 | def calc(v) do 175 | v |> tee(tagged_inc) >>> tee(tagged_inc) >>> tee(tagged_inc) 176 | end 177 | end 178 | 179 | # notice how the incremented value is not passed through the pipeline, 180 | # but just the original argument `1` 181 | iex> TeeExample.calc(1) 182 | inc for 1 183 | inc for 1 184 | inc for 1 185 | _{:ok, 1} 186 | ``` 187 | 188 | 189 | ### `ok` 190 | 191 | A simple utility function to extract the value from `{:ok, result}` tuple and to raise the error in `{:error, ErrorStruct}`. 192 | 193 | ```elixir 194 | defmodule OkExample do 195 | use Rop 196 | def ok_result do 197 | {:ok, 1} |> ok 198 | end 199 | 200 | def error_result do 201 | {:error, %ArithmeticError{}} |> ok 202 | end 203 | 204 | def any_value_result do 205 | "bad value" |> ok 206 | end 207 | end 208 | 209 | iex> OkExample.ok_result 210 | 1 211 | 212 | iex> OkExample.error_result 213 | ** (ArithmeticError) bad argument in arithmetic expression 214 | (rop) lib/rop.ex:70: Rop.ok/1 215 | 216 | 217 | iex> OkExample.any_value_result 218 | ** (RuntimeError) bad value 219 | (rop) lib/rop.ex:71: Rop.ok/1 220 | ``` 221 | 222 | 223 | 224 | 225 | Background information 226 | ---------------------- 227 | 228 | ### Some discussions about Railsway programming: 229 | - http://insights.workshop14.io/2015/10/18/handling-errors-in-elixir-no-one-say-monad.html 230 | - http://blog.danielberkompas.com/2015/09/03/better-pipelines-with-monadex.html 231 | - http://onor.io/2015/08/27/railway-oriented-programming-in-elixir/ 232 | - http://www.zohaib.me/railway-programming-pattern-in-elixir/ 233 | - http://www.zohaib.me/monads-in-elixir-2/ 234 | - http://fsharpforfunandprofit.com/posts/recipe-part2/ 235 | - https://www.reddit.com/r/programming/comments/30coly/railway_oriented_programming_in_elixir/ 236 | 237 | ### Code (Railsway Programming) 238 | - https://github.com/remiq/railway-oriented-programming-elixir/blob/master/lib/rop.ex 239 | - https://gist.github.com/zabirauf/17ced02bdf9829b6956e (Railway Oriented Programming macros in Elixir) -> Rop 240 | - https://github.com/CrowdHailer/OK/blob/master/lib/ok.ex 241 | - https://gist.github.com/danielberkompas/52216db76d764a68dfa3 -> pipeline.ex 242 | 243 | ### Code (Monads) 244 | - https://github.com/rmies/monad.git 245 | - https://github.com/rob-brown/MonadEx.git 246 | 247 | 248 | ### Altenatives 249 | - https://github.com/batate/elixir-pipes - Macros for more flexible composition with the Elixir Pipe operator 250 | 251 | --------------------------------------------------------------------------------