Cool Haskell functional magic (arrows)


/ Published in: Java
Save to your folder(s)

Some really cool Haskell clustering function, the implementation uses Arrows (seen at http://debasishg.blogspot.com/2009/01/seeking-scala-equivalent-for-this.html).


Copy this code and paste it in your HTML
  1. -- Uasge
  2. *Main> let antwords = words "the tan ant gets some fat"
  3.  
  4. *Main> clusterBy length antwords
  5. [["the","tan","ant","fat"],["gets","some"]]
  6.  
  7. *Main> clusterBy head antwords
  8. [["ant"],["fat"],["gets"],["some"],["the","tan"]]
  9.  
  10. *Main> clusterBy last antwords
  11. [["the","some"],["tan"],["gets"],["ant","fat"]]
  12.  
  13. -- Source
  14. import Control.Arrow ((&&&))
  15. import qualified Data.Map as M
  16.  
  17. clusterBy :: Ord b => (a -> b) -> [a] -> [[a]]
  18. clusterBy f = M.elems . M.map reverse . M.fromListWith (++) . map (f &&& return)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.