tr88
tr88

Reputation: 57

haskell - String where integer is needed

I have the following code

data Ops = Sum Integer | Div Integer | None deriving (Read)

main = do
    ans <- getLine
print $ case read ans of
    Sum n -> sum n
    Div n -> div n

I want to display an error message to the user for a wrong input

Nothing -> "Error"

I understand that I cannot stick in a string here, so how can I possibly implement the error condition

Upvotes: 1

Views: 118

Answers (2)

ErikR
ErikR

Reputation: 52049

If you can't use a module like Text.Read here is how to define readMaybe in terms of just Prelude functions:

data Foo = Sum Int Int | Div Int Int deriving (Show,Read)

readMaybe str =
  case reads str of
    [] -> Nothing
    ((a,_):_) -> Just a

main = do
  str <- getLine
  case readMaybe str of
    Nothing         -> putStrLn "bad input"
    Just (Sum a b)  -> print $ a + b
    Just (Div a b)  -> print $ div a b

Upvotes: 0

bheklilr
bheklilr

Reputation: 54068

A better choice would be to use readMaybe from Text.Read:

import Text.Read (readMaybe)

data Ops
    = Sum Integer
    | Div Integer
    | None
    deriving (Eq, Show, Read)

main :: IO ()
main = do
    ans <- getLine
    case readMaybe ans of
        Nothing -> putStrLn "Error"
        Just x  -> print $ handleInput x
    where
        handleInput (Sum n) = sum n
        handleInput (Div n) = div n

This lets you separate your error handling from how you handle the input, pulling that out into a pure function away from IO

Upvotes: 4

Related Questions