0

I have a bit freetime, so started to fiddle a bit around with lambda expressions in C#, just for the sake of learning something new. So I started with a simple square function:

Func<int, int> square = x => x * x;

Which worked as I expected. Next I tried something like this:

Func<int, int> cube = x => x * x * x;
Func<int, int> pow4 = x => square(x) * square(x);

Which also worked like expected. Then I got curious and wanted to do something like this:

Func<int, int, int> pow = (x,y) => ... // multiply x with itself, y-times  ;

I know, there are cases like y = 0 to care about, recursive algorithms to do this or use Math.pow(). So my question is: is it possible calculating the power of an integer by only using lambda expressions? How does it look like?

Thanks in advance.

  • 1
    What are you allowing, and what are you disallowing? It'll either have to be recursive, iterative, or call Math.Pow. – canton7 Aug 19 '19 at 12:36
  • lambda expressions are only "syntactic sugar" - nothing stops you from writing a complex function. But why not use a real function then? – KYL3R Aug 19 '19 at 12:37
  • Agreed with @canton7 it sounds like you have the solution, but want something else? – Austin T French Aug 19 '19 at 12:38
  • I'm not aware of every lambda feature, so I would disqualify only the Math.Pow call. Every other solution would be interesting. – CaptainRedbeard Aug 19 '19 at 12:39
  • 3
    It seems somewhat unfair that you're allowing `*` (for which there happens to be a built-in operator), but not allowing `Math.Pow (for which there doesn't happen to (currently) be a built-in operator) – canton7 Aug 19 '19 at 12:40
  • You can squeeze this answer into an inline function: https://stackoverflow.com/a/48138343/993547. Not sure what that would help though. – Patrick Hofman Aug 19 '19 at 12:43
  • @canton7 It wasn't my intention to be unfair. I just wanted to know if it's possible without Math.Pow, since i struggled to get it right by myself. – CaptainRedbeard Aug 19 '19 at 12:54
  • 1
    Then that doesn't have anything to do with lambda expressions? That's just "How do I implement Math.Pow without using `Math.Pow`?" – canton7 Aug 19 '19 at 12:55
  • 1
    This may also be interesting to you since you want to know how Math.Pow works: https://stackoverflow.com/a/8870593/9338645 – Chrᴉz remembers Monica Aug 19 '19 at 13:06
  • @canton7 I think, I had a slightly wrong understanding of how lambdas actually work. Reading the comments and answers helped me to get a better understanding. – CaptainRedbeard Aug 19 '19 at 13:42

3 Answers3

1

(Doesn't consider negative powers, hopelessly inefficient, do not do this!)

Iterative:

Func<int, int, int> pow = (x,y) => 
{
    if (y == 0)
        return 1;

    int result = x;
    for (int i = 1; i < y; i++)
    {
        result *= x;    
    }
    return result;
};

Recursive:

Func<int, int, int> pow = null;
pow = (x,y) => (y == 0) ? 1 : x * pow(x, y - 1);
canton7
  • 37,633
  • 3
  • 64
  • 77
0

This is an approach using recursion.

Note that declaring functions using lambda expressions and throwing exceptions from Lambda expressions are C# 7.0 features.

private int pow(int x, int y) 
        => 
        (y < 0) ? throw new ArgumentException("Negative exponent", nameof(y)) :
        (y == 0)  ? 1 :
        x * pow(x, y - 1);
NineBerry
  • 26,306
  • 3
  • 62
  • 93
0

Here is iterative solution (works for y>=1):

        Func<int, int, int> pow = (x, y) =>
        {
            int result = 1;
            for (int i = 0; i < y; i++)
            {
                result *= x;
            }
            return result;
        };

Here we use that instead of one statement (such as x => x * x), we can define code block (x => { ...; ...; ...; }). If you think about it, it's exactly the same thing we already do with methods!

static int ReturnFour() => 4;

static int ReturnFour() {
    return 4;
}

We can do the same thing with lambdas. So instead of Func<int, int> square = x => x * x;, you could write Func<int, int> square = x => { return x * x; }. This allows us to write more complex things, such as loops.


Here is recursive solution (y>=1):

        Func<int, int, int> pow = null;
        pow = (x, y) =>
            y == 1 ? x
                   : x * pow(x, y - 1);

We use something called ternary operator. It works like this:

bool condition = 1 > 0;
string result = (condition) ? ("Yes!") : ("No :-("); // Yes!

condition = 1 < 0;
string result2 = (condition) ? ("Yes!") : ("No :-("); // No :-( 

(note that the parenthesis are unnecessary in this case)

We can use this to use if statement without the code block { ... }. But to actually call lambda itself, it needs to be defined first. Lambda is not yet defined in it's body, so we need to define it before we start writing the body. The solution is to assign null (or whatever) to it first.

SoptikHa
  • 437
  • 4
  • 19
  • I think till this question I had bit of a wrong understanding of lambdas. your answer was helpful for my understanding, Thank you. – CaptainRedbeard Aug 19 '19 at 13:38