'Case matching on read function in Haskell [duplicate]
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Francis King |
