Int32.TryParse FSharp Implementation in Haskell
I liked the Int32.TryParse function in F # and wanted to make my own in 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
Seven lines to parse Int ?! Is there a shorter way?
Thank...
+3
Dragno
source
to share
2 answers
You can use reads
:
tryParse :: String -> (Bool, Int)
tryParse s =
case reads s of
[(i, "")] -> (True, i)
_ -> (False, 0)
it would be more idomatic to return a Maybe Int
instead:
tryParse :: String -> Maybe Int
tryParse s =
case reads s of
[(i, "")] -> Just i
_ -> Nothing
+9
Lee
source
to share
You can use readMaybe
from Text.Read
and get instead Maybe Int
:
import Text.Read
tryParse :: String -> Maybe Int
tryParse = readMaybe
+9
Vektorweg
source
to share