Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determining the correct type of exceptions

Tags:

haskell

monads

(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
like image 860
Paul Nathan Avatar asked Aug 02 '11 21:08

Paul Nathan


1 Answers

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.

like image 175
sepp2k Avatar answered Sep 28 '22 13:09

sepp2k