purescript-foldable-traversable icon indicating copy to clipboard operation
purescript-foldable-traversable copied to clipboard

discussion: describe relation between Foldable and Unfoldable and there indexed versions

Open safareli opened this issue 6 years ago • 6 comments

I had an idea:

What if instead of

Map.fromFoldable $ Map.toUnfoldable someMap

You could do:

unfoldWithIndex $ foldWithIndex someMap

where

foldWithIndex   ∷ ∀ g f idx a
    . Unfoldable g
    ⇒ FolableWithIndex idx f
    ⇒ f  idx   a
    → g (idx × a)
unfoldWithIndex ∷ ∀ g f idx a
    . Foldable g
    ⇒ UnfoldableWithIndex idx f
    ⇒ g (idx × a)
    → f  idx   a

p.s. names foldWithIndex and unfoldWithIndex are arbitrary just types meter

safareli avatar Nov 29 '17 20:11 safareli

this two functions are describing relation between all 4 classes, we can derive a law unfoldWithIndex <<< foldWithIndex === id

doing it the other way might be be an id (duplicate indexes in list for example) unfoldWithIndex >>> foldWithIndex === id

safareli avatar Nov 29 '17 20:11 safareli

I don't think you need a new UnfoldableWithIndex class, just unfold the index as you go.

paf31 avatar Nov 29 '17 20:11 paf31

yes but in that case you need special functions like Map.fromFoldable. when Map could be an instance of UnfoldableWithIndex which means one could do unfoldrWithIndex and get as result a Map or any UnfoldableWithIndex.

safareli avatar Nov 29 '17 20:11 safareli

Oh I see, you're unfolding with access to the key of the Map. There's something wrong with the kinds in your types though. f is applied to too many type arguments.

class UnfoldableWithIndex i f | f -> i where
  unfoldrWithIndex :: (s -> Maybe ({ value :: a, index :: i, next :: s }) -> s -> f a

Is that what you want?

That seems strange to me, since I can't write an UnfoldableWithIndex Int List instance, for example.

paf31 avatar Nov 29 '17 20:11 paf31

ah yes I was thinking index part was visible in types. so they should be like this:

foldWithIndex ∷ ∀ g f idx a
    . Unfoldable g
    ⇒ FolableWithIndex idx f
    ⇒ f  a
    → g (idx × a)
unfoldWithIndex ∷ ∀ g f idx a
    . Foldable g
    ⇒ UnfoldableWithIndex idx f
    ⇒ g (idx × a)
    → f  a

That seems strange to me, since I can't write an UnfoldableWithIndex Int List instance, for example.

that's expected I think because linked-ness of List, I guss we can do: UnfoldableWithIndex Int Array and UnfoldableWithIndex i (Map i)

safareli avatar Nov 29 '17 21:11 safareli

actually we can name them fromFoldable and toUnfoldable:

fromFoldable ∷ ∀ g f idx a
    . Foldable g
    ⇒ UnfoldableWithIndex idx f
    ⇒ g (idx × a)
    → f a
toUnfoldable ∷ ∀ g f idx a
    . Unfoldable g
    ⇒ FolableWithIndex idx f
    ⇒ f a
    → g (idx × a)

safareli avatar Nov 29 '17 21:11 safareli