lundi 26 janvier 2015

Is partial application of functions the corresponding technique for state saving objects?


Imagine we have Converter object which is responsible for converting Strings in different ways, e.g. with convertingMethod1 and convertingMethod2. As the Converter depends on some context, it also internally stores some state and uses it for converting. Pseudo-code:



class Converter {
//these are set when constructing the convert and used in methods below
final contextPart1
final contextPart2

convertingMethod1(text, contextPart3) {
//use contextParts 1, 2 and 3 to do something with text and return it
}

convertingMethod2(text, contextPart4) {
//use contextParts 1, 2 and 4 to do something with text and return it
}
}


With that I can create my custom Converter, initially pass contextParts 1 and 2 and call it like myConverter.convertingMethod2("someText", "someContextParameter"). I can even pass this converter to another object that can use it without caring about its internal state.


What would be the functional way to do that? I can imagine having a function convertingFunction(contextPart1, contextPart2, text, contextPart3) which I can partial apply or curry, so that I create my customConvertingFunction = convertingFunction.setFix("myContextPart1", "myContextPart2") and then call customConvertingFunction("someText", "someContextParameter") and pass it to other functions. But how exactly would I pass both convertingFunction1 and convertingFunction2 together/bundled up (without having to repeat myself)?





Aucun commentaire:

Enregistrer un commentaire