Function to check if printable ASCII character not working

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 conditions to make a function work ?

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
iex(8)> AsciiPrint.p_ascii(1)
"non printable ASCII character"
iex(9)> AsciiPrint.p_ascii(200)
 printable ASCII character
:ok
iex(10)> AsciiPrint.p_ascii(2001)
"non printable ASCII character"
1 Like

The end result should look like this :
iex> AsciiPrint.p_ascii(+)
“printable ASCII character”

+ is an operator. So you would probably need to write macros or something to work on AST.

It’s easier to do it like this

iex> AsciiPrint.p_ascii(?+)
"printable ASCII character"
iex> AsciiPrint.p_ascii("+")
"printable ASCII character"
1 Like

Thank you. Your answer made things clearer

  1. ?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: ….
  2. ASCII is 7 bit only, so 128…255 do not exist in ASCII.
  3. ASCII 127 is DEL, do you consider this one printable?
1 Like

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”

Yeah, just have seen it.

I’d prefer to call it as p_ascii(?@)… Your implementation will happily accept p_ascii([32, :foo]) as a printable ASCII character…

2 Likes

You’re right. I will edit it.
Thank you for your answers :slight_smile: !
It’s very helpful.