Read either Double or Int

huangapple go评论49阅读模式
英文:

Read either Double or Int

问题

read function requires type annotation. However I want to make it read int as int, double as double when either int or double is provided. Can we do that?

英文:

Read either Double or Int

read function requires type annotation. However I want to make it read int as int , double as double when either int or double is provided. Can we do that?

Thanks.

答案1

得分: 3

你可以使用 readMaybe 首先尝试将其解析为 Int,如果失败,再尝试将其解析为 Double。 (请注意,反过来是行不通的,因为整数也是有效的双精度浮点数。)

readDoubleOrInt :: String -> DoubleOrInt
readDoubleOrInt s = case readMaybe s of
   Just i  -> R i
   Nothing -> L $ read s

顺便提一下,最好根本不使用 read,而仅使用 readMaybe / readsPrec,还要定义适合处理可能失败情况的实例。上述的失败处理版本也可以使用 Alternative 组合子来很好地编写:

readMaybeDoubleOrInt :: String -> Maybe DoubleOrInt
readMaybeDoubleOrInt s = R <$> readMaybe s <|> L <$> readMaybe s
英文:

You can use readMaybe to first attempt parsing it as an Int, if that fails you read it as a Double. (Note the other way around wouldn't work, because integers are also valid doubles.)

readDoubleOrInt :: String -&gt; DoubleOrInt
readDoubleOrInt s = case readMaybe s of
   Just i  -&gt; R i
   Nothing -&gt; L $ read s

BTW it's actually better not to use read at all, but only readMaybe / readsPrec, and also defining your instance suitable to handle possible failures. The failure-handling version of the above can also nicely be written using Alternative combinators:

readMaybeDoubleOrInt :: String -&gt; Maybe DoubleOrInt
readMaybeDoubleOrInt s = R&lt;$&gt;readMaybe s &lt;|&gt; L&lt;$&gt;readMaybe s

huangapple
  • 本文由 发表于 2023年3月7日 20:17:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定