[Haskell-cafe] tips on using monads

Ryan Ingram ryani.spam at gmail.com
Mon May 18 12:49:21 EDT 2009


On Mon, May 18, 2009 at 3:08 AM, Neil Brown <nccb2 at kent.ac.uk> wrote:
> With ErrorT you can use throwError when you want to break out of the
> block and give back an error, which seems to fit what you were doing.

Of course, now that you are using throwError, you can remove a lot of
the extra indentation:

> insertNote :: NoteRecord -> Connection -> IO ()
> insertNote nr conn = either putStrLn return =<< runErrorT
>  (do -- Check if it exists in the database already.
>      status <- liftIO $ checkPreExistingText nr conn
>      when status $ throwError "Skipping... text exists already."
>      -- Find best fit for all topics and source.
>      -- See type signatures below.
>      bestFitTopics <- liftIO $ fitTopics nr conn
>      bestFitSource <- liftIO $ fitSource nr conn
>      when (any isNothing bestFitTopics) $ throwError "Error... some topic couldn't be matched."
>      when (isNothing bestFitSource) $ throwError "Error.. source couldn't be matched."
>      b <- liftIO $ isUserOkay nr bestFitTopics bestFitSource
>      when (not b) $ throwError "Abort due to user request."
>      -- Create a new NoteRecord with matched
>      -- and validated topics/source.
>      let nrValidated = nr { recordTopics = bestFitTopics, recordSource = bestFitSource }
>      liftIO $ insertRow nrValidated conn
>  )

  -- ryan


More information about the Haskell-Cafe mailing list