Home > Development > Functional Programming in C#

Functional Programming in C#


Here are some basic high order functions from functional programming circles. This is essentially where Linq comes from 🙂

Filter – Select Items based on Predicate.
Map – Transform from A -> B
Reduce – Aggregate data
Partition – Filter and store results of positives and Negetives

using System;
using System.Collections.Generic;
using System.Linq;

namespace FunctionalProgrammingConcepts
{

    public class Tuple<TFirst, TSecond>
    {
        private readonly TFirst first;
        private readonly TSecond second;

        public Tuple(TFirst first, TSecond second)
        {
            this.first = first;
            this.second = second;
        }

        public TFirst First
        {
            get { return first; }
        }

        public TSecond Second
        {
            get { return second; }
        }
    }

    public static class HighOrderFunctions
    {
        public static IEnumerable<T> Filter<T>(this IEnumerable<T> items, Func<T, bool> predicate)
        {
            foreach (var item in items)
            {
                if (predicate(item))
                    yield return item;
            }
        }

        public static IEnumerable<K> Map<T, K>(this IEnumerable<T> items, Func<T, K> transform)
        {
            foreach (var item in items)
            {
                yield return transform(item);
            }
        }

        public static K Reduce<T, K>(this IEnumerable<T> items, Func<IEnumerable<T>, K> aggregate)
        {
            return aggregate(items);
        }

        public static Tuple<IEnumerable<T>, IEnumerable<T>> Partition<T>(this IEnumerable<T> enumerableOf, Func<T, bool> predicate)
        {
            var positives = enumerableOf.Where(predicate);
            var negatives = enumerableOf.Where(e => !predicate(e));
            return new Tuple<IEnumerable<T>, IEnumerable<T>>(positives, negatives);

        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class MainClass
    {
        public static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>{
                new Customer{ Id = 1, Name = "Blair Davidson"},
                new Customer{ Id = 2, Name = "Tim Davidson"},
                new Customer{ Id = 3, Name = "Tom Davidson"},
                new Customer{ Id = 4, Name = "Michelle Davidson"},
                new Customer{ Id = 5, Name = "Sophie Davidson"},
                new Customer{ Id = 6, Name = "Esther Hew"}
            };

            foreach (Customer c in customers.Filter(x => x.Id < 3))
            {
                Console.WriteLine(c.Name);
            }
            Console.WriteLine(new string('-',50));

            foreach (string c in customers.Map(x => x.Name))
            {
                Console.WriteLine(c);
            }
            Console.WriteLine(new string('-', 50));

            Console.WriteLine(customers.Reduce(x =>
                                 {

                                     int sum = 0;
                                     foreach (Customer customer in x)
                                     {
                                         sum += customer.Id;
                                     }
                                     return sum;
                                 }));


            Console.WriteLine(new string('-', 50));

            var items = customers.Partition(x => x.Id < 4);

            foreach (Customer c in items.First)
            {
                Console.WriteLine(c.Name);
            }
            Console.WriteLine(new string('-', 50));

            foreach (Customer c in items.Second)
            {
                Console.WriteLine(c.Name);
            }
            Console.WriteLine(new string('-', 50));


            Console.ReadKey();
        }
    }
}

Enjoy.

Blair

Advertisements
  1. March 3, 2010 at 10:18 pm

    Most of these already exist as a part of LINQ, mind you.

    filter exists as “Where”: http://msdn.microsoft.com/en-us/library/bb534803.aspx
    map exists as “Select”: http://msdn.microsoft.com/en-us/library/bb548891.aspx
    fold/reduce exists as “Aggregate”: http://msdn.microsoft.com/en-us/library/bb548651.aspx

    • March 4, 2010 at 1:15 am

      I know this is to demonstrate concepts only. Obviously LINQ is much nicer 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: