Skip to content

Commit 6e84c1d

Browse files
committed
Add oneOf1 and oneOfMap1 to Data.Semigroup.Foldable
1 parent be73dca commit 6e84c1d

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/Data/Semigroup/Foldable.purs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ module Data.Semigroup.Foldable
77
, traverse1_
88
, for1_
99
, sequence1_
10+
, oneOf1
11+
, oneOfMap1
1012
, foldMap1Default
1113
, fold1Default
1214
, fold1DefaultR
@@ -21,7 +23,9 @@ module Data.Semigroup.Foldable
2123

2224
import Prelude
2325

26+
import Control.Alt (class Alt, alt)
2427
import Data.Foldable (class Foldable)
28+
import Data.Monoid.Alternate (Alternate(..))
2529
import Data.Monoid.Dual (Dual(..))
2630
import Data.Monoid.Multiplicative (Multiplicative(..))
2731
import Data.Newtype (ala, alaF)
@@ -115,6 +119,14 @@ for1_ = flip traverse1_
115119
sequence1_ :: forall t f a. Foldable1 t => Apply f => t (f a) -> f Unit
116120
sequence1_ = traverse1_ identity
117121

122+
-- | Combines a non empty collection of elements using the `Alt` operation.
123+
oneOf1 :: forall f g a. Foldable1 f => Alt g => f (g a) -> g a
124+
oneOf1 = foldr1 alt
125+
126+
-- | Folds a non empty structure into some `Alt`.
127+
oneOfMap1 :: forall f g a b. Foldable1 f => Alt g => (a -> g b) -> f a -> g b
128+
oneOfMap1 = alaF Alternate foldMap1
129+
118130
maximum :: forall f a. Ord a => Foldable1 f => f a -> a
119131
maximum = ala Max foldMap1
120132

test/Main.purs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import Data.Int (toNumber, pow)
1313
import Data.Maybe (Maybe(..))
1414
import Data.Monoid.Additive (Additive(..))
1515
import Data.Newtype (unwrap)
16-
import Data.Semigroup.Foldable (class Foldable1, foldr1, foldl1, fold1Default, foldr1Default, foldl1Default)
16+
import Data.Semigroup.Foldable (class Foldable1, foldr1, foldl1, fold1Default, foldr1Default, foldl1Default, oneOf1, oneOfMap1)
1717
import Data.Traversable (class Traversable, sequenceDefault, traverse, sequence, traverseDefault)
1818
import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex)
1919
import Effect (Effect, foreachE)
@@ -200,6 +200,13 @@ main = do
200200
assert $ "(a(b(cd)))" == foldMap (foldr1 (\x y -> "(" <> x <> y <> ")")) (maybeMkNEArray ["a", "b", "c", "d"])
201201
assert $ "(((ab)c)d)" == foldMap (foldl1 (\x y -> "(" <> x <> y <> ")")) (maybeMkNEArray ["a", "b", "c", "d"])
202202

203+
log "Test oneOf1"
204+
assert $ Just "a" == (maybeMkNEArray [Nothing, Just "a", Just "b"] >>= oneOf1)
205+
206+
log "Test oneOfMap1" *> do
207+
let pred n = if n >= 5 then Just n else Nothing
208+
assert $ Just 5 == (maybeMkNEArray [1, 5, 10, 20] >>= oneOfMap1 pred)
209+
203210
log "All done!"
204211

205212

0 commit comments

Comments
 (0)