07 Jul 2015

map & reduce 1 are the bread & butter tools of functional programming, but if you’re new to FP it’s easy to get muddled about which to use when, so here’s my mental checklist:

  • If you have a sequence and you want a sequence, use map.
  • If you have a sequence and you want a single value, use reduce (or
  • fold).
  • If you have a single value and you want a sequence, use unfold.

That’s a simplification, but a good rule of thumb to get started with. (The twist comes when you realise that the “single value” that reduce produces can itself be a new sequence.) But hopefully that will serve as a simple signpost if you’re coming from a world of for loops and wondering how to break things down.

Footnotes

  1. Or map and fold/foldl/foldr , depending on your language. 

comments powered by Disqus