Skip to content
This repository has been archived by the owner on Oct 4, 2020. It is now read-only.

Index function #78

Open
robertmassaioli opened this issue Dec 26, 2016 · 3 comments
Open

Index function #78

robertmassaioli opened this issue Dec 26, 2016 · 3 comments

Comments

@robertmassaioli
Copy link

A nice helper function to add to the library might be:

uniqueIndex :: forall f a b. (Foldable f, Functor f, Ord b) => (a -> b) -> f a -> Map b a
uniqueIndex toKey = M.fromFoldable <<< map (\x -> Tuple (toKey x) x)

I got the idea from the equivalent method from Guava in Java land.

This is obviously a method that we could all re-write ourselves but it seems like a common enough pattern (and one that is easy enough to support) that it might be worth making it into the library.

An equivalent method can be written for StrMap; just replace all references to 'b' with 'String' and 'Map' with 'StrMap'.

@paf31
Copy link
Contributor

paf31 commented Dec 27, 2016

Maybe this should be called something like fromFoldableWithKey?

Also, does it really need Functor? (Yes if it's implemented this way, but maybe not if we can fuse the fromFoldable with the map somehow)

@robertmassaioli
Copy link
Author

I don't know if it strictly needs Functor but I was not able to come up with a method that did not require it. Maybe somebody with some more skills than I can work out how to implement this without the Functor requirement; I just went for the simplest possible thing that would work.

And 'fromFoldableWithKey sounds great to me.

@natefaubion
Copy link
Contributor

natefaubion commented Jan 2, 2017

I think it's just

foldl (\acc val -> insert (toKey val) val acc) mempty

Or

foldMap (\a -> singleton (toKey a) a)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants