Implement Lambda Expression TRUE, FALSE, AND, OR, and NOT with Javascript

3

I was reading about lambda > in this article and there were some examples of functional programming implementing TRUE, FALSE, NOT, AND and OR with Ruby:

T = lambda { |a,b| a } 
F = lambda { |a,b| b } 
display = lambda { |boolean| boolean['verdadeiro','falso']}

NOT = lambda{ |x| x[F,T] }
AND = lambda{ |a,b| a[b,F] }
OR = lambda{ |a,b| a[T,b] }

How to implement the same examples with JavaScript?

    
asked by anonymous 12.07.2015 / 09:34

1 answer

7

You chose a somewhat complex article to start understanding the lambas, huh? :) It could have started with a simpler one.

First, you need to understand what a lambda is: it is an anonymous function, which has not assigned it a specific name. This sounds different to those who are accustomed to always creating functions by naming them, for example (in Javascript):

function minha_funcao() {}

So how do you create a function without naming it? Both Javascript and Ruby allow you to do this (in fact, many other languages allow, even Java now in version 8 is allowing).

var funcao = function(param) {}

Note that the above function does not have a name. Actually, it was assigned to a variable and the name of the variable, however tempting, is not the name of the function, but a reference to that function. So, how useful is that?

var funcao1 = function(param) {
     alert(param);
}

function funcao2() {
    funcao1("Testando");
}

You can pass functions as a parameter to other functions! And then things get sinister and interesting! In the example above, an alert will be displayed with the String "Testing".

In Ruby, this same task is done differently, using the keyword lambda , but I'd rather not explain much about Ruby, since it is meant to learn how to do this in Javascript. Now, let's make the examples you passed in Ruby but in JS:

var T = function(a,b) { return a; };
var F = function(a,b) { return b; };
var display = function(booleano) { return booleano('verdadeiro', 'falso'); };

var NOT = function(x) { return x(F,T); };
var AND = function(a,b) { return a(b,F); };
var OR = function(a,b) { return a(t,B); };

// agora testando:
alert(display(AND(T,F))); // Vai exibir verdadeiro, como deveria.

I created this fiddle with this example: link . This example you brought is a little tricky to understand, but it's interesting because it makes use of the lambda functions masterfully.

Note that the function stored in the T variable takes two parameters (two lambda functions too) and returns only the first function. The function in F returns the second parameter. From then on, it defines how NOT, AND, and OR would be using only those functions!

If you use jQuery, you know there is a each ( link ) method that receives a function as a parameter. This function you pass is a lambda!

    
12.07.2015 / 16:57