Translating some Erlang to Elixir

Just out of curiosity, how does this Erlang snippet translate to Elixir?

Also, can elixir do this smarter?

b2h(Bin) when is_binary(Bin) ->
    << <<(hex(H)),(hex(L))>> || <<H:4,L:4>> <= Bin >>.

hex(C) when C < 10 -> $0 + C;
hex(C) -> $a + C - 10.

original source:

binary |> Base.encode16

Maybe something like

defmodule Test do
  def b2h(bin) when is_binary(bin) do
    for <<h::4, l::4 <- bin>>, into: <<>>, do: <<hex(h), hex(l)>>

  defp hex(c) when c < 10, do: ?0 + c
  defp hex(c),             do: ?a + c - 10
iex(2)> Test.b2h("aasdf")
iex(3)> Base.encode16("aasdf")
1 Like

oh… way smarter, thanks

thanks. It was the list comprehension from erlang that was looking backwards

Apples to oranges … when you compare
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].


> 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).


It’s thisX || X ... part that i can’t seem to parse in my head

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.


I tend to see [ X || ...] as “the list of X where X is … ]”.