gpt4 book ai didi

haskell - 读取比率时如何检测零分母?

转载 作者:行者123 更新时间:2023-12-02 01:46:17 25 4
gpt4 key购买 nike

我想从字符串中读取比率,但我不希望我的程序在分母为零时崩溃。如何检测零分母并避免错误?只需使用 readMaybe不起作用:

Prelude Text.Read> readMaybe "1 % 0" :: Maybe Rational
Just *** Exception: Ratio has zero denominator
我创造了这个远非完美的解决方案:
readMaybeRational :: String -> Maybe Rational
readMaybeRational s =
case ((readMaybe $ drop 1 $ dropWhile (/='%') s) :: Maybe Int)
of Just 0 -> Nothing
_ -> readMaybe s
但我不知道如何很好地处理嵌套的比率:
"Just (1 % 0)"
如果我可以覆盖 Ratio 的 Read 实例,我可以让 readMaybe 在分母为零时返回 Nothing:
instance (Integral a, Read a) => Read (Ratio a) where
readPrec =
parens
( prec ratioPrec
( do x <- step readPrec
expectP (L.Symbol "%")
y <- step readPrec
-- is y 0? If so, do something here
return (x % y)
)
)
但我很确定我不能那样做。

最佳答案

我认为您最好的解决方案是 newtype包装 Ratio , 像这样:

import Control.Monad
import GHC.Read
import GHC.Real
import qualified Text.Read.Lex as L
import Text.ParserCombinators.ReadPrec

newtype SaneReadRatio a = SaneReadRatio (Ratio a)
type SaneReadRational = SaneReadRatio Integer

instance (Integral a, Read a) => Read (SaneReadRatio a) where
readPrec =
parens
( prec ratioPrec
( do x <- step readPrec
expectP (L.Symbol "%")
y <- step readPrec
guard (y /= 0)
return (SaneReadRatio (x % y))
)
)

readListPrec = readListPrecDefault
readList = readListDefault
通过 SaneReadRational 读取数据来使用它代替 Rational ,然后使用 coerce来自 Data.Coerce结果,这将把它改回底层 Rational无论它在你的字体中埋藏的多么深。

关于haskell - 读取比率时如何检测零分母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63093859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com