我喜欢F#中的Int32.TryParse函数,我想在Haskell中创建自己的函数:
import qualified Control.Exception as CE
handler:: CE.ErrorCall -> IO (Bool,Int)
handler e = return (False,0)
s2Int :: String->Int
s2Int s = read s
tryParse :: String -> IO (Bool,Int)
tryParse s = CE.catch (s2Int s `seq` return (True,read s)) handler
解析Int的七行?!有更短的方式吗?
...谢谢
答案 0 :(得分:9)
您可以使用reads
:
tryParse :: String -> (Bool, Int)
tryParse s =
case reads s of
[(i, "")] -> (True, i)
_ -> (False, 0)
然而,返回Maybe Int
会更加个性化:
tryParse :: String -> Maybe Int
tryParse s =
case reads s of
[(i, "")] -> Just i
_ -> Nothing
答案 1 :(得分:9)
您可以使用readMaybe
中的Text.Read
并获得Maybe Int
代替:
import Text.Read
tryParse :: String -> Maybe Int
tryParse = readMaybe