在Haskell中实现FSharp的Int32.TryParse

时间:2014-10-11 15:53:25

标签: haskell f#

我喜欢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的七行?!有更短的方式吗?

...谢谢

2 个答案:

答案 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