英文:
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 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 -> DoubleOrInt
readDoubleOrInt s = case readMaybe s of
Just i -> R i
Nothing -> 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 -> Maybe DoubleOrInt
readMaybeDoubleOrInt s = R<$>readMaybe s <|> L<$>readMaybe s
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论