How can I use reading a string that is not a double quote?

I am reading the values ​​from the console using readLn.

I would like to write a function:

requestValue :: String -> IO a  
requestValue s = do  
  putStrLn $ "Please enter a new value for " ++ s   
  readLn

Then I could do, for example,

changeAge :: Person -> IO Person
changeAge p = do
    age' <- requestValue "age"
    return $ p { age = age'}

changeName :: Person -> IO Person
changeName p = do
    name' <- requestValue "name"
    return $ p { name = name'}

The problem is that reading the String instance requires the string to be in quotation marks. I do not want to type "Fred"in the console to change the name when I really only want to type Fred.

Is there an easy way to do this while maintaining requestValuepolymorphic?

+5
source share
2 answers

read , - . :

import Control.Arrow (first)

newtype Name = Name { unName :: String }
    deriving (Eq, Ord, Show)

read:

instance Read Name where
    readsPrec n = map (first Name) . readsPrec n . quote
        where quote s = '"' : s ++ ['"'] 

, , .

Person, Name String:

data Person = Person { age :: Int
                     , name :: Name } deriving Show  

:

*Main> changeName (Person 31 (Name "dons"))
Please enter a new value for name
Don
Person {age = 31, name = Name {unName = "Don"}}
+4

getLine, readLn.

+2

All Articles