A simple macro to allow bare captures in pipes

One thing to look at are ways that it might feel awkward. I tried to put it through some paces via a nonsensical example and it looks nice to my eyes in various new and existing scenarios. (* denotes new function usage)

defmodule CapturepipeTest do
  use ExUnit.Case, async: true

  import Capturepipe
  import Kernel, except: [|>: 2]

  test "capture pipe usage" do
    assert speak("Jane", "Hello") == {:ok, "...HELLO, JANE..."}
  end

  def speak(name, greeting) do
    name
    # * function that requires different order
    |> greet(greeting, &1)
    # regular function still works fine
    |> String.upcase()
    # does not disrupt adding ellipses via original method
    |> (&(&1 <> "...")).()
    # * example of adding ellipses with enhanced pipe
    # could also be ("..." <> &1) if you prefer
    |> "...#{&1}"
    # * returning a tuple
    |> {:ok, &1}
  end

  defp greet(greeting, name) do
    "#{greeting}, #{name}"
  end
end

I also wonder if it causes any confusion regarding usage of captures outside the pipe operator. I can’t think of any good examples off-hand, but perhaps a developer might think the & is somehow unnecessary for, say, Enum functions. I don’t know. It is still looking really good to me.

4 Likes