diff --git a/lib/elixir/lib/kernel.ex b/lib/elixir/lib/kernel.ex index 2c9ab81c7ce..259600acabf 100644 --- a/lib/elixir/lib/kernel.ex +++ b/lib/elixir/lib/kernel.ex @@ -2654,7 +2654,7 @@ defmodule Kernel do Pipes the first argument, `value`, into the second argument, a function `fun`, and returns the result of calling `fun`. - In other words, it invokes the function `fun` with `value` as argument, + In other words, it invokes the function `fun` with `value` as the argument, and returns its result. This is most commonly used in pipelines, using the `|>/2` operator, allowing you @@ -2675,6 +2675,27 @@ defmodule Kernel do end end + @doc """ + Pipes `value` into the given `fun` when `predicate` is truthy. + + When the `predicate` is truthy `fun` will be called with `value`, + otherwise `value` is returned as is. + This is most commonly used in pipelines, allowing you + to pipe a value to a function outside of its first argument. + + ### Examples + + iex> opts = [flag: true] + iex> 1 |> then?(opts[:flag], & &1 + 10) + 11 + """ + @doc since: "1.12.0" + defmacro then?(value, predicate, fun) do + quote bind_quoted: [value: value, predicate: predicate, fun: fun] do + if predicate, do: fun.(value), else: value + end + end + @doc """ Gets a value from a nested structure.