Tail Recursion in Dataweave

醉酒当歌 提交于 2020-12-13 13:20:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!