Haskell/Yesod - Butchering use of MaybeT The following is some code that is used to provide the frontend with certain parameters when rendering a form. The parameters are conditional based around what data is being changed, getNewSaleFormOptions provides a way of quering these options using a GET request and url params (ie /sales/new?dealership=11&amp;vehicle=2), and another getEditSaleFormOptions when returning to edit, but through the entity id, ie /sales/1 (this will pull necessary data, dealership, vehicle, from Sale 1).

I've tried to use MaybeT here to simplify a lot of the calls that return m (Maybe a), though its possible i'm not using it in the most efficient way. There are lots of MaybeT and runMaybeT calls (though this might be okay), and a few spots where there is duplicated code... I'm just not sure of the best way to eliminate them.

{-# LANGUAGE GADTs            #-}
{-# LANGUAGE FlexibleContexts #-}

module Forms.SaleForm
  ( SaleFormOptions(..)
  , getNewSaleFormOptions
  , getEditSaleFormOptions
  ) where

import           Control.Monad (join)
import           Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
import qualified Data.Aeson as Aeson
import           Data.Aeson ((.=), ToJSON)
import qualified Data.Maybe as M
import           Data.Text (Text)
import           Database.Esqueleto (SqlPersistT, get)
import           Yesod.Core (MonadHandler(..), PathPiece(..))

data SaleFormOptions = SaleFormOptions
  { saleFormOptionsCampaigns :: Maybe MarketingCampaigns
  , saleFormOptionsDiscountElegible :: Bool
  }

instance ToJSON SaleFormOptions where
  toJSON SaleFormOptions{..} =
    Aeson.object [ "campaigns" .= saleFormOptionsCampaigns
                 , "discount_elegible" .= saleFormOptionsDiscountElegible
                 ]

getNewSaleFormOptions :: MonadHandler m =&gt; Key User -&gt; SqlPersistT m SaleFormOptions
getNewSaleFormOptions userKey = NewTenancyFormFields &lt;$&gt; campaigns &lt;*&gt; discountElegible
 where
    campaigns =
      runMaybeT (MaybeT . fetchCampaigns userKey =&lt;&lt; lookupIdGetParamM "dealership")

    discountElegible =
      M.fromMaybe False &lt;$&gt; runMaybeT (MaybeT . fmap Just . isDiscountElegible =&lt;&lt; lookupIdGetParamM "vehicle")

getEditSaleFormOptions
  :: MonadHandler m
  =&gt; Key User
  -&gt; Key Sale
  -&gt; SqlPersistT m SaleFormOptions
getEditSaleFormOptions userKey saleKey = do
  sale &lt;- get saleKey
  EditTenancyTenantFormFields &lt;$&gt; fmap join (mapM (fetchCampaigns userKey) (saleDealership &lt;$&gt; sale))
                              &lt;*&gt; (M.fromMaybe False &lt;$&gt; mapM isDiscountElegible (saleVehicle &lt;$&gt; sale))

fetchCampaigns :: MonadHandler m =&gt; Key User -&gt; Key Dealership -&gt; SqlPersistT m (Maybe MarketingCampaigns)
fetchCampaigns userKey dealershipKey = do
  enabled &lt;- campaignsEnabled userKey dealershipKey
  if enabled then Just &lt;$&gt; getCampaigns dealershipKey
             else return Nothing

isDiscountElegible :: MonadHandler m =&gt; Key Vehicle -&gt; SqlPersistT m Bool
isDiscountElegible vehicleKey = M.fromMaybe False &lt;$&gt; runMaybeT checkElegible
  where
    checkElegible = do
      vehicle &lt;- MaybeT (get vehicleKey)
      vehicleHasDiscount &lt;$&gt; (MaybeT . get $ vehicleManufacturer vehicle)
                         &lt;*&gt; pure vehicle

lookupIdGetParamM
  :: (PathPiece (Key a), MonadHandler m)
  =&gt; Text
  -&gt; MaybeT m (Key a)
lookupIdGetParamM = MaybeT . lookupIdGetParam


And this is the code for lookupIdGetParam:

lookupIdGetParam :: (PathPiece (Key a), MonadHandler m) =&gt; Text -&gt; m (Maybe (Key a))
lookupIdGetParam name = do
  mraw &lt;- lookupGetParam name
  case mraw of
    Nothing  -&gt; return Nothing
    Just raw -&gt; return (fromPathPiece raw)
I'd suggest these points to simplify your code:


Make everything that returns Maybe something into MaybeT, and as close to the origin as possible. This will make composition of your functions much easier. For example:

lookupIdGetParam :: (PathPiece (Key a), MonadHandler m) =&gt; Text -&gt; MaybeT m (Key a)
lookupIdGetParam name = liftM fromPathPiece (MaybeT $ lookupGetParam name)


Notice using MaybeT just at lookupGetParam, then we don't need to duplicate MaybeT's functionality in the case expression.

This also helps you to avoid complicated code with two nested monads (such as SqlPersistT m (Maybe MarketingCampaigns)) and then complex and hard-to-read operations on them like fmap join (mapM ...).
MaybeT . fmap Just is equivalent to lift.
Whenever applicable, use functions from MonadPlus. Not just mzero (which is here equivalent to Nothing) and mplus, there are also some other very useful ones such as mfilter or guard. Like in:

fetchCampaigns :: MonadHandler m =&gt; Key User -&gt; Key Dealership -&gt; MaybeT (SqlPersistT m) MarketingCampaigns
fetchCampaigns userKey dealershipKey = do
  enabled &lt;- lift $ campaignsEnabled userKey dealershipKey
  guard enabled
  lift $ getCampaigns dealershipKey

Something to try out, I'm not sure if this will help you, but it might: Instead of a function that returns a Bool in a monad, return MaybeT MyMonad () such that original False corresponds to a failure in MaybeT and True to a () value. To be specific, instead of isDiscountEligible, you could have

checkDiscountElegible :: MonadHandler m =&gt; Key Vehicle -&gt; MaybeT (SqlPersistT m) ()
checkDiscountElegible vehicleKey = do
  vehicle &lt;- MaybeT (get vehicleKey)
  hasDiscount &lt;- vehicleHasDiscount &lt;$&gt; (MaybeT . get $ vehicleManufacturer vehicle)
                                    &lt;*&gt; pure vehicle
  guard hasDiscount


The idea is that this will make these functions composable with the other MaybeT ... ones, and avoid the tedious M.fromMaybe False &lt;$&gt; runMaybeT.

In other words, in MaybeT m Bool there are two failure modes: One failing within the monad, and another returning False. If you know from the beginning that they're both equivalent, just collapse them instead of keeping the distinction.


Disclaimer: I haven't tried to compile any of the above, so there might be syntax errors, but hopefully the meaning is clear.