As a learning exercise, I’m trying to implement the map operation for a list. My first attempt was:
def map1([], _), do: []
def map1([head | tail], f) do
[f.(head) | map1(tail, f)]
end
This works, but then I realize this was not tail recursive, because the last operation to happen is prepending an item to the list. I tried to come up with a tail recursive solution, but I can’t find a simple one. I came up with this:
but this reverses the list. I could re-reverse it afterwards of course, but isn’t there a solution that is tail recursive and does not require post-processing?
Since [head | tail] operation is optimized by compiler it’s much faster to simply call reverse (which is second [head | tail] operation) instead of appending item to list like list ++ [item] which is much more expensive.
In case you are not sure which solution is faster consider using this library: