如何在非双引号的字符串上使用 read ?
我正在使用 readLn 从控制台读取值。
我想编写一个函数:
requestValue :: String -> IO a
requestValue s = do
putStrLn $ "Please enter a new value for " ++ s
readLn
然后我就可以这样做,例如,
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'}
我遇到的问题是 String 的读取实例似乎要求字符串用引号引起来。当我真的只想输入 Fred
时,我不想在控制台中输入 "Fred"
来更改名称。
有没有一种简单的方法可以保持 requestValue 的多态性?
I'm reading values from in from a console using readLn
.
I'd like to write a function:
requestValue :: String -> IO a
requestValue s = do
putStrLn $ "Please enter a new value for " ++ s
readLn
I'd then be able to 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 I have is that the read instance of String seems to require the string to be in quotes. I don't want to have to enter "Fred"
in the console to change name when I really only want to type in Fred
.
Is there an easy way to do this that keeps requestValue
polymorphic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您想要为用户名添加自己的自定义
read
行为,因此执行此操作的方法是实际为读数名称编写一个新实例。为此,我们可以为名称创建一个新类型:并为其编写一个自定义的读取:
这与字符串的读取实例相同,但我们首先引用字符串,读入后。
现在您可以修改
Person
类型以使用Name
而不是String
:并且我们正在做生意:
Since you want to add your own custom
read
behavior for user names, the way to do that is to actually write a new instance for readings names. To do that we can create a new type for names:and write a custom
read
for it:this is the same as the read instance for strings, but we first quote the string, after reading it in.
Now you can modify your
Person
type to useName
instead ofString
:and we're in business:
您需要
getLine
,而不是readLn
。You want
getLine
, notreadLn
.