Skip to content

Commit 223584f

Browse files
Martin Bidlingmaierpaf31
authored andcommitted
Fix foldMapDefaultL (#73)
* Fix foldMapDefaultL Previously, ```purescript foldMapDefaultL singleton [1, 2] = [2, 1] ``` This commit fixes this: ```purescript foldMapDefaultL singleton [1, 2] = foldMapDefaultR singleton [1, 2] = [1, 2] ``` * Refactor test to detect foldMapDefaultL bug This refactors the test for the Foldable instance of array and the default implementations of Foldable's functions. In a way, it does not really make sense to test the default implementations of Foldable's functions, because they are part of the rules of the type class. Up to execution speed and memory usage, every valid instance has to satisfy ```purescript foldMap = foldMapDefaultL foldMap = foldMapDefaultR foldl = foldlDefault foldr = foldrDefault ``` and, for any reasonable instance that is also a functor, ```purescript foldMap f = fold <<< map f ``` Testing these properties for some instances that we think are valid should reveal errors in the specification. I've refactored the test so that the equations above can be tested via `foldMap` on any Monoid m, in particular on non-commutative monoids such as `Array a`, which detects the `foldMapDefaultL` bug. * Revert "Refactor test to detect foldMapDefaultL bug" This reverts commit a9d74ce. * Add test for fix in 0fa2889
1 parent 363af1e commit 223584f

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

src/Data/Foldable.purs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ foldMapDefaultL
115115
=> (a -> m)
116116
-> f a
117117
-> m
118-
foldMapDefaultL f = foldl (\acc x -> f x <> acc) mempty
118+
foldMapDefaultL f = foldl (\acc x -> acc <> f x) mempty
119119

120120
instance foldableArray :: Foldable Array where
121121
foldr = foldrArray

test/Main.purs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ main = do
2626
log "Test foldableArray instance"
2727
testFoldableArrayWith 20
2828

29+
assert $ foldMapDefaultL (\x -> [x]) [1, 2] == [1, 2]
30+
2931
log "Test foldableArray instance is stack safe"
3032
testFoldableArrayWith 20000
3133

0 commit comments

Comments
 (0)