How can I create functor in TypeScript?
EDIT:
Functor is, in C++ world, function that can hold state - basically class that has overriden ()
operator.
So, for example, I'm able to do following:
class myClass {
var value : string;
// how?
functor() : string {
return value;
}
}
var a = new myClass();
a.value = "abc";
a(); // to return "abc"
In functional programming, a functor is a design pattern inspired by the definition from category theory, that allows for a generic type to apply a function inside without changing the structure of the generic type.
Functors are objects that behave as functions. They are class objects which can overload the function operator() and act as function themselves. They can encapsulate their own function which is executed when needed.
A functor data type is something you can map over. It's a container which has an interface which can be used to apply a function to the values inside it. When you see a functor, you should think “mappable”. Functor types are typically represented as an object with a .
A function pointer allows a pointer to a function to be passed as a parameter to another function. Function Objects (Functors) - C++ allows the function call operator() to be overloaded, such that an object instantiated from a class can be "called" like a function.
So really what you have here is a method on a class, like this:
class myClass {
constructor(private text: string) {
}
methodName() : string {
return this.text;
}
}
var a = new myClass('Example');
a.methodName(); // 'Example'
If you just want a plain function, you can do that too:
function functor(text : string) : string {
return "abc";
}
functor('text');
You can attempt to reproduce a functor, like this:
function functor(text : string) : () => string {
return function() {
return text;
}
}
var x = functor('Example');
x(); // returns 'Example'
But actually, using a class gives you the very similar:
var myClass = (function () {
function myClass(text) {
this.text = text;
}
myClass.prototype.methodName = function () {
return this.text;
};
return myClass;
})();
var a = new myClass('Example');
a.methodName(); // 'Example'
With the benefits of class semantics... you can extend the class, you can generate an interface from the class and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With