Wednesday 15 March 2017

Lambda

A lambda is a convenient way to declare an anonymous Predicate/Func/Action basically a delegate; it uses => syntax which is spoken as "such that" x => x * x would be spoken as x such that x squared. It doesn't make sense 100% of the time, but I've heard some people use "Maps to" and other such statements.

anyway let's take a look at a predicate example; a predicate is also a Func that takes in one parameter and returns either true or false as a result.

static void Main(string[] args)
{  
    var nums = Enumerable.Range(0, 10);

    Predicate<int> getOdd = n => n % 2 == 1;
    var result1 = Array.FindAll(nums.ToArray<int>(), getOdd);
    Console.WriteLine(result1.Length);

    var result2 = nums.Count(getOdd.Invoke);
    Console.WriteLine(result2);

}

this is actually referred to as a expression lambda, this is because it doesn't have a body in { }; it simply returns a value, an expression lambda doesn't have to return a value it could be as simple as.

static void Main(string[] args)
{
    Action<string> SayHello = name => Console.WriteLine($"Hello {name}");
    SayHello("Pawel");
}

SayHello is also considered a expression lambda, this is a nice short hand but could have been written as

static void Main(string[] args)
{
    Action<string> SayHello = name =>
    {
        string output = $"Hello {name}";
        Console.WriteLine(output);
    };

    SayHello("Pawel");
}

Making it a statement lambda. A statement lambda can also have a return type

static void Main(string[] args)
{
    Func<int, bool> IsOdd = n =>
    {
        if (n % 2 == 1)
            return true;
        return false;
    };

    int result = Enumerable.Range(0, 10).Count(IsOdd);
    Console.WriteLine($"Odd number count:{result}");

}

in short if your lambda has {} around it; it's referred to as a statement lambda, otherwise if it's a one liner it's an expression lambda.

Creating an async Lambda is also very straight forward, just leverage the async/await keywords.

static void Main(string[] args)
{
    var nums = Enumerable.Range(0, 10);

    Func<int, Task<bool>> IsOdd = async n =>
        {
            await Task.Delay(500);
            if (n % 2 == 1)
                return true;
            return false;
        };

    foreach (var num in nums)
    {
        var isOdd =  IsOdd(num).Result;
        Console.WriteLine("{0} {1}", num, isOdd ? "is odd" : "is even");
    }
}

there's some complexity here that's being glossed over, but we'll dive into deeper detail when we look at asynchronous programming.

Lambda Expressions are a shorthand syntax for creating anonymous methods.

using System;
using System.Linq;

namespace pc.LambdaExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            var ints = Enumerable.Range(0, 10).ToArray();
            var odds = Array.FindAll(ints, i => i % 2 == 1);

            Console.WriteLine("Show odd integers");
            foreach (var n in odds)
                Console.Write($"{n} ");
        }
    }
}

For the lambda expression i => i % 2  you would say i goes to i mod 2
The => is referred to as the "goes to" operator.