Category Theory via C# (1) Fundamentals

[LINQ via C# series]

[Category Theory via C# series]

Category theory is a theoretical framework to describe abstract structures and relations in mathematics, first introduced by Samuel Eilenberg and Saunders Mac Lane in 1940s. It examines mathematical concepts and properties in an abstract way, by formalizing them as collections of items and their relations. Category theory is abstract, and called "general abstract nonsense" by Norman Steenrod; It is also general, therefore widely applied in many areas in mathematics, physics, and computer science, etc. For programming, category theory is the algebraic theory of types and functions, and also the rationale and foundation of LINQ and any functional programming. This chapter discusses category theory and its important concepts, including category, morphism, natural transform, monoid, functor, and monad, etc. These general abstract concepts will be demonstrated with intuitive diagrams and specific C# and LINQ examples. These knowledge also helps building a deep understanding of functional programming in C# or other languages, since any language with types and functions is a category-theoretic structure.

Category and category laws

In category theory, a category C is a algebraic structure consists of the following 3 kinds of mathematical entities:

  • A collection of objects, denoted ob(C). This is not the objects in object-oriented programming paradigm.
  • A collection of morphisms (relations, aka arrows or maps) between objects, denoted hom(C). A morphism m from source object X to target object Y is denoted m: X → Y.
  • A composition operation of morphisms, denoted ∘. For m1: X → Y and m2: Y → Z, their composition is also a morphism (m2∘ m1): Y → Z. Here the name of m1 of m2 also implies the order. m2 ∘ m1 can be read as m2 after m1.

And these entities must satisfy the following 2 category laws:

  • Associative law: the composition of morphisms associative: For m1: W → X, m2: X → Y and m3: Y → Z, there is (m3 ∘ m2) ∘ m1≡ ≡ m3 ∘ (m2 ∘ m1).
  • Identity law: for each object X, there is an identity morphism: idx : X → X, and identity morphism is neutral for morphism composition. For m: X → Y, there is idY ∘ m ≡ m ≡ m ∘ idX.

To make above abstract definitions intuitive, a category can be represented by the following interface:

public interface ICategory<TObject, TMorphism>
    IEnumerable<TObject> Objects { get; }

    TMorphism Compose(TMorphism morphism2, TMorphism morphism1);

    TMorphism Id(TObject @object);

A simple example of category is the category of integers, where the collection of objects are all integers, and the collection of morphisms are ≤ (less than or equal to) relations, from an integer either to itself, or to another integer greater than or equal to it, for example: m1: 0 → 1 (0 ≤ 1), m2: 1 → 10 (1 ≤ 10), etc. Regarding the transitivity of inequality, the ≤ morphisms can be composed, for example, m1: 0 → 1 (0 ≤ 1) and m2: 1 → 10 (1 ≤ 10) can be composed to another morphism (m2 ∘ m1): 0 → 10 (0 ≤ 10).



Apparently, the above composition is associative, foe example: ((1 ≤ 10) ∘ (0 ≤ 1)) ∘ (-1 ≤ 0) ≡ -1 ≤ 10 ≡ (1 ≤ 10) ∘ ((0 ≤ 1) ∘ (-1 ≤ 0)). And for each integer X, there is an identity morphism idX: X → X (X ≤ X), and (Y ≤ Y) ∘ (X ≤ Y) ≡ X ≤ Y ≡ (X ≤ Y) ∘ (X ≤ X). So the category laws are satisfied. In C#, integer can be represented by int, and the morphism of ≤ relation can be represented by a BinaryExpression of node type LessThanOrEqual, so the category can be represented as:

public class Int32Category : ICategory<int, BinaryExpression>
    public IEnumerable<int> Objects
            for (int int32 = int.MinValue; int32 <= int.MaxValue; int32++)
                yield return int32;

    public BinaryExpression Compose(BinaryExpression morphism2, BinaryExpression morphism1) =>
        Expression.LessThanOrEqual(morphism2.Left, morphism1.Right); // (Y <= Z) ∘ (X <= Y) => X <= Z.

    public BinaryExpression Id(int @object) =>
        Expression.LessThanOrEqual(Expression.Constant(@object), Expression.Constant(@object)); // X <= X.

DotNet category

.NET can also be viewed as a category of types and functions, called DotNet:

  • ob(DotNet): the collection of objects in DotNet category are .NET types, like string (System.String), int (System.Int32), bool (System.Boolean), etc.
  • hom(DotNet): the collection of morphisms in DotNet category are .NET pure functions between the input type (source object) to the output type (target object), like int.Parse: string → int, DateTime.IsLeapYear: int → bool, etc.
  • ∘: in DotNet category, the composition operation of morphisms is the composition of functions.

As already discussed in lambda calculus chapter, function composition is associative, and the unit function Id is the identity morphism:

public static partial class Functions
    public static Func<TSource, TResult> o<TSource, TMiddle, TResult>(
        this Func<TMiddle, TResult> function2, Func<TSource, TMiddle> function1) =>
            value => function2(function1(value));

    public static TSource Id<TSource>(T value) => value;

So that the category laws are satisfied.


The DotNet category can be represented as:

public partial class DotNetCategory : ICategory<Type, Delegate>
    public IEnumerable<Type> Objects =>
            .SelectMany(assembly => assembly.GetExportedTypes());

    public Delegate Compose(Delegate morphism2, Delegate morphism1) =>
        // return (Func<TSource, TResult>)Functions.Compose<TSource, TMiddle, TResult>(
        //    (Func<TMiddle, TResult>)morphism2, (Func<TSource, TMiddle>)morphism1);
            .MakeGenericMethod( // TSource, TMiddle, TResult.
            .Invoke(null, new object[] { morphism2, morphism1 });

    public Delegate Id(Type @object) => // Functions.Id<TSource>
            .CreateDelegate(typeof(Func<,>).MakeGenericType(@object, @object));

    private static IEnumerable<Assembly> SelfAndReferences(
        Assembly self, HashSet<Assembly> selfAndReferences = null)
        selfAndReferences = selfAndReferences ?? new HashSet<Assembly>();
        if (selfAndReferences.Add(self))
            self.GetReferencedAssemblies().ForEach(reference => 
                SelfAndReferences(Assembly.Load(reference), selfAndReferences));
            return selfAndReferences;
        return Enumerable.Empty<Assembly>(); // Circular or duplicate reference.

In DotNet category, each object is a type represented by System.Type, so Objects method queries all available types in current assembly, and also recursively query all available assemblies in all reference assemblies. And each morphism is a function from one type to another, which can be represented by System.Delegate, so the composition is just to call the o operator with 2 Delegate instances.


  • Hello
    I think there is a typo in:
    > A composition operation of morphisms, denoted ∘. For m1: X → Y and m2: Y → Z, their composition is also a morphism (m2∘ m1): Y → Z. Here the name of m1 of m2 also implies the order. m2 ∘ m1 can be read as m2 after m1
    the statement
    > their composition is also a morphism (m2∘ m1): Y → Z
    should be rewritten
    > their composition is also a morphism (m2∘ m1): X → Z

  • This is an invaluable article.

  • This is an invaluable article.

  • In the Functions class

    public static TSource Id<TSource>(T value) => value;

    T should be TSource right?

    In the DotNetCategory


    Should be


  • It looks like .NET code snippets are not generating proper HTML anymore.

  • A pedido de amigos os resultados anteriores foram incluídos nesta página.
    Deu no poste.
    Segunda-Feira 2020 O resultado do jogo do bicho,
    deu no poste desta Domingo,
    segue abaixo para apuração.
    Pesquise sempre por
    “jogo do bicho portalbrasil.

  • Deu no Poste ? Resultados Jogo do Bicho das 11 horas, 14 horas, 16 horas, 18 horas, 21 horas.
    Mostramos-lhe a tabela de resultados do jogo do bicho.

  • - enter the 6 digit amazon mytv code you receive at screen at to regiter your device. contact amazon support for hel

  • Hello there! Nice article!!! But anyways here’s one of the trusted online baccarat site we can offer you so many promo and event everyday!! Good luck!!!

  • Thank you for sharing your truth! I have so much more that I would like to say but I don't think its necessary. Just visit my site:

  • Great article, This post helps me a lot Thank you. Anyways I have this site recommendation for you, Just follow the given link here:

  • Reading this info So i am glad to convey that I have a very just right uncanny feeling I found out exactly what I needed. See more about sportstoto:

  • استفاده از سرویس ادوردز، نیاز به تخصص و تجربه کافی در این زمینه دارد. از این رو، مدیریت اکانت های ادوردز، در سال های اخیر به یک شغل محبوب تبدیل شده است که بسیاری از کارشناسان و شرکت های حوزه دیجیتال مارکتینگ، آن را ارائه می دهند. اگر به اندازه کافی با کار کردن با این سیستم آشنایی ندارید، یک اشتباه کوچک در آن می تواند هزینه های شما را هدر بدهد و منجر به کلیک های بی هدف شود.

  • مجموعه تولیدی زعیم ZAEEM با سابقه طولانی در زمینه تهیه و توزیع انواع نهاده های کشاورزی، با اتکا به دانش روز تولید نهاده های کشاورزی، اقدام به تولید انواع کود های مایع ، پودری و گرانول نموده و محصولات خود را با افتخار با نام تجاری ZAEEM به بازار عرضه می نماید. تمامی محصولات ZAEEM در پایلوت های مشخص مورد آزمون قرار گرفته و پس از دریافت مجوز های لازم از موسسه خاک و آب کشور به بازار ارائه می گردد. کشاورزان محترم می توانند با دانلود کاتالوگ محصولات زعیم در سایت ZAEEM و در بخش همکاران ZAEEM، اطلاعات تماس نمایندگی ها و عوامل فروش شرکت در سطح کشور را مشاهده کرده و از خدمات و محصولات مورد نیاز خود با کمترین هزینه ارسال کالا و درکمترین زمان ممکن برخوردار شوند.

  • <a href="">شرکت تهویه نوین ایرانیان</a> با بهره گیری از کادری مجرب و حرفه ای، متشکل از مهندسین با تجربه و نیروهای متخصص بر آن است تا در مسیر تحقق مشتری مداری گامهایی مؤثرتر بردارد. در این راستا با ارائه محصولاتی با کیفیت، عملکردی مطلوب، هزینه ای بهینه و نیز خدمات پس از فروش، در پی جلب رضایت مشتریان گرامی است.

  • This post is really astounding one! I was delighted to read this, very much useful. Many thanks

  • awesome post. I’m a normal visitor of your web site and appreciate you taking the time to maintain the nice site. I’ll be a frequent visitor for a long time.

  • This article is really fantastic and thanks for sharing the valuable post.

  • I arrived here from I've never seen anyone try to express category theory via C#, and even if it's less-suited to this type of exposition than, say, Haskell, it's still a very nice presentation of the concepts!

    I would like to make a small, hopefully constructive criticism of the commutative diagrams. I found the text written written in yellow, labeling the yellow morphsim arrows, nearly impossible to read.

    All the recent comments look like spam, so I have no idea if this comment will ever be read, but nice work!

  • Hello thankyou so much for this ,if someone taking online class so I believe it is very difficult for him and for that visit our website we have experts who will help you guys for taking your online class and online exam.

  • I am delighted to share after reading this awesome piece of writing. Excellent post.


  • آموزش جوشکاری صفر تا صد با ارائه مدرک بین المللی فنی و حرفه ای جهت مهاجرت
    آموزش جوشکاری در آموزشگاه جوشکاری آریاگستر از جمله دوره های فنی می باشد که بازار کار خوبی داشته و معمولا جوشکاران از درآمد بالایی برخوردارند. نیاز جوامع به تولید و صنعت به این شغل باعث شده که افراد زیادی خواهان آموزش جوشکاری باشند .

  • Thank you for helping people get the information they need. Great stuff as usual. Keep up the great work!!!.

  • Betting users who wish to use Sports Toto are advised to practice sports analysis techniques consistently. If you learn this knowledge by discussing the analysis of very good fixers, you can gain a useful position in sports betting as a constant.

  • Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you!

  • Magnificent post, very informative. I’m wondering why the opposite experts of this sector do not realize this. You should continue our writing. I am sure, you’ve a great readers’ base already!

  • To an extraordinary degree beautiful and enthralling post. I was chasing down this sort of data and recognized inspecting this one. Continue posting. Grateful for sharing.
    <a href="" target="_blank" title="성인웹툰">성인웹툰</a>

  • <a href="">virtual assistant jobs</a><br />
    <a href="">virtual assistant job</a><br />
    <a href="">virtual assistant jobs near me</a><br />
    <a href="">part time virtual assistant jobs</a><br />
    <a href="">virtual assistant jobs for beginners</a><br />
    <a href="">virtual assistant jobs online</a><br />
    <a href="">virtual assistant jobs part time</a><br />
    <a href="">virtual assistant jobs from home</a><br />
    <a href="">virtual assistant jobs no experience</a><br />
    <a href="">virtual personal assistant jobs</a><br />
    <a href="">virtual assistant jobs amazon</a><br />
    <a href="">virtual assistant jobs teenager</a><br />
    <a href="">virtual.assistant jobs</a><br />
    <a href="">virtual assistant jobs chicago  </a><br />
    <a href="">lamb chops</a><br />
    <a href="">lamb chops near me</a><br />
    <a href="">lamb chops recipe</a><br />
    <a href="">how to cook lamb chops</a><br />
    <a href="">grilled lamb chops</a><br />
    <a href="">lamb</a><br />
    <a href="">lamb chops</a><br />
    <a href="">mutton chops</a><br />
    <a href="">lamb chop recipes</a><br />
    <a href="">rack of lamb</a><br />
    <a href="">air fryer</a><br />
    <a href="">medium</a><br />
    <a href="">lamb</a><br />
    <a href="">fresh thyme</a><br />
    <a href="">pan</a>

  • قهوه فرانسه یک نوع قهوه سبک و دمی، که انتخاب مناسبی برای وعده صبحانه می باشد. به دلیل در مجاورت بودن آب و قهوه موقع دم کشی، کافئین خوبی هم دارد. برای دم کردن این قهوه از وسیله‌ای بنام فرنچ پرس، استفاده می‌ شود.

  • برای مشاهده و خرید انواع لاک ژل در رنگ بندی و مدل‌های مختلف کلیک کنید

  • خریدshadowlands ، شدولند مکانی است که تمام مردگان و ارواح به آنجا سفر میکنند . سیلواناس به رهبری هلیا ، گروهی برای مبارزه تشکیل داده . سیلوانا قصد دارد در دنیای آزروت ، تمام موجودات را نابود و به شدولند ببرد .
    تمام قدرت سیلوانا به خاطر شخصی است که با او در ارتباط است . سیلوانا Domination را شکست میدهد و مرز بین آزروت و شدولند ( زندگی بعد از مرگ ) را از بین میبرد .امپراطوری سیاه بر پا خواهد شد . جنگجویان بعد از کشتن هر قربانی ، روحشان را به شدولند میفرستند . الینس ها با خدایان در شدولند میجنگند . هاکار قصد دارد تا با بلعیدن رواح قدرتمند شود .
    سیلواناس با هدایت جنگ ، قصد دارد ارواح را از هاکار به سمت هلیا هدایت کند . ارواح تمام ترول هایی که در تزمیر کشته شده اند ، در موربارا ساکن اند . در النیر ریفت‌لندز بیشترین فساد وید در دراگون آیلز و رویای زمردین وجود دارد . شهر و قرارگاه اصلی به عنوان منطقه آرام در ژیروس قرار دارد . این ناحیه دارای مقدار خیلی زیادی از کؤست لاین و دو دانجن میباشد . در مجموع 9 دانجن که 5 تا در شدولند و بقیه در دراگون ایلز است و اسمی ندارد .

Add a Comment

As it will appear on the website

Not displayed

Your website