Home > Net >  How to calculate func in c#?
How to calculate func in c#?

Time:09-21

I have this:

eight(minus(three())); should return 5
eight(plus(three())); should return 11

I only added two functions:

private static Func<int> Minus(
       Func<int> left,
       Func<int> right)
       => left - right;

private static Func<int> Plus(
       Func<int> left,
       Func<int> right )
       => left   right;

How can I solve the problem?

CodePudding user response:

This should work

    double One( Func<double>? right=null)=> 1   (right!=null ? right(): 0 );
    double Two( Func<double>? right=null)=> 2   (right!=null ? right(): 0 );
    double Three( Func<double>? right=null)=> 3   (right!=null ? right(): 0 );
    double Four( Func<double>? right=null)=> 4   (right!=null ? right(): 0 );
    double Five( Func<double>? right=null)=> 5   (right!=null ? right(): 0 );
    double Six( Func<double>? right=null)=> 6   (right!=null ? right(): 0 );
    double Seven( Func<double>? right=null)=> 7   (right!=null ? right(): 0 );
    
    double Eigth(Func<double>? right =null)=> 8   (right != null ? right() : 0);
    double Nine(Func<double>? right =null)=> 9   (right != null ? right() : 0);
    double Zero(Func<double>? right =null)=> 0   (right != null ? right() : 0);
    
    
    Func<double> Plus(double right) => () => right;
    Func<double> Minus(double right) => () => right * -1;
    
    
    
    Console.WriteLine(Eigth(Minus(Three())).ToString()); // 5 
    Console.WriteLine(Eigth(Plus(Three())).ToString()); // 11
    
    Console.WriteLine(One(Minus(Three())).ToString()); // -2 
    
    Console.WriteLine(One(Plus(Four())).ToString()); // 5
    Console.WriteLine(One(Plus(Zero())).ToString()); // 1
    Console.WriteLine(Two(Plus(Five())).ToString()); // 7
    
    Console.WriteLine(Seven(Minus(Six())).ToString()); // 1
    Console.WriteLine(Nine(Plus(Six())).ToString()); // 15
    Console.Write(Seven(Plus(Nine(Plus(Two()))))); // 18 
    Console.WriteLine(Two(Plus(Nine(Minus(One(Plus(Seven()))))))); // 2   ( 9 - (1   7) ) = 3

CodePudding user response:

This will work, which will keep the intermediate results in a variable x, and will default to add the value. The output of eight(three()) will also be 11.

int x;

static int Minus(int x) {
    x=-x;
    return x;
}
static int Plus(int x) {
    return x;
}

static int three(int x=0) {
    x=x 3;
    return x;
}

static int eight(int x=0) {
    x=x 8;
    return x;
}

int y = eight(Minus(three()));
System.Console.WriteLine( y  );

y = eight(Plus(three()));
System.Console.WriteLine( y  );

output:

5
11
  •  Tags:  
  • c#
  • Related