Skip to content

Commit 65bfd30

Browse files
authored
Merge pull request #62 from purescript/length
length for Foldables
2 parents 70bebec + 0f0c3eb commit 65bfd30

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
@@ -22,6 +22,7 @@ module Data.Foldable
2222
, minimum
2323
, minimumBy
2424
, null
25+
, length
2526
) where
2627

2728
import Prelude
@@ -313,3 +314,9 @@ minimumBy cmp = foldl min' Nothing
313314
-- | is no general way to do better.
314315
null :: forall a f. Foldable f => f a -> Boolean
315316
null = foldr (\_ _ -> false) true
317+
318+
-- | Returns the size/length of a finite structure.
319+
-- | Optimized for structures that are similar to cons-lists, because there
320+
-- | is no general way to do better.
321+
length :: forall a b f. Foldable f => Semiring b => f a -> b
322+
length = foldl (\c _ -> add one c) zero

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, null)
11+
import Data.Foldable (class Foldable, foldl, foldr, foldMap, foldrDefault, foldlDefault, foldMapDefaultR, foldMapDefaultL, minimumBy, minimum, maximumBy, maximum, find, findMap, length, null)
1212
import Data.Function (on)
1313
import Data.Int (toNumber)
1414
import Data.Maybe (Maybe(..))
@@ -110,6 +110,13 @@ main = do
110110
assert $ null [0] == false
111111
assert $ null [0,1] == false
112112

113+
log "Test length"
114+
assert $ length Nothing == 0
115+
assert $ length (Just 1) == 1
116+
assert $ length [] == 0
117+
assert $ length [1] == 1
118+
assert $ length [1, 2] == 2
119+
113120
log "All done!"
114121

115122

0 commit comments

Comments
 (0)