(Newbie question. :-) )
Suppose you have a sequence of operations (sanity checks on the outside world). If sanity fails, one has to holler.
However, Haskell ifs require both branches be defined. The case of fail
is a monad. However, I'm unsure what the correct type to generate in the else case. The compiler thinks the inferred type is IO a. However, I'm not sure how to create an no-op IO a.
holler msg test =
do
if not test
then
fail msg
else
-- ??? no-op
main :: IO ()
main = do
holler "Go" True
The inferred type is IO a
because fail msg
may return anything (since it does in fact never return). However the else part doesn't actually have to produce an IO a
, it's perfectly fine to make it into something more specific, i.e. IO WhateverYouWant
.
In this case you don't care about the return value, so you should just use IO ()
, i.e. put return ()
in the else
case.
And as it turns out there's already a function called when condition action
in the Control.Monad
module, which does exactly if condition then action else return ()
, so you can just use that one (or its counterpart unless
, which negates the condition saving you the not
) instead of typing out the if
.
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