Scatman_John
Scatman_John

Reputation: 107

How to make program keep ASCII values in erlang?

I have a function where I enter from the erlang shell:

huffman:table([$H,$E,$L,$L,$O]).

I want to keep the ASCII values like that, but mine are changed into integers in the output. How do I make the program not interpret them into integers?

Upvotes: 0

Views: 398

Answers (3)

legoscia
legoscia

Reputation: 41568

As $H is just another way of writing the integer 72, there is no way to print it as $H built-in to Erlang. You'd have to write your own function to output the values this way.

In the example you show, it looks like you need to keep small integers as integers, while printing alphabetic values as letters. Something like this might work:

maybe_char_to_string(N) when $A =< N, N =< $Z ->
    [$$, N];
maybe_char_to_string(N) ->
    integer_to_list(N).

This is what it outputs:

3> foo:maybe_char_to_string($H).
"$H"
4> foo:maybe_char_to_string(1).
"1"

Upvotes: 2

tkowal
tkowal

Reputation: 9289

If you want to print something as string, use:

io:format("~s", [String]).

Upvotes: 1

filmor
filmor

Reputation: 32212

Erlang doesn't distinguish characters and integers. In particular, Erlang string-literals like "HELLO" result in a list [$H, $E, $L, $L, $O]. The shell decides by a heuristic (basically checking that all integers are printable unicode characters) whether it outputs [72, 69, 76, 76, 79] or "HELLO". Here's the output in my shell session:

Erlang R16B03 (erts-5.10.4) [64-bit] [smp:4:4] [async-threads:10]

Eshell V5.10.4  (abort with ^G)
1> [$H,$E,$L,$L,$O].
"HELLO"
2> 

Upvotes: 3

Related Questions