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 ?
You can’t; you’ll have to manipulate
readValue‘s result while in theIOmonad.The
returnfunction takes the result of theinsertand puts it back neatly into theIOmonad. This code exemplifies a general pattern for manipulating values with ordinary functions insideIO.No; consider what that would mean.
IO Stringmeans 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 theIOmonad withMap-typed result.