I am wondering how to check success or failure (resulting in Prelude.read: no parse) of the read function in Haskell. In my case i run "(read formatted :: Int)" in code formatting a record structure, where the fields might be a single Int in String form but might also contain something else. I want to apply my function only to the fields where the read returns an Int. Thanks.
You should consider readMaybe from Text.Read. Once the value is returned within the Maybe monad then you can use case to decide what to do.
import Text.Read
add1 :: String -> Maybe Int
add1 str = case intval of
Just x -> Just (x + 1)
Nothing -> Nothing
where
intval = readMaybe str
main = do
print $ add1 "7"
print $ add1 "7.0"
If you want to be more adventurous, now that the data is in the Maybe monad, we can treat the Maybe as a functor and use applicative functors to process them.