Published on InterSystems Developer Community (https://community.intersystems.com)

Home > Map, Reduce and Filter Collections

Article
Sean Connelly · Mar 28, 2017 2m read

Map, Reduce and Filter Collections

Inspired by the article "Declarative development in Caché" that's still trending  on the dev com. The OP explored a functional style of iterating over a collection. A comment today suggested "Caché would need syntax support for anonymous functions".

With Macros you can kind of get anonymous like syntax using dot notation.

This is not production code, but it does work. First the macros...

#Define foreach(%c,%l) for i=1:1:%c.Size set %l=%c.GetAt(i) do
#Define map(%oc,%nc,%l) set %nc=##class(%ListOfDataTypes).%New() for i=1:1:%oc.Size set %l=%oc.GetAt(i) do  do %nc.Insert(fpl8349312378)
#Define filter(%oc,%nc,%l) set %nc=##class(%ListOfDataTypes).%New() for i=1:1:%oc.Size set %l=%oc.GetAt(i) set fpl8349312378="" do  if fpl8349312378'="" do %nc.Insert(fpl8349312378)
#Define reduce(%oc,%res,%l) set %res="" for i=1:1:%oc.Size set %l=%oc.GetAt(i) do  set %res=fpl8349312378
#Define return(%val) set fpl8349312378=(%val) quit

Then in COS code...

Map all items to a new auto created collection in UPPERCASE, later foreach over the list...

  $$$map(originalCollection,newCollection,item)
  .$$$return($ZCONVERT(item,"U"))

  $$$foreach(newCollection,item)
  .write !,item

Filter all items in to a new auto created collection where the items must pattern match one or more alpha chars...

  $$$filter(originalCollection,newCollection,item)
  .if item?1.A $$$return(item)

Reduce down all items in a collection to get a total...

  $$$reduce(originalCollection,total,item)
  .$$$return(total+item)

It's a quick 5 minute hack, but it's kind of interesting how macro's can simplify code (and potential bugs) if done in the right way. With the exception of creating Macro soup!

One baked in language feature that would be nice is a real return statement (still wishing).

Sean.

#Caché #Code Snippet #ObjectScript #Mapping #Tips & Tricks

Source URL:https://community.intersystems.com/post/map-reduce-and-filter-collections