Skip to content

Fix Foldable1 (NonEmpty f) instance #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Data/NonEmpty.purs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import Data.Eq (class Eq1)
import Data.Foldable (class Foldable, foldl, foldr, foldMap)
import Data.FoldableWithIndex (class FoldableWithIndex, foldMapWithIndex, foldlWithIndex, foldrWithIndex)
import Data.FunctorWithIndex (class FunctorWithIndex, mapWithIndex)
import Data.Maybe (Maybe(..))
import Data.Maybe (Maybe(..), maybe)
import Data.Ord (class Ord1)
import Data.Semigroup.Foldable (class Foldable1, foldMap1)
import Data.Traversable (class Traversable, traverse, sequence)
Expand Down Expand Up @@ -107,6 +107,8 @@ instance traversableWithIndexNonEmpty
instance foldable1NonEmpty :: Foldable f => Foldable1 (NonEmpty f) where
fold1 = foldMap1 identity
foldMap1 f (a :| fa) = foldl (\s a1 -> s <> f a1) (f a) fa
foldr1 f (a :| fa) = maybe a (f a) $ foldr (\a1 -> Just <<< maybe a1 (f a1)) Nothing fa
foldl1 = foldl1

instance unfoldable1NonEmpty :: Unfoldable f => Unfoldable1 (NonEmpty f) where
unfoldr1 f b = uncurry (:|) $ unfoldr (map f) <$> f b
5 changes: 3 additions & 2 deletions test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Prelude
import Data.Foldable (fold, foldl)
import Data.Maybe (Maybe(..))
import Data.NonEmpty (NonEmpty, (:|), foldl1, oneOf, head, tail, singleton)
import Data.Semigroup.Foldable (fold1)
import Data.Semigroup.Foldable (fold1, foldr1)
import Data.Unfoldable1 as U1
import Effect (Effect)
import Test.Assert (assert)
Expand All @@ -19,7 +19,8 @@ main :: Effect Unit
main = do
assert $ singleton 0 == 0 :| []
assert $ 0 :| Nothing /= 0 :| Just 1
assert $ foldl1 (+) (1 :| [2, 3]) == 6
assert $ foldl1 (\l r -> "(" <> l <> r <> ")") ("a" :| ["b", "c", "d"]) == "(((ab)c)d)"
assert $ foldr1 (\l r -> "(" <> l <> r <> ")") ("a" :| ["b", "c", "d"]) == "(a(b(cd)))"
assert $ foldl (+) 0 (1 :| [2, 3]) == 6
assert $ fold1 ("Hello" :| [" ", "World"]) == "Hello World"
assert $ fold ("Hello" :| [" ", "World"]) == "Hello World"
Expand Down