-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Define an Alternative module giving implementations in terms of Alter…
…native.
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
module Control.Effect.Alternative | ||
( -- * NonDet effects | ||
module Control.Effect.Choose | ||
, module Control.Effect.Empty | ||
, oneOf | ||
, foldMapA | ||
-- * Re-exports | ||
, Alternative(..) | ||
, guard | ||
) where | ||
|
||
import Control.Applicative (Alternative(..)) | ||
import Control.Effect.Choose hiding ((<|>), many, some) | ||
import Control.Effect.Empty hiding (empty, guard) | ||
import Control.Monad (guard) | ||
import Data.Coerce | ||
import Data.Monoid (Alt(..)) | ||
|
||
-- | Nondeterministically choose an element from a 'Foldable' collection. | ||
-- This can be used to emulate the style of nondeterminism associated with | ||
-- programming in the list monad: | ||
-- @ | ||
-- pythagoreanTriples = do | ||
-- a <- oneOf [1..10] | ||
-- b <- oneOf [1..10] | ||
-- c <- oneOf [1..10] | ||
-- guard (a^2 + b^2 == c^2) | ||
-- pure (a, b, c) | ||
-- @ | ||
oneOf :: (Foldable t, Alternative m) => t a -> m a | ||
oneOf = foldMapA pure | ||
|
||
-- | Map a 'Foldable' collection of values into a nondeterministic computation using the supplied action. | ||
foldMapA :: (Foldable t, Alternative m) => (a -> m b) -> t a -> m b | ||
foldMapA f = getAlt #. foldMap (Alt #. f) | ||
|
||
|
||
-- | Compose a function operationally equivalent to 'id' on the left. | ||
-- | ||
-- cf https://github.com/fused-effects/diffused-effects/pull/1#discussion_r323560758 | ||
(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) | ||
(#.) _ = coerce | ||
{-# INLINE (#.) #-} |