sanctuary icon indicating copy to clipboard operation
sanctuary copied to clipboard

Add `FoldableWithKey` and `TraversableWithKey`

Open masaeedu opened this issue 6 years ago • 3 comments

It'd be handy to have something like foldMapWithKey so you can do:

const replaceAll = foldMapWithKey(Endo)(k => v => s => s.replace(k, v))

const f = replaceAll({
  "Earth": "Jupiter",
  "Mars": "Earth"
})

f("Come in Earth, this is Mars speaking")
// => "Come in Jupiter, this is Earth speaking"

Similarly traverseWithKey.

masaeedu avatar Mar 20 '19 19:03 masaeedu

That looks neat, @masaeedu! What are the types of the two functions?

davidchambers avatar Mar 20 '19 19:03 davidchambers

@davidchambers Weird, looks like I edited away the types I just edited in. Here they are:

type FoldableWithKey k f = {
  foldMapWithKey : Monoid m -> (k -> v -> m) -> f v -> m
}

and:

type TraversableWithKey k f = {
  traverseWithKey : Applicative f -> (k -> a -> f b) -> t a -> f (t b)
}

masaeedu avatar Mar 20 '19 19:03 masaeedu

I'm actually still a little bit torn about whether it's a better idea to have foldMapWithKey and traverseWithKey or just: type WithKey k f = { withKey : f a -> f (k, a) }. If you do it the second way you can implement traverseWithKey just once for anything that happens to be both Traversable and WithKey (although of course you have to implement withKey for everything).

masaeedu avatar Mar 20 '19 20:03 masaeedu