Is using anomyous functions in pipes good practise?

I realized today that I can use anonymous functions to process “malformed” outputs inside pipes. For example:

  def str_to_int!(str) when is_bitstring(str) do
    str
    |> Integer.parse()
    |> (fn {res, ""} -> res end).()
  end

My question is, is something like that good to use or does it make code harder to read? If you start using a lot of anonymous functions in that manner, you could turn most functions into one long pipe.

1 Like

I would say it’s good as long as the anonymous function is short and concise. If it gets too bulky then it should become a proper function.

Btw: since recently, it is more idiomatic to use then:

str
    |> Integer.parse()
    |> then(fn {res, ""} -> res end)
6 Likes

Ah. Thanks. I wasn’t aware of this.

I think it makes code harder to read, and in the words of Great Leader: If all we have are opinions, I prefer mine.

2 Likes

Me too! :laughing:

For this case I wirte a macro to reverse the =.
It can rebinding the result after the in the pipe operater.

def str_to_int!(str) when is_bitstring(str) do
    str
    |> Integer.parse()
    |> tr({_,ret},into: ret)
  end

The library doc is here