我喜欢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
Run Code Online (Sandbox Code Playgroud)
解析Int的七行?!有更短的方式吗?
谢谢...
你可以使用reads:
tryParse :: String -> (Bool, Int)
tryParse s =
case reads s of
[(i, "")] -> (True, i)
_ -> (False, 0)
Run Code Online (Sandbox Code Playgroud)
Maybe Int然而,返回a会更加个性化:
tryParse :: String -> Maybe Int
tryParse s =
case reads s of
[(i, "")] -> Just i
_ -> Nothing
Run Code Online (Sandbox Code Playgroud)
你可以使用readMaybe从Text.Read,并得到一个Maybe Int相反:
import Text.Read
tryParse :: String -> Maybe Int
tryParse = readMaybe
Run Code Online (Sandbox Code Playgroud)