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 ?
How I can get a clear
Stringvalue fromreadValueand pass it to another function?
You can't; you'll have to manipulate readValue's result while in the IO monad.
{- read value for name and store both in map -}
readAndStore :: Name -> Map Name Value -> IO (Map Name Value)
readAndStore name m = do value <- readValue name
return $ insert name value m
The return function takes the result of the insert and puts it back neatly into the IO monad. This code exemplifies a general pattern for manipulating values with ordinary functions inside IO.
Or should I change
type Value = Stringtotype Value = IO String
No; consider what that would mean. IO String means a computation with possible side-effects (IO) with String-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 the IO monad with Map-typed result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With