问题
Is there a way to take a recursive function (like the following) and make it tail recursive? I have an input like this:
{
"message": "Test ",
"read": [
{
"test": " t "
}
]
}
and this Dataweave function
fun trimWS(item) = item match {
case is Array -> $ map trimWS($)
case is Object -> $ mapObject {
($$): $ match {
case is String -> trim($)
case is Object -> trimWS($)
case is Array -> $ map trimWS($)
else -> $
}
}
case is String -> trim($)
else -> $
}
回答1:
I reworked a little bit your existing function to simplify it and I also run a few tests under Mule 4.2.1.
By building a data structure with over 840 levels deep, I was able to navigate and trim the fields. My guess is because of the structure of the data and lazy evaluation I am able to get past 256 depths which is the default value where DW 2.0 is throwing StackOverflow.
You can also increase the default value by passing a runtime parameter, its name is com.mulesoft.dw.stacksize
(e.g. com.mulesoft.dw.stacksize=500
) or any other number provided your system can handle it.
As I said creating a tail-recursive version is not easy, it will complicate the code, it will be way less maintainable as compared to the existing version, etc.
I hope it helps even if I am not directly answering your question.
%dw 2.0
output application/json
var ds = {
"message": "Test ",
"read": [
{
"test": " t "
}
]
}
var deepData = (0 to 840) as Array reduce (e, acc=ds) -> {value: " TO_TRIM ",next: acc}
fun trimWS(item) = item match {
case is Array -> $ map trimWS($)
case is Object -> $ mapObject {($$): trimWS($)}
case is String -> trim($)
else -> $
}
---
trimWS(deepData)
来源:https://stackoverflow.com/questions/58532367/tail-recursion-in-dataweave