J
J
Julia2016-09-14 17:54:59
C++ / C#
Julia, 2016-09-14 17:54:59

How is the Lambda function used in the example?

Hi all. Please help me understand the example.
Execution results

2.0^3=8
2.0^3=8
2.0^3=8
2.0^3=8
end of main

In general, I don’t understand why the parameter in x3 is passed with a comma
#include <iostream>
#include <cstdlib>
using namespace std;

#include "../tools/tools.h"

typedef double (*polynom_t)(double x);  //  ???что тут происходит? 

double x3(double x) { return x*x*x; }

//double eval(polynom_t p, double x)
//{
  //return p(x);
//}

 
double eval(function<double(double)> p, double x)   // ???что значит function<double(double)> p
{
  return p(x);
}  

int main()
{
  // Variante 1
    cout << "2.0 ^ 3 = " << eval(x3,2.0) << endl;   // ?? почему тут нет передачи параметра в фю x3 параметра явно 


   cout << "2.0 ^ 3 = " << eval([](double x) -> double {return x*x*x;},2.0) << endl;     cout << "2.0 ^ 3 = " << eval([](double x){return x*x*x;},2.0) << endl;

    auto lambda_x3 = [](double x){return x*x*x;};
   cout << "2.0 ^ 3 = " << eval(lambda_x3,2.0) << endl;

  function<double(double)> func_x3 = [](double x){return x*x*x;};
    cout << "end of main" << endl;
    
    return EXIT_SUCCESS;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2016-09-14
@Anton3

function<double(double)>-- is a type of function that takes one double parameter and returns a double.
You can create a function type value using lambda expression syntax. The simplest example:

function<double(double)> f;
f = [](double x){ return x * 2; };
f(5);  //=> 10
f = [](double x){ return x * x; };
f(5);  //=> 25

The eval function in your example is a higher-order function that takes a function-type variable p and a double variable x. It is defined so that eval(lambda_x3,2.0)-- is the same as lambda_x3(2.0).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question