{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE UndecidableInstances #-}
module Control.Eff.NdetEff where
import Control.Eff.Internal
import Data.OpenUnion
import Control.Applicative
import Control.Monad
import Control.Monad.Base
import Control.Monad.Trans.Control
import Data.Foldable (foldl')
data NdetEff a where
MZero :: NdetEff a
MPlus :: NdetEff Bool
instance Member NdetEff r => Alternative (Eff r) where
empty = mzero
(<|>) = mplus
instance Member NdetEff r => MonadPlus (Eff r) where
mzero = send MZero
mplus m1 m2 = send MPlus >>= \x -> if x then m1 else m2
instance ( MonadBase m m
, SetMember Lift (Lift m) r
, MonadBaseControl m (Eff r)
) => MonadBaseControl m (Eff (NdetEff ': r)) where
type StM (Eff (NdetEff ': r)) a = StM (Eff r) [a]
liftBaseWith f = raise $ liftBaseWith $ \runInBase ->
f (runInBase . makeChoiceLst)
restoreM x = do lst :: [a] <- raise (restoreM x)
foldl' (\r a -> r <|> pure a) mzero lst
makeChoiceA0 :: Alternative f => Eff (NdetEff ': r) a -> Eff r (f a)
makeChoiceA0 = handle_relay (return . pure) $ \m k -> case m of
MZero -> return empty
MPlus -> liftM2 (<|>) (k True) (k False)
makeChoiceA :: Alternative f => Eff (NdetEff ': r) a -> Eff r (f a)
makeChoiceA m = loop [] m
where
loop [] (Val x) = return (pure x)
loop (h:t) (Val x) = loop t h >>= \r -> return (pure x <|> r)
loop jq (E u q) = case decomp u of
Right MZero -> case jq of
[] -> return empty
(h:t) -> loop t h
Right MPlus -> loop (q ^$ False : jq) (q ^$ True)
Left u0 -> E u0 (singleK (\x -> loop jq (q ^$ x)))
makeChoiceLst :: Eff (NdetEff ': r) a -> Eff r [a]
makeChoiceLst = makeChoiceA
msplit :: Member NdetEff r => Eff r a -> Eff r (Maybe (a, Eff r a))
msplit = loop []
where
loop [] (Val x) = return (Just (x,mzero))
loop jq (Val x) = return (Just (x, msum jq))
loop jq (E u q) = case prj u of
Just MZero -> case jq of
[] -> return Nothing
(j:jqT) -> loop jqT j
Just MPlus -> loop ((q ^$ False):jq) (q ^$ True)
_ -> E u (qComps q (loop jq))
ifte :: Member NdetEff r => Eff r a -> (a -> Eff r b) -> Eff r b -> Eff r b
ifte t th el = msplit t >>= check
where check Nothing = el
check (Just (sg1,sg2)) = (th sg1) `mplus` (sg2 >>= th)
once :: Member NdetEff r => Eff r a -> Eff r a
once m = msplit m >>= check
where check Nothing = mzero
check (Just (sg1,_)) = return sg1