在Haskell中实现FSharp的Int32.TryParse

3

我喜欢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个回答

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

2
返回 (Bool, Int) 真的没有意义。F# 中这样做的唯一原因是它是对一个接受可变 int 并返回 bool 的 C# 函数的语法糖。 - Tarmil

9
您可以使用来自Text.Read的readMaybe,并获得一个Maybe Int:
import Text.Read

tryParse :: String -> Maybe Int
tryParse = readMaybe

2
走得好,TryX模式与Maybe太相似了。 - Mephy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接