Elixir Pipe
What’s the big deal with |>
, the pipe operator?
Let’s read everything from stdin, parse the lines as integers, then add up the odd ones as an example.
Spaghetti Monster
IO.puts(
Enum.reduce(
Enum.filter(
Enum.map(
String.split(IO.read(:stdio, :all)),
fn(x) -> String.to_integer(x) end
),
fn(x) -> Solution.is_odd(x) end
), 0, fn(x, acc) -> x + acc end
)
)
This is as clean as I could make this. It still sucks, though it’s valid.
Intermediate Space Junk
lines = String.split(IO.read(:stdio, :all))
nums = Enum.map(lines, fn(x) -> String.to_integer(x) end)
odds = Enum.filter(nums, fn(x) -> Solution.is_odd(x) end)
result = Enum.reduce(odds, 0, fn(x, acc) -> x + acc end)
IO.puts(result)
This is an improvement as the logic is in a friendlier form, but we’re making a lot of disposable variables.
Oh, that’s why.
String.split(IO.read(:stdio, :all))
|> Enum.map(fn(x) -> String.to_integer(x) end)
|> Enum.filter(fn(x) -> Solution.is_odd(x) end)
|> Enum.reduce(0, fn(x, acc) -> x + acc end)
|> IO.puts()
This is similar to the previous example, without the junk. |>
passes the
result as the first argument to the function on the right, so it’s a bit odd at
first (see the empty IO.puts()
for example). This is pretty clean, though.