Skip to content

Commit

Permalink
Reimplement Foldable1 in terms of NonEmptyArray, reducing JS code foo…
Browse files Browse the repository at this point in the history
…tprint
  • Loading branch information
JamieBallingall committed Oct 9, 2022
1 parent 7a8775e commit b867e53
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 30 deletions.
22 changes: 0 additions & 22 deletions src/Data/Array/AtLeast.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,3 @@ export const offsetWithImpl = function (offset) {
}
}
}

export const foldr1Impl = function (f) {
return function (xs) {
let len = xs.length;
let acc = xs[len - 1];
for (let i = len - 2; i >= 0; i--) {
acc = f(xs[i])(acc);
}
return acc;
}
}

export const foldl1Impl = function (f) {
return function (xs) {
let acc = xs[0];
let len = xs.length;
for (let i = 1; i < len; i++) {
acc = f(acc)(xs[i]);
}
return acc;
}
}
14 changes: 6 additions & 8 deletions src/Data/Array/AtLeast.purs
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,12 @@ import Data.FastVect.FastVect as FV
import Data.Foldable (class Foldable)
import Data.FoldableWithIndex (class FoldableWithIndex)
import Data.FunctorWithIndex (class FunctorWithIndex)
import Data.Int.AtLeast (IntAL, fromInt', toInt)
import Data.Int.AtLeast (fromLength) as IntAL
import Data.Int.AtLeast (IntAL, fromInt', toInt)
import Data.Maybe (Maybe(Nothing, Just), fromJust)
import Data.Reflectable (class Reflectable, reflectType)
import Data.Semigroup.Foldable (class Foldable1, foldMap1DefaultL)
import Data.Semigroup.Foldable (class Foldable1)
import Data.Semigroup.Foldable as Foldable1
import Data.Traversable (class Traversable)
import Data.TraversableWithIndex (class TraversableWithIndex)
import Partial.Unsafe (unsafePartial)
Expand Down Expand Up @@ -107,12 +108,9 @@ derive newtype instance Traversable (ArrayAL n)
derive newtype instance TraversableWithIndex Int (ArrayAL n)

instance Compare n 0 GT => Foldable1 (ArrayAL n) where
foldMap1 = foldMap1DefaultL
foldr1 = foldr1Impl
foldl1 = foldl1Impl

foreign import foldr1Impl :: forall n a. (a -> a -> a) -> ArrayAL n a -> a
foreign import foldl1Impl :: forall n a. (a -> a -> a) -> ArrayAL n a -> a
foldMap1 = Foldable1.foldMap1DefaultL
foldr1 f xs = Foldable1.foldr1 f $ toNonEmptyArray xs
foldl1 f xs = Foldable1.foldl1 f $ toNonEmptyArray xs

instance Apply (ArrayAL n) where
apply (ArrayAL fab) (ArrayAL a) = ArrayAL (Array.zipWith ($) fab a)
Expand Down

0 comments on commit b867e53

Please sign in to comment.