Skip to content

Commit ced1fb8

Browse files
committed
null for Foldables
adapted from Haskell's null in Data.Foldable
1 parent 11db59e commit ced1fb8

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/Data/Foldable.purs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ module Data.Foldable
2121
, maximumBy
2222
, minimum
2323
, minimumBy
24+
, null
2425
) where
2526

2627
import Prelude
@@ -302,3 +303,9 @@ minimumBy cmp = foldl min' Nothing
302303
where
303304
min' Nothing x = Just x
304305
min' (Just x) y = Just (if cmp x y == LT then x else y)
306+
307+
-- | Test whether the structure is empty.
308+
-- | Optimized for structures that are similar to cons-lists, because there
309+
-- | is no general way to do better.
310+
null :: forall a f. Foldable f => f a -> Boolean
311+
null = foldr (\_ _ -> false) true

test/Main.purs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Control.Monad.Eff.Console (CONSOLE, log)
88
import Data.Bifoldable (class Bifoldable, bifoldl, bifoldr, bifoldMap, bifoldrDefault, bifoldlDefault, bifoldMapDefaultR, bifoldMapDefaultL)
99
import Data.Bifunctor (class Bifunctor, bimap)
1010
import Data.Bitraversable (class Bitraversable, bisequenceDefault, bitraverse, bisequence, bitraverseDefault)
11-
import Data.Foldable (class Foldable, foldl, foldr, foldMap, foldrDefault, foldlDefault, foldMapDefaultR, foldMapDefaultL, minimumBy, minimum, maximumBy, maximum, find, findMap)
11+
import Data.Foldable (class Foldable, foldl, foldr, foldMap, foldrDefault, foldlDefault, foldMapDefaultR, foldMapDefaultL, minimumBy, minimum, maximumBy, maximum, find, findMap, null)
1212
import Data.Function (on)
1313
import Data.Int (toNumber)
1414
import Data.Maybe (Maybe(..))
@@ -103,6 +103,13 @@ main = do
103103
(map (negate <<< toNumber) (arrayFrom1UpTo 10))
104104
== Just (-1.0)
105105

106+
log "Test null"
107+
assert $ null Nothing == true
108+
assert $ null (Just 1) == false
109+
assert $ null [] == true
110+
assert $ null [0] == false
111+
assert $ null [0,1] == false
112+
106113
log "All done!"
107114

108115

0 commit comments

Comments
 (0)