Skip to content

Commit

Permalink
Add oneOf1 and oneOfMap1 to Data.Semigroup.Foldable
Browse files Browse the repository at this point in the history
  • Loading branch information
kl0tl committed Dec 13, 2020
1 parent 8413e6d commit 3c8fd65
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/Data/Semigroup/Foldable.purs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ module Data.Semigroup.Foldable
, traverse1_
, for1_
, sequence1_
, oneOf1
, oneOfMap1
, foldMap1Default
, fold1Default
, fold1DefaultR
Expand All @@ -23,7 +25,9 @@ module Data.Semigroup.Foldable

import Prelude

import Control.Alt (class Alt, alt)
import Data.Foldable (class Foldable)
import Data.Monoid.Alternate (Alternate(..))
import Data.Monoid.Dual (Dual(..))
import Data.Monoid.Multiplicative (Multiplicative(..))
import Data.Newtype (ala, alaF)
Expand Down Expand Up @@ -117,6 +121,14 @@ for1_ = flip traverse1_
sequence1_ :: forall t f a. Foldable1 t => Apply f => t (f a) -> f Unit
sequence1_ = traverse1_ identity

-- | Combines a non empty collection of elements using the `Alt` operation.
oneOf1 :: forall f g a. Foldable1 f => Alt g => f (g a) -> g a
oneOf1 = foldr1 alt

-- | Folds a non empty structure into some `Alt`.
oneOfMap1 :: forall f g a b. Foldable1 f => Alt g => (a -> g b) -> f a -> g b
oneOfMap1 = alaF Alternate foldMap1

maximum :: forall f a. Ord a => Foldable1 f => f a -> a
maximum = ala Max foldMap1

Expand Down
9 changes: 8 additions & 1 deletion test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import Data.Int (toNumber, pow)
import Data.Maybe (Maybe(..))
import Data.Monoid.Additive (Additive(..))
import Data.Newtype (unwrap)
import Data.Semigroup.Foldable (class Foldable1, foldr1, foldl1, fold1Default, foldr1Default, foldl1Default)
import Data.Semigroup.Foldable (class Foldable1, foldr1, foldl1, fold1Default, foldr1Default, foldl1Default, oneOf1, oneOfMap1)
import Data.Semigroup.Foldable as Foldable1
import Data.Traversable (class Traversable, sequenceDefault, traverse, sequence, traverseDefault)
import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex)
Expand Down Expand Up @@ -213,6 +213,13 @@ main = do
(maybeMkNEArray (negate <<< toNumber <$> arrayFrom1UpTo 10)))
== Just (-1.0)

log "Test oneOf1"
assert $ Just "a" == (maybeMkNEArray [Nothing, Just "a", Just "b"] >>= oneOf1)

log "Test oneOfMap1" *> do
let pred n = if n >= 5 then Just n else Nothing
assert $ Just 5 == (maybeMkNEArray [1, 5, 10, 20] >>= oneOfMap1 pred)

log "All done!"


Expand Down

0 comments on commit 3c8fd65

Please sign in to comment.