在haskell中处理IO值
我正在 Haskell 中编写一个带有 IO 操作的小程序 正如
module StackQuestion where
import Data.Map (Map, insert, fromList)
type Name = String
type Value = String
readValue :: Name -> IO String
readValue name = do putStrLn name
value <- getLine
return value
addPair :: Name -> Value -> Map Name Value -> Map Name Value
addPair = insert
names = map show [1..5]
values = map (\char -> [char]) ['a'..'d']
initialMap = fromList (zip names values)
您所看到的,我有一些带有值的初始映射,以及向映射添加一对的函数,以及读取值的函数。
如何从 readValue
获取清晰的 String
值并将其传递给另一个函数?
或者我应该将 type Value = String
更改为 type Value = IO String
并使用 map Map String (IO String)
?
如果我有 Map String (IO String)
我该如何处理这个映射,如何根据 IO
容器中的数据获取任何值(也许是某些函数 func :: (a->b) -> IO a -> b
) 例如,有什么方法可以将 IO String
与 clear String
进行比较吗?
如果我有函数func
,我会写
map :: Map String (IO String)
...
func (==) (map ! "key")
What is the Strategy ofworking with IO
values?
I'm writing a small program with IO actions in Haskell
here is
module StackQuestion where
import Data.Map (Map, insert, fromList)
type Name = String
type Value = String
readValue :: Name -> IO String
readValue name = do putStrLn name
value <- getLine
return value
addPair :: Name -> Value -> Map Name Value -> Map Name Value
addPair = insert
names = map show [1..5]
values = map (\char -> [char]) ['a'..'d']
initialMap = fromList (zip names values)
As you can see I have some initial map with values, and function which adds a pair to map, functions which reads a value.
How I can get a clear String
value from readValue
and pass it to another function ?
Or should I change type Value = String
to type Value = IO String
and use map Map String (IO String)
?
And if I have Map String (IO String)
how can i process this map, how I can get any value depening on data in IO
containter (maybe some function func :: (a->b) -> IO a -> b
)
For instance is there any way to compare IO String
with the clear String
?
If I have function func
I would have written
map :: Map String (IO String)
...
func (==) (map ! "key")
What is the strategy of working with IO
values ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能;您必须在
IO
monad 中操作readValue
的结果。return
函数获取insert
的结果并将其整齐地放回到IO
monad 中。此代码举例说明了使用IO
内的普通函数操作值的一般模式。否;考虑一下这意味着什么。
IO String
表示具有String
类型结果的可能副作用 (IO
) 的计算。您会将名称映射到计算。 (这是可能的,但这不是您的意思。)上面显示的示例使用
IO(映射名称值)
来代替;即,IO
monad 中具有Map
类型结果的计算。You can't; you'll have to manipulate
readValue
's result while in theIO
monad.The
return
function takes the result of theinsert
and puts it back neatly into theIO
monad. This code exemplifies a general pattern for manipulating values with ordinary functions insideIO
.No; consider what that would mean.
IO String
means a computation with possible side-effects (IO
) withString
-typed result. You would be mapping names to computations. (That's possible, but it's not what you mean.)The example I've shown above uses
IO (Map Name Value)
instead; i.e., a computation in theIO
monad withMap
-typed result.