LoginSignup
3
3

More than 5 years have passed since last update.

with以外の手段で{:ok, x}を何とかする方法

Last updated at Posted at 2016-03-22

パイプラインでok

withを置き換えるのが目的ではありませんが、パイプラインの恩恵を得ながら{:ok, x}をどうにかしたいです。withの書き方はfor寄りでパイプラインの流れの中には馴染みません。awesome-elixirから幾つか抜粋すると

plumber_girl

ruby2elixir/plumber_girl
>>>okで{:ok, x}を剥けます。

happy

vic/happy
case ~ doで包んでくれるという物。ちょっと見慣れません…

happy_path do
  {:ok, b} = a
  c(b)
else
  x -> x
end

gets rewritten to:

case(a) do
  {:ok, b} ->
    case (b) do
      {:ok, d} -> c(d)
    end
end

ok_jose

名前がw
vic/ok_jose
目的に対して直球です。

def dup(x), do: {:ok, x * 2}
def nop(x), do: {:error, x}

{:ok, 12} |> dup |> dup |> ok # => {:ok, 48}
{:ok, 24} |> nop |> dup |> ok # => {:error, 24}

tap

mgwidmann/elixir-pattern_tap
plumber_girl の物より汎用的。

defmodule Foo do
  def get_stuff(input) do
    input
      |> Enum.map(&(to_string(&1)))
      |> Foo.HardWorker.work
      |> tap({:ok, r1} ~> r1) # tap({:ok, r1}, r1) is also a supported format
      |> Enum.map(&(Foo.IntermediateResult.handle(&1)))
      |> tap({:ok, r2} ~> r2) # tap({:ok, r2}, r2) is also a supported format
  end
end

モナドは…?

(*´・ω) (ω・`*)ネー

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3