[erlang-questions] Re: Getting the position of a list item

Attila Rajmund Nohl attila.r.nohl@REDACTED
Thu Dec 3 16:47:43 CET 2009

2009/12/2, Tim Fletcher <twoggle@REDACTED>:
>> Hmm, I fail to come up with a good usage scenario for wanting this. What
>> are
>> you needing the position of an item in a list for?
> FWIW, here's something i wrote recently:
>   base32_decode(Char) ->
>     list_index(Char, base32_alphabet()).
>   base32_alphabet() ->
>     "0123456789bcdefghjkmnpqrstuvwxyz".

I usually see code like this implemented like this:

base32_decode2(Char) when Char>=$0, Char=<$9 ->

base32_decode2(Char) when Char>=$b, Char=<$h ->

base32_decode2(Char) when Char>=$j, Char=<$k ->

base32_decode2(Char) when Char>=$m, Char=<$n ->

base32_decode2(Char) when Char>=$p, Char=<$z ->

It (ab)uses the fact that we're latin-1 (effectively ASCII) charset.
The other kind of code I usually see for this kind of task contains
one function clause for each possible inputs. I don't know, but I
think both approaches are faster than traversing the list with
string:str/2. Probably binaries could be used instead of lists to
speed up indexing.

More information about the erlang-questions mailing list