[erlang-questions] lists

zxq9 zxq9@REDACTED
Tue Sep 17 05:51:09 CEST 2019

On 2019/09/17 8:44, Sam Overdorf wrote:
> How do I tell the difference between:
> "sam1"
> ["sam1","sam2"]
> They are both lists but behave differently when I apply
>    [H|T] = List.
>    H = "s"
>    H = "sam1".
>    The second one is what I want and then stop breaking them down.

"sam1" is syntactic sugar for [$s, $a, $m, $1].

["sam1", "sam2"] is likewise syntactic sugar for
[[$s, $a, $m, $1], [$s, $a, $m, $1]]

With this in mind, if I want to take the first 's' character from "sam1" 
I can do:

[H | _] = "sam1".

If I want to get the first character from the second string in a list of 
strings I could do this:

1> [_, [H | _]] = ["sam", "bob"].
2> H.
3> $b.

The syntax $[character] is a shorthand for the unicode codepoint of a 
given character. 98 is the numeric value of the character 'b', so that 
is what we see there.

With this in mind, I can construct the string/list "sam" by finding the 
codepoints for the characters 's', 'a', and 'm' and putting the numeric 
values in a list:

4> $s.
5> $a.
6> $m.
7> [115, 97, 109].

Play around with lists inside of lists a bit and you'll find that a list 
of strings is just a nested list. There are many convenience functions 
for operating over deep lists of strings like this in the unicode and 
string modules.


More information about the erlang-questions mailing list