I’m learning Elixir right now. And i tried to write this simple program.
But it doesn’t work.
defmodule AsciiPrint do
def p_ascii(c) when (?c >= 32 and ?c<=255) do
IO.puts " printable ASCII character"
end
def p_ascii(_), do: "non printable ASCII character"
end
What are the errors?
What are you trying to accomplish?
Is c a number or a binary string?
What do you want to return from p_ascii?
defmodule AsciiPrint do
def p_ascii(c) when c in 32..255 do
IO.puts(" printable ASCII character")
end
def p_ascii(_) do
"non printable ASCII character" # should it be IO.puts(" non printable ASCII character")?
end
end
?c is a “character literal” and transformed to the integer 99. What you want is probably to compare the value of c: … when (c >= 32) and (c <= 255), do: ….
ASCII is 7 bit only, so 128…255 do not exist in ASCII.
ASCII 127 is DEL, do you consider this one printable?
The idea of my program was to check if the argument is a printable ASCII character.
I think that it’s more appropriate to write things this way :
defmodule AsciiPrint do
def p_ascii(c) when (hd(c) in 32..126) do
IO.puts " printable ASCII character"
end
def p_ascii(_), do: "non printable ASCII character"
end
iex(1)> AsciiPrint.p_ascii(‘+’)
printable ASCII character
:ok
iex(2)> AsciiPrint.p_ascii(‘@’)
printable ASCII character
:ok
iex(3)> AsciiPrint.p_ascii(‘é’)
“non printable ASCII character”