data Union = F Float | I Int | S String
getUnionFromString :: String -> Union
getUnionFromString str =
case (readMaybe str :: Maybe Int) of
Just i -> I i
Nothing ->
case (readMaybe str :: Maybe Float) of
Just f -> F f
Nothing -> S str
getStr (F f) = "Float " ++ show f
getStr (I i) = "Int " ++ show i
getStr (S s) = "String " ++ s
main = do
str <- getLine
putStrLn $ getStr (getUnionFromString str)
I want to make a function that transforms string to union type(Float | Int | String). So I used readMaybe to find out type of a string. And then, using case-of to handle Just and Nothing branch. I think it's not able to cope this situation with Monad behavior of Maybe, because I don't want to stop computation when Nothing got out, I want to handle Nothing case. Is there better way to write getUnionFromString function?