Skip to content
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

Implement foldMap1 for arrays in JavaScript to fuse mapping and folding #202

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
13 changes: 13 additions & 0 deletions src/Data/Array/NonEmpty/Internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ exports.foldl1Impl = function (f) {
};
};

exports.foldMap1Impl = function (append) {
return function (f) {
return function (xs) {
var acc = f(xs[0]);
var len = xs.length;
for (var i = 1; i < len; i++) {
acc = append(acc)(f(xs[i]));
}
return acc;
};
};
};

exports.traverse1Impl = function () {
function Cont(fn) {
this.fn = fn;
Expand Down
6 changes: 4 additions & 2 deletions src/Data/Array/NonEmpty/Internal.purs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import Data.Foldable (class Foldable)
import Data.FoldableWithIndex (class FoldableWithIndex)
import Data.FunctorWithIndex (class FunctorWithIndex)
import Data.Ord (class Ord1)
import Data.Semigroup.Foldable (class Foldable1, foldMap1DefaultL)
import Data.Semigroup.Foldable (class Foldable1)
import Data.Semigroup.Traversable (class Traversable1, sequence1Default)
import Data.Traversable (class Traversable)
import Data.TraversableWithIndex (class TraversableWithIndex)
Expand Down Expand Up @@ -48,7 +48,7 @@ derive newtype instance foldableNonEmptyArray :: Foldable NonEmptyArray
derive newtype instance foldableWithIndexNonEmptyArray :: FoldableWithIndex Int NonEmptyArray

instance foldable1NonEmptyArray :: Foldable1 NonEmptyArray where
foldMap1 = foldMap1DefaultL
foldMap1 = foldMap1Impl (<>)
foldr1 = foldr1Impl
foldl1 = foldl1Impl

Expand All @@ -74,6 +74,8 @@ derive newtype instance altNonEmptyArray :: Alt NonEmptyArray
foreign import foldr1Impl :: forall a. (a -> a -> a) -> NonEmptyArray a -> a
foreign import foldl1Impl :: forall a. (a -> a -> a) -> NonEmptyArray a -> a

foreign import foldMap1Impl :: forall a m. (m -> m -> m) -> (a -> m) -> NonEmptyArray a -> m

foreign import traverse1Impl
:: forall m a b
. (forall a' b'. (m (a' -> b') -> m a' -> m b'))
Expand Down