我有以下简单的代码来查找转换为int的字符串是否有大于127的字符:
isbinary ss = do
if any (>127) ss
then return "True"
else return "False"
mystr = "this is a test"
main = do
print (isbinary mystr)
但是,我遇到以下错误:
$ runghc isbinary.hs
isbinary.hs:9:9: error:
• Ambiguous type variable ‘m0’ arising from a use of ‘print’
prevents the constraint ‘(Show (m0 [Char]))’ from being solved.
Probable fix: use a type annotation to specify what ‘m0’ should be.
These potential instances exist:
instance (Show a, Show b) => Show (Either a b)
-- Defined in ‘Data.Either’
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
instance (Show a, Show b) => Show (a, b) -- Defined in ‘GHC.Show’
...plus 14 others
...plus 24 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In a stmt of a 'do' block: print (isbinary mystr)
In the expression: do { print (isbinary mystr) }
In an equation for ‘main’: main = do { print (isbinary mystr) }
isbinary.hs:9:16: error:
• No instance for (Num Char) arising from a use of ‘isbinary’
• In the first argument of ‘print’, namely ‘(isbinary mystr)’
In a stmt of a 'do' block: print (isbinary mystr)
In the expression: do { print (isbinary mystr) }
print $ isbinary mystr
也不起作用。
问题出在哪里,如何解决?谢谢。
答案 0 :(得分:5)
问题在于Char
不是数字类型(不同于C语言),这就是No instance for (Num Char) arising from a use of ‘isbinary'
试图告诉您的。您需要对其进行显式转换。让我们搜索-我在Hoogle中输入了Char -> Int
。第二个结果ord
是我们想要的。
import Data.Char (ord)
isbinary :: String -> Bool
isbinary s = any (\c -> ord c > 127) s
要使意图更清晰,您可以使用isAscii函数
import Data.Char (isAscii)
isbinary :: String -> Bool
isbinary s = any (\c -> not (isAscii c)) s
稍微清理一下代码(我们通常是eta-reduce并使用camelCase名称)
import Data.Char (isAscii)
isBinary :: String -> Bool
isBinary = any (not . isAscii)
另一种可能的解决方案是编写isBinary = any (> '\127')
。