softshipper
softshipper

Reputation: 34071

How to make it more safe?

I have following function:

isElemChar :: Char -> Bool
isElemChar x = elem x ['A'..'Z'] || elem x ['a'..'z']

When I try to use the function as follow:

isElemChar 5

Then I've got the exception:

<interactive>:73:12: error:
    * No instance for (Num Char) arising from the literal `5'
    * In the first argument of `isElemChar', namely `5'
      In the expression: isElemChar 5
      In an equation for `it': it = isElemChar 5
*Cipher Data.Char> isElemChar 'a'

How to make the function more safe? Which would be the right approach to make it to total function?

I could use the Maybe datatype, but do not know how to implement it.

Upvotes: 0

Views: 73

Answers (2)

Netwave
Netwave

Reputation: 42688

There is no need to make the function more safe, this is not python, the functions params have a type, so your code will just give you a compile error. If you are dealing with IO you will always get an IO([Char]) or a IO(Char).

Upvotes: 0

Michal Charemza
Michal Charemza

Reputation: 27012

Your function is safe. The "exception" you mention is actually a compile-time error, which is exactly the time you want errors.

This is slightly hidden by the fact you're at an interactive prompt, but if you wrote the program safe.hs....

isElemChar :: Char -> Bool
isElemChar x = elem x ['A'..'Z'] || elem x ['a'..'z']

main = print $ isElemChar 5

... and you tried to compile it...

ghc safe.hs

... you would get a similar error

safe.hs:5:27: error:
    • No instance for (Num Char) arising from the literal ‘5’
    • In the first argument of ‘isElemChar’, namely ‘5’
      In the second argument of ‘($)’, namely ‘isElemChar 5’
      In the expression: print $ isElemChar 5

Upvotes: 11

Related Questions