I have the following code which does the job of changing the configuration file:
mutateConfig :: (Config -> Config) -> IO ()
mutateConfig f = do
!cfg <- readConfig
let !newCfg = f cfg
in writeConfig newCfg
Bang patterns are used to disable lazy evaluation: i need writeConfig to be called after an old configuration was parsed and modified with function f
.
But there is still a problem: imagine that f
gives an error. In this case writeConfig has already opened the file for writing (because it is called first by lazy evaluation) when an error occures, so the configuration file gets lost.
I have tried to compose a simple step-by-step logic from IO monads (in order to prevent the loss of data) like this
!cfg <- readConfig
newCfg <- return $ f cfg
writeConfig newCfg
but this doesn't work either (I kind of expected that).
What would be the correct way to accomplish this goal?
readConfig
uses thereadFile
function, which is (I believe) lazy. So yes, you are right! Which function should I use to read configurations strictly?Config
is fully strict? If it was any errors inf
would be caught before attempting to write the file because of the bang pattern onnewCfg
, even if the file was read lazily (I just tested this). You should still make sure the file is read strictly because it could cause problems when trying to write back to the config file. You can do this with thestrict
package. (but melphomene's temporary and rename is probably a better solution)Config
. I've just fixed this andmutateConfig
is working just I expect it to. Thank you very much for your assistance!