Get current value while piping (something like &1)

I think i’m missing something obvious about the syntax but I don’t know what… the thing is to fetch the current value from a pipe and pass it as argument to the next function, my current implementation looks like:

foo_with_bar = foo |> ...  |> add_bar() 

something(foo_with_bar, foo_with_bar.bar) |> do_more()

I’d like something like

foo
|> ...
|> add_bar()
|> &something(&1.bar) # get the current "foo" and pass "foo.bar"
|> do_more()

I’ve tried every syntax varations that came to my mind but can’t get it right. It is possible to do that?

Thanks :smiley:

Is foo enumerable? If yes, Enum.map is your friend.

|> Enum.map(&something(&1.bar))

No, it is just a map, I’ve updated the OP, something is defined as something/2

There is no &1 syntax in pipes. However, you can rewrite you pipe into

foo
|> ...
|> add_bar()
|> Map.fetch!(:bar)
|> something()
|> do_more()

Or you can use then like

foo
|> ...
|> add_bar()
|> then(&something(&1, &1.bar))
|> do_more()

Don’t forget to mark the correct answer

1 Like
|> then(& &1.bar)

You can use anonymous functions in pipes like so
foo |> (&something(&1, &1.bar)).()

However I’d recommend using something like the aforementioned then/2 or perhaps rewriting the logic in a way that would make functions more composable in the first place.

1 Like

I am late here so I’ll just echo the others: either use then/2 or just make your own functions that accept one thing and return something from inside of it, which makes pipes more composable and more readable.

1 Like