defmodule Test do
def b2h(bin) when is_binary(bin) do
for <<h::4, l::4 <- bin>>, into: <<>>, do: <<hex(h), hex(l)>>
end
defp hex(c) when c < 10, do: ?0 + c
defp hex(c), do: ?a + c - 10
end
Apples to oranges … when you compare Base.do_encode16
to base16:encode
similar things are going on anyway - though Base seems to use lookups rather than calculations.
Again that is in the eye of the beholder - even though I was exposed to Elixir first I prefer the Erlang’s comprehension syntax as it seems less cluttered and more “organic” in a left to-right culture.
> [X || X <- [1,2,a,3,4,b,5,6], X > 3].
[a,4,b,5,6]
vs.
> for x <- [1,2,?a,3,4,?b,5,6], x > 3, do: x
[97, 4, 98, 5, 6]
With the Erlang syntax I’m getting more the sense of the list being created left to right - first showing me the shape of a single element that will be cons’ed to the list, then letting me know where the raw data comes from. Comparatively speaking the for syntax seems almost imperative (i.e. a recipe how to do something rather than a declaration of what is needed):
For these inputs
Into this data structure (List, Map, etc.)
Append this element
Don’t ditch a language just because it doesn’t seem “pretty” on first blush. I got used to Erlang’s syntax quite quickly (… though I still don’t want to revisit APL).
I see it as a variation of the [h|t] syntax, interpreting || as “to repeatedly append” something of the shape of X - shunting each element over to the left in turn.
PS: I also thought that for was somewhat misleading - comprehensions made more sense when I started thinking map.