Is it possible to prepend to a list in a pipeline

[2,3,4]
|> double()
|> Kernel.++(1)

Would result in [4, 6, 8, 1] (along with being “slow” since it has to traverse the entire list). Instead is there an easy way to prepend to the list resulting in [1, 4, 6, 8]?

1 Like

Not sure about the “speed”, but you could List.insert_at/3

1 Like

The warnings about it being slow have more to do with making sure you avoid doing it in a loop. If you’re doing it just once it’s fine.

1 Like

Thanks! That looks about exactly what I was looking for.

Yeah, good point. This particular case is not in a loop so that’s fine.

1 Like

I guess it depends on your actual code, but FWIW I’d say [1 | double([2,3,4])] is much easier to follow than the pipe when reading the code.

1 Like

I think he actually means append because that’s how his example would turn out with |> Kernel.++. If in fact prepending though I completely agree with your example.

1 Like

I don’t know about “easy”:

iex(1)> [2,3,4] |>                   
...(1)> Enum.map(&(&1*2)) |>         
...(1)> (fn (xs,x) -> [x|xs] end).(1) 
[1, 4, 6, 8]

and alternately

iex(2)> [2,3,4] |>          
...(2)> Enum.map(&(&1*2)) |>
...(2)> (&([&2|&1])).(1)    
[1, 4, 6, 8]

Also: The Seven Myths of Erlang Performance: 2.2 Myth: Operator “++” is Always Bad

2 Likes

Ah yeah I got completely thrown off by the “slow” thing and thought we were doing appending. Whoops!

Yeah best answer: don’t prepend to a list via a pipeline.

2 Likes