bridging the gap: functional csharp

I would love to do more (or any) professional Haskell and I am really happy that I can do F# in my day to day work but the sad fact is: most of you probably may not (or don’t want to) use F# in your day-job and do C#.

Now that does not mean that you cannot program in a functional fashion – not at all. It only means that you might have to consider carefully if the different paradigm (and maybe the additional fight with C#s inferior type-inference and lacking syntax caps) will hinder you too much.

With this I want to start a small series where I give some examples of how the same small problem can be solved in a functional way in my favorite languages.

I hope some of you will sent me some proposals for future topics.

If not I will tease you with my usual non-real-life examples.

today’s problem: the Caesar cipher

As a first and easy example I want to show how a implementation of the infamous Caesar cipher could look like in Haskell, F# and finally C#.

For those of you who don’t know this algorithm: it’s a very easy encoding scheme (that you should never use in more than toy examples and games for kids) that Caesar used to hide messages from enemies.

You basically shift your alphabet by a constant (the key) to switch from plaintext to ciphertext:

Caesars cipher

The decoding is the same only that you shift in the other direction.

In programming you typically shift using addition modulo the max. representable number/character to get a bijection (the inverse here is the same function with the negative key).


Just pick the once you (can) understand and ignore the rest – I’m sure you get it 😉

Haskell version

A (hopefully readable) example implementation:

import Data.Char (ord, chr)

caesar :: Int -> String -> String
caesar key = map encode
  where encode  = chr . shift . ord
        shift c = (c + key) `mod` max'
        max'    = ord maxBound

here is a test-run

λ> let cipher = caesar 3 "Hello"
λ> cipher
λ> caesar (-3) cipher

F# version

In F# we usually don’t use point-free-style as much and prefer piping so a idiomatic version might look like this:

module Caesar =
    let private makeString (cs : char seq) =
        System.String (Seq.toArray cs)

    let private shift key (text : string) =
        let max = int System.Char.MaxValue
        |> int
        |> (fun n -> (n + key) % max)
        |> char
        |> makeString

    let encode key = shift key
    let decode key = shift -key

Please not that right now we cannot easily use constructors as functions and with |> so I introduced makeString (something you will see again shortly) – aside from this it’s more or less a typical translation from Haskell into F#.


  > let enc = "Hello" |> Caesar.encode 3;;
  val enc : System.String = "Khoor"

  > let dec = enc |> Caesar.decode 3;;
  val dec : System.String = "Hello"

C# version

You can now easily translate the F# version into C# by using extension-methods and LINQ (focus on ShiftCipher):

    public static class Caesar
        static string MakeString(this IEnumerable<Char> characters)
            return new string(characters.ToArray());

        static string ShiftCipher(this string text, int key)
            const int max = (int)Char.MaxValue;
                    .Select(c => (int)c)
                    .Select(n => (n + key) % max)
                    .Select(n => (char)n)

        public static string Encode(this string text, int key)
            return text.ShiftCipher(key);

        public static string Decode(this string text, int key)
            return text.ShiftCipher(-key);

and aside from having a bit more boilerplate and {/}s the piping with extension methods seem to work quite nicely (don’t you think?).

Here is the usual test-run:

var enc = "Hello".Encode(3); // = Khoor
var dec = enc.Decode(3);     // = Hello

Now of course this is a static class and stuff and your OOP heart might want you to transform this into some singleton-pattern or other OO-shit but please don’t 😉

Is it really that hard to pass the key parameter around? I don’t think so.


Leave a comment 😉


Mathias Brandewinder suggested this Test Run article via twitter as a further example – I have to look at it more carefully (it’s been quite some time I did something like this) but I like the idea – maybe we can compare after – it might take some time though, but easter vacation is comming (even if it looks more like winter at the moment)

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1832()

  • Nathan Armstrong

    Grumble, grumble… since you’re passing around the key parameter everywhere, just make it a member variable and create instances of class Caesar. Seriously, I hesitate to even call that proper C#.

    I kid, I kid. Nice ‘n’ tidy!

  • Tomáš Pažourek

    I tried to implement a solution to similar problem, the ROT13 cipher.

    Here’s my solution in functional C#:

    I designed a small library with some helpers for functional programming in C#, e.g. helpers for infinite sequences, or helpers for generating sequences, which can be used to create Haskell-like list comprehensions in C#:

    I would be happy for any feedback on the library:

    Hopefully you’ll not consider it as spam, I think it’s related. 🙂

    • Hi – thanks for your comment – indeed I was thinking of building something very similar and blogging in parallel about it (you see I want C# people to consider functional programming in order to fix em up for F#/Haskell/other cool stuff)

  • B’Flag

    It’s actually Caesar, not Ceasar.

  • your friendly coder

    The F# version seems to be a bit verbose and ineffective ( 4 traverses of the input). I would change the shift function to something like this (just 2 traverses here):

    let shift key text =
    let maxChar = int System.Char.MaxValue
    let convert (ch: System.Char) = (int ch + key) % maxChar |> char
    System.String(text |> convert |> Array.ofSeq)

    • performance was never a concern – so I honestly don’t care here if one or the other will take 1ns less 😉

      Aaside from this, I see where you are going. Indeed it’s just one of the functor-laws ( ) and as you can see I already used this in my Haskell version.

      But I liked the multiple maps because it is idiomatic for F# to write small step transformations (instead of point-free function composition) and it is a nice middle between Haskell and C#/LINQ)

      But thank you for your comment

      PS: I did not think your second comment would add anything to this discussion so I removed it

  • your friendly coder

    As far as C# version goes, I think that LINQ expressions are very declarative and thus very functional. Instead of translating F# code I would go for something like this (:

    static string ShiftCipher(this string text, int key)
    var cipher = from ch in text
    let shifted = (ch + key) % Char.MaxValue
    select (char)shifted;
    return new String(cipher.ToArray());

    • why not – what ever works for you – personally do prefer the vanilla extension methods over the SQLish syntax though – but yeah, as long as you have fun

  • SaintGerbil

    While I like the idea of making C# functional where possible I’ve yet to see any example which doesn’t rely on LINQ (or sometimes RX) while this is all well and good I think it teaches a lot of non-functional developers that FP is just the MapReduce pattern. Where as functional programming is so much more.

    • thanks for your comment.

      First let me just state it: the basic thing about FP is using mathematical functions and the consequences from this – historically this just makes reasoning about programs very easy.

      I cannot show every cool thing about FP in one single post and for C# developers things like currying might be nice but it’s rather useless in practice. What is really useful IMO are pure functions and immutable datastructures and the use of interesting extensions methods (that basically allow a nice form of F#-like piping – formerly known as fluent interfaces 😉 ) – and well LINQ provides you with lots of those already and most C# developers know LINQ by know so it’s a very good point to get started.

  • javier troconis

    Great post. I’m digging into F#/Clojure at the moment, but have been doing C# for some time, you could also go like this :

    static readonly Func<string,int,string> caesar = (input, key) => input
    .Aggregate(string.Empty, (result, x) => result + (char)(x + key % char.MaxValue));

    A left fold in other words.