Skip to content

FoldableWithIndex and TraversableWithIndex instances for Cofree #126

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

Merged
merged 1 commit into from
Sep 5, 2023
Merged
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
20 changes: 20 additions & 0 deletions src/Control/Comonad/Cofree.purs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ import Control.Monad.Free (Free, runFreeM)
import Control.Monad.Rec.Class (class MonadRec)
import Control.Monad.State (State, StateT(..), runState, runStateT, state)
import Data.Eq (class Eq1, eq1)
import Data.FoldableWithIndex (class FoldableWithIndex)
import Data.FunctorWithIndex (class FunctorWithIndex)
import Data.Foldable (class Foldable, foldr, foldl, foldMap)
import Data.Lazy (Lazy, force, defer)
import Data.Ord (class Ord1, compare1)
import Data.Traversable (class Traversable, traverse)
import Data.TraversableWithIndex (class TraversableWithIndex)
import Data.Tuple (Tuple(..), fst, snd)

-- | The `Cofree` `Comonad` for a functor.
Expand Down Expand Up @@ -152,12 +154,30 @@ instance foldableCofree :: Foldable f => Foldable (Cofree f) where
where
go fa = f (head fa) <> (foldMap go (tail fa))

instance foldableWithIndexCofree :: Foldable f => FoldableWithIndex Int (Cofree f) where
foldrWithIndex f = go 0
where
go ix b fa = f ix (head fa) (foldr (flip (go (ix + 1))) b (tail fa))

foldlWithIndex f = go 0
where
go ix b fa = foldl (go (ix + 1)) (f ix b (head fa)) (tail fa)

foldMapWithIndex f = go 0
where
go ix fa = f ix (head fa) <> foldMap (go (ix + 1)) (tail fa)

instance traversableCofree :: Traversable f => Traversable (Cofree f) where
sequence = traverse identity
traverse f = loop
where
loop ta = mkCofree <$> f (head ta) <*> (traverse loop (tail ta))

instance traversableWithIndexCofree :: Traversable f => TraversableWithIndex Int (Cofree f) where
traverseWithIndex f = loop 0
where
loop ix ta = mkCofree <$> f ix (head ta) <*> (traverse (loop (ix + 1)) (tail ta))

instance extendCofree :: Functor f => Extend (Cofree f) where
extend f = loop
where
Expand Down