Skip to content

Commit 4c94d02

Browse files
authored
Fix the Semigroup instance for Foreign.Object.Object (#19)
The Semigroup instance for Foreign.Object.Object currently appends values from the right to values from the left: `singleton k a <> singleton k b` is equivalent to `singleton k (b <> a)` and not to `singleton k (a <> b)` as expected.
1 parent f471d8a commit 4c94d02

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/Foreign/Object.purs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ mapWithKey :: forall a b. (String -> a -> b) -> Object a -> Object b
273273
mapWithKey f m = runFn2 _mapWithKey m f
274274

275275
instance semigroupObject :: (Semigroup a) => Semigroup (Object a) where
276-
append m1 m2 = mutate (\s1 -> foldM (\s2 k v2 -> OST.poke k (runFn4 _lookup v2 (\v1 -> v1 <> v2) k m2) s2) s1 m1) m2
276+
append m1 m2 = mutate (\s1 -> foldM (\s2 k v1 -> OST.poke k (runFn4 _lookup v1 (\v2 -> v1 <> v2) k m2) s2) s1 m1) m2
277277

278278
instance monoidObject :: (Semigroup a) => Monoid (Object a) where
279279
mempty = empty

test/Test/Foreign/Object.purs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@ import Data.List as L
1111
import Data.List.NonEmpty as NEL
1212
import Data.Maybe (Maybe(..))
1313
import Data.NonEmpty ((:|))
14+
import Data.Semigroup.First (First(..))
15+
import Data.Semigroup.Last (Last(..))
1416
import Data.Traversable (sequence, traverse)
1517
import Data.TraversableWithIndex (traverseWithIndex)
1618
import Data.Tuple (Tuple(..), fst, snd, uncurry)
1719
import Effect (Effect)
1820
import Effect.Console (log)
19-
import Foreign.Object (Object)
2021
import Foreign.Object as O
2122
import Foreign.Object.Gen (genForeignObject)
2223
import Partial.Unsafe (unsafePartial)
@@ -257,3 +258,13 @@ objectTests = do
257258
{ expected: entries
258259
, actual: O.size (O.fromFoldable (map (\x -> Tuple (show x) x) (A.range 1 entries)))
259260
}
261+
262+
log "Semigroup instance"
263+
assertEqual
264+
{ expected: O.singleton "a" (First 1)
265+
, actual: O.singleton "a" (First 1) <> O.singleton "a" (First 2)
266+
}
267+
assertEqual
268+
{ expected: O.singleton "a" (Last 2)
269+
, actual: O.singleton "a" (Last 1) <> O.singleton "a" (Last 2)
270+
}

0 commit comments

Comments
 (0)