Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functor in TypeScript

Tags:

typescript

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"
like image 487
nothrow Avatar asked Oct 06 '15 12:10

nothrow


People also ask

What is functor?

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.

What is a functor vs function?

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.

What is a functor in Javascript?

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 .

Is a function a functor?

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.


1 Answers

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');

Difference Between JS-Style Functor and Class Output

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.

like image 65
Fenton Avatar answered Nov 10 '22 13:11

Fenton