如何让它更安全?

问题描述:

我有以下功能:如何让它更安全?

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

当我尝试使用功能如下:

isElemChar 5 

然后我有例外:

<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' 

如何使功能更安全?哪种方法可以使其达到全部功能?

我可以使用Maybe数据类型,但不知道如何实现它。

+0

你试图将一个数字传递给一个只接受'Char'的函数。试试'isElemChar'5''。 – Cirdec

+0

如果用户会传递5而不是'5'如何处理异常? –

您的功能安全。你提到的“异常”实际上是编译时错误,这正是你想要错误的时候。

这是稍微你在交互模式提示符的事实隐藏,但如果你写的程序safe.hs ....

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

main = print $ isElemChar 5 

...你试图编译它...

ghc safe.hs 

...你会得到一个类似的错误

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 

没有必要使函数多个S afe,这不是python,函数params有一个类型,所以你的代码只会给你一个compile error。 如果您正在处理IO,您将永远得到一个IO([Char])IO(Char)