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:
output:
jerry-java
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.
Output:
jerry-java-scala

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).
LOOP AT lt_temp ASSIGNING FIELD-SYMBOL(<temp>).
   lv_result = lv_result && |{ <temp>  case = lower }| .
   IF sy-tabix <> lines( lt_temp ).
      lv_result = lv_result && '-'.
   ENDIF.
ENDLOOP.

WRITE: / lv_result.
Output:
jerry-java-scala
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:
To report this post you need to login first.

1 Comment

You must be Logged on to comment or reply to a post.

Leave a Reply