我知道Haskell试图做一些比简单地抛出错误更有利的事情
test :: Int -> Int -> String
test a b = case a/b of
Infinity -> "fool"
x -> Show x
Run Code Online (Sandbox Code Playgroud)
但是我被告知我的ghc Infinity不是数据构造函数.实际上是什么,我该如何利用它?我不想简单地检查b0
有几种方法可以做到这一点.我首选的是使用isInfinitePrelude:
test :: Int -> Int -> String
test a b = case fromIntegral a / fromIntegral b of
x | isInfinite x && x > 0 -> "fool"
| otherwise -> show x
Run Code Online (Sandbox Code Playgroud)
或者,您可以infinity在此问题中定义并比较相等(从Infinity == Infinity).
您的代码还有一些我认为与您的问题无关的问题:
Show 应该 show(/)不适用于Int参数,因此您需要使用fromIntegral转换a和b浮动的东西我也怀疑你知道这个特殊功能不需要无限检查......
test :: Int -> Int -> String
test a 0 | a > 0 = "fool"
| otherwise = show (fromIntegral a / fromIntegral b)
Run Code Online (Sandbox Code Playgroud)