diff --git a/CHANGELOG.md b/CHANGELOG.md index b667c25..251b5e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Notable changes to this project are documented in this file. The format is based Breaking changes: New features: +- Added semigroup instance (#18 by @jmatsushita) Bugfixes: diff --git a/src/Data/NonEmpty.purs b/src/Data/NonEmpty.purs index 4135c5c..11d6bc8 100644 --- a/src/Data/NonEmpty.purs +++ b/src/Data/NonEmpty.purs @@ -167,3 +167,11 @@ instance foldable1NonEmpty :: Foldable f => Foldable1 (NonEmpty f) where instance unfoldable1NonEmpty :: Unfoldable f => Unfoldable1 (NonEmpty f) where unfoldr1 f b = uncurry (:|) $ unfoldr (map f) <$> f b + +-- | This is a lawful `Semigroup` instance that will behave sensibly for common nonempty +-- | containers like lists and arrays. However, it's not guaranteed that `pure` will behave +-- | sensibly alongside `<>` for all types, as we don't have any laws which govern their behavior. +instance semigroupNonEmpty + :: (Applicative f, Semigroup (f a)) + => Semigroup (NonEmpty f a) where + append (a1 :| f1) (a2 :| f2) = a1 :| (f1 <> pure a2 <> f2) diff --git a/test/Main.purs b/test/Main.purs index acf08e7..14be533 100644 --- a/test/Main.purs +++ b/test/Main.purs @@ -27,3 +27,4 @@ main = do assert $ oneOf (0 :| Nothing) == oneOf (0 :| Just 1) assert $ second (1 :| 2 :| [3, 4]) == 2 assert $ U1.range 0 9 == (0 :| [1, 2, 3, 4, 5, 6, 7, 8, 9]) + assert $ (0 :| [1,2]) <> (3 :| [4,5]) == (0 :| [1, 2, 3, 4, 5])