Haskell read 例外処理

read 関数の Exception をどう扱ってよいか迷ってたところ、クールなわざを見つけた。
How to catch a no parse exception from the read function in Haskell? - Stack Overflow

maybeRead = fmap fst . listToMaybe . reads

関数の重ね方とか勉強になるなぁ。
# GHC 7.6 には readMaybe という関数が追加される予定なので、リリース後は必要ないかも。

早速、試してみる。

{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Maybe

maybeRead = fmap fst . listToMaybe . reads

実行例

*Main> maybeRead "3.14" :: Maybe Double
Just 3.14
*Main> maybeRead "abc" :: Maybe Double
Nothing
*Main> maybeRead "3d-4" :: Maybe Double
Just 3.0

3番目の実行例が思わしくないので改良。

{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Maybe

maybeRead s = do
     case (listToMaybe . reads) s of
        Just (x, "") -> Just x
        _ -> Nothing

実行例

*Main> maybeRead "3.14" :: Maybe Double
Just 3.14
*Main> maybeRead "abc" :: Maybe Double
Nothing
*Main> maybeRead "3d-4" :: Maybe Double
Nothing