Functional Programming – Try Reduce in JavaScript and in ABAP | SAP Blogs

Capture Date: 11.03.2018 19:42:51


In my previous blog Functional programming – Simulate Curry in ABAP I simulate a very important concept “Curry” in functional programming world using ABAP.

In that blog I use the curry idea in the example below:
In this blog, as blog title, I will show another approach by leveraging built-in function reduce in JavaScript Array and Reduce keyword in ABAP to fulfill the same requirement.
First see official documentation for Array.reduce here.
Follow the idea of functional programming, I first declare three dedicated functions which are responsible for a specific task in line 6 ~ 8.
Then in line 10, I construct a new composite function which will finally executes the three small functions driven by reduce.

Reduce in ABAP

Now let’s see how we can achieve the same function in ABAP.
If we use the traditional imperative programming paradigm, the code is written as:
DATA: lv_input TYPE string value 'Jerry Java Scala',
      lv_result TYPE string.

SPLIT lv_input AT space INTO TABLE DATA(lt_temp).
   lv_result = lv_result && |{ <temp>  case = lower }| .
   IF sy-tabix <> lines( lt_temp ).
      lv_result = lv_result && '-'.

WRITE: / lv_result.
Now let’s try with Reduce. Here is the ABAP documentation for keyword REDUCE.
See how ABAP code can be re-written using REDUCE:
This version looks quite clear and more human-readable compared with the first imperative one:
1. in line 11~13 there are three command instance created and inserted into a command queue held by variable lo_queue.
2. command queue ZCL_COMMAND_QUEUE internally execute the commands one by one using REDUCE as the execution engine.
The rough design of ABAP solution using REDUCE is listed below:
1. I have declare an interface ZIF_COMMAND which has one method DO to perform concrete command, one method GET_RESULT to return command execution result and method SET_TASK to specify command input.
2. ZCL_COMMAND_QUEUE has internally maintained a command queue. The enqueue operation is provided by public method INSERT.
Another public method EXECUTE is defined to fire the command queue execution.
Inside this method, ABAP keyword is used. The last command in the queue will be returned and its interface method get_result is called to return the final calculation request to consumer call.
Hope this small example can help you understand the reduce usage in functional programming world and how to use command design pattern to resolve some real problem.
The complete source code could be found here.
I have written a series of blogs which compare the language feature among ABAP, JavaScript and Java. You can find a list of them below: