0248881
0248881

Reputation: 771

How do I convert a string to a list of Maybe Int

How would I go about converting a string like this "13.2..2" to a list like this

[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]

I have had a look at digitToInt but it does not take care of Maybe Int. Is there a way I could maybe modify digitToInt to handle Maybe Int?

Upvotes: 3

Views: 1975

Answers (3)

Michal Charemza
Michal Charemza

Reputation: 27012

If you would like all non digits to be converted to Nothing, you can use guards and fmap

import Data.Char

charToMaybeInt :: Char -> Maybe Int
charToMaybeInt  x 
 | isDigit x = Just $ digitToInt x
 | otherwise = Nothing

main = putStrLn $ show $ fmap charToMaybeInt "13.2..2"

Using guards is, from my non-expert understanding, a bit more idiomatic than using if/else.

Upvotes: 5

Michal Charemza
Michal Charemza

Reputation: 27012

If you're certain the data coming is definitely a digit or . (or are happy with exceptions being thrown if the data is different), you can use pattern matching and fmap

import Data.Char

chatToMaybeInt :: Char -> Maybe Int
chatToMaybeInt '.' = Nothing
chatToMaybeInt  x  = Just $ digitToInt x

main = putStrLn $ show $ fmap chatToMaybeInt "13.2..2"

Upvotes: 1

Chris Martin
Chris Martin

Reputation: 30736

You can use isDigit to test whether digitToInt will succeed.

λ> fmap (\c -> if isDigit c then Just (digitToInt c) else Nothing) "13.2..2" :: [Maybe Int]
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]

We can introduce a new function to clean this up a bit:

digitToIntMay :: Char -> Maybe Int
digitToIntMay c = if isDigit c then Just (digitToInt c) else Nothing

λ> fmap digitToIntMay "13.2..2" :: [Maybe Int]
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]

Upvotes: 7

Related Questions