What is the most idiomatic way to convert this: "helloworld"
to ["h","e","l","l","o","w","o","r","l","d"]
in Erlang ?
Asked
Active
Viewed 1,661 times
1

Muhammad Lukman Low
- 8,177
- 11
- 44
- 54
-
1Well, the string is already a list of characters. What you are asking for is a list of one character strings/lists. One would wonder why you would like to do it for? – Hynek -Pichi- Vychodil Mar 13 '18 at 07:37
3 Answers
6
The string is a list of characters
1> [$h, $e, $l, $l, $o, $w, $o, $r, $l, $d].
"helloworld"
So if you ask
What is the most idiomatic way to convert a string to characters in Erlang?
The answer is none, it already is a list of characters, you don't have to convert it.
If you ask, how to apply some function to the characters of the string, for example how to subtract 32.
2> [ X - 32 || X <- "helloworld" ].
"HELLOWORLD"
Or if you ask how to get a list of one character strings
3> [[X] || X <- "helloworld"].
["h","e","l","l","o","w","o","r","l","d"]

Hynek -Pichi- Vychodil
- 26,174
- 5
- 52
- 73
1
an alternative to list comprehension in this simple case is the map function from lists module:
String = "helloworld",
lists:map(fun(X) -> [X] end, String).

Pascal
- 13,977
- 2
- 24
- 32
0
You can try with the code below:
1> [[X] || X <- "helloworld"].
["h","e","l","l","o","w","o","r","l","d"]

Muhammad Lukman Low
- 8,177
- 11
- 44
- 54

Pouriya
- 1,626
- 11
- 19