Tag Archives: .NET

Bind? No.. Apply…? No… Map!?

After continuing my foray into the functional with Giraffe and .NET Core, I have struggled with the code not quite reading very well. Various data sources are pluggable, i.e. they can be replaced with mocks if you don’t want to run other supporting systems while debugging. This pluggability along with the way Giraffe handles some of its configuration means that – while we would like to compose partially applied functions with either mocked or actual services baked in that are then passed in to the relevant handlers, we instead have to pass a HttpContext around everywhere. If you followed that link you probably wondered why we did not just use the strategy outlined in that blog series. I can only say that we did not understand fish operators at this point. 

So we turn to the googles, and as usual the first or second hit lands us on F# for fun and profit. Scott Wlaschin introduces us to the Reader Monad. We watch his talks, we read his blog posts. A week of enthusiastic coding goes by.

Essentially – the reader monad allows you to write and construct all the code and only at the end plug in the HttpContext as the whole thing is evaluated and returned to the caller.

You make a Reader<‘env, ‘data>  and you create functions to wrap and unwrap things in and out of the Reader. Then you make functions that mind their own business but they return Reader<‘env, b: and you allow the reader to handle some railway oriented programming for you. Essentially you lay the track all through the code but on the last line in the handler you put the train on the tracks and set it off, only then realising whether or not it ended up running through the failure cases or went all through the success track.

Wrappers, essentially, like Option<‘a>, IEnumerable<‘a> or Reader as described above, are introduced as Elevated things. The proper word seems to be Monadic types, but that does not seem to be a good term, as there is no need for a wrapper type to be a monad, although they can be. After a few specific examples the general case is presented and it turns out you can do a bunch of stuff with these elevated types only using functions like bind, return, apply and map. There is a brief epiphany as we experience a flicker of understanding of  the monad laws.

A monad is just a monoid in the category of endofunctors, what is the problem?

Now I cannot explain the chaining of elevated and non-elevated functions properly. I know what bind does, and I can use it correctly on the first try. Return is obvious. Map and apply though… it’s like being ten years old again and round-robining commands until the compiler is happy. As it stands all I can do is link to the posts we have read and the metaphors that have been presented to me, that I have half understood and then tried to reconcile with other conflicting metaphors.

Inevitably the golden success case of “first I need this, then I pass it to this other thing and then I flip it, kick it and reverse it and then I return it” is soon replaced by “well, first I need this one thing, that I need to just check against this other thing, but then use it again in this third thing which I convert to this fourth thing that I might return if this fifth thing is true” and the nice chaining goes out the window and it makes you sad.  Every let b =  … feels like a let-down (hence the name).

This let = thing is apparently called applicative style, where you compose values, while chaining is called monadic style. At least it has name. 

So after a while when you have been writing things like

task {
    let! a = coolFunc b c
    return! a |> modifyInAnAwesomeWay
async {
   let! a = thingThatDoesDatabaseThings b 
   return! match a with 
      | Some data -> coolThing data
      | None -> unCoolError

You start wondering what the heck it is you are doing. What are these things? It turns out they are computational expressions. But how do I make them?  You essentially create a ThingBuilder class with members for bind and return, and then create a let thing = new ThingBuilder(), after which you can write expressions like:

thing {
    let! unwrapped = funcThatGetsPassedToBind arg
    return unwrapped

To be a bit enterprisey I have come up with a draft of a brilliant thing. The F# Functional Maturity Model (FFMM):

  1. Can get samples to compile even with modifications
  2. Can get write small programs that do useful things in prod
  3. Can write software systems that fulfill a business purpose
  4. Can see how bad OO in F# looks and strive to create functional style code
  5. Attempt to write a monad tutorial
  6. See the beauty of computational expressions and want to use them everywhere
  7. Stops being afraid and starts to love Kliesli composition (the fish operator)
  8. Realise computational expressions are an antipattern and curse their existence
  9. ..

 As you can see I have yet to ascend the ladder enough to know what all the levels are, but I am currently on 6 I believe, but given the hate people have for do in Haskell, it seems that there must be a level where you realise the computational expressions are of the devil and must be eliminated at all cost, but at the level where I am now, they do indeed seem like they cut away a lot of plumbing code where I otherwise map and bind to call various things. Also, I see the fish operator everywhere so clearly it must be awesome. I now at least understand what it does, but I can’t say it fits very well in the code I want to write. I’m sure that is an epiphany for a later date. 


Simple vs “Simple”

F# has two key features that makes the code very compact. Significant whitespace and forced compilation order.

Significant whitespace removes the need for curly braces or the use of keywords such as begin/end. Forced compile order means your dependencies have to be declared in code files above yours in the project declaration. This gives your F# projects a natural reading order and makes projects follow a natural order that transcends individual style.

Now there is a user voice suggestion that the enforced compile order be removed.

I think this is a good idea. I am against project files. As soon as you have three or more developers working in the same group of files, any one file used to maintain state is bound to become a source of merge conflicts and strife. Just look at C#.

I am sure your IDE could evaluate the dependency order of your files and present them in that order for you, heck one could probably make a CLI tool to show that same information if the navigational benefits of the current order is what is holding you back. Let us break out of IDE-centric languages and allow the programs to be defined in code rather than config.

So what’s this FP thingy?

People are talking about Scala, F#, Erlang, Haskell and what-have-you. What is the point of functional? What is wrong with OOP? How does it all work?

Here are some videos you might want to look at. Maybe you find them helpful, maybe not.

Jessica Kerr: Functional Concepts for Object Oriented developers

This introduces the concept of immutability and pure functions and how your life gets better if you use those concepts in your everyday life. Of course, in DDD Value Objects and immutability is king as well, for the very reasons Kerr brings up in the video.

Brian Beckman: Don’t fear the Monad

This is a scary attempt at explaining monoids and monads. You may follow it, you may not. Don’t get too distracted or discouraged. Think of it monads in terms of LINQ and composability.

Erik Meijer C# Lecture, Functional Programming and Monads


This talk is affected by Erik Meijers huge brain and is scarily influenced by Haskell, but makes sense if you saw the video above.

F# Creator Don Syme does a Tutorial

Don Syme F# Tutorial Part 1

You should skip the first part unless you want to know from whence F# came. There is very little syntax info in this chapter.

Don Syme F# Tutorial Part 2
Loops, data structures, beginning of pattern matching.

Don Syme F# Tutorial Part 3

WCF 4.0

As the tour is now concluded and we are doing business as usual I figured it is time to post some promised source code and powerpoint material. If you just joined us, the final Jayway seminar of the spring season was on Windows Identity Foundation and a short roundup of new features in WCF 4.0. Stefan Severin MC:d the WIF section while I did the presentation on WCF 4.0.

So what IS up with WCF 4.0?  My three main points were the following:

  1. Simplified Configuration
  2. Full implementation of WS Discovery
  3. A turn-key RoutingService

My full presentation in attached and I also submit some source code, largely based on Aaron Skonnard’s excellent MSDN article with minor modifications to show the difference between WCF3.5 and WCF4 in terms of configuration.



Source Code

Aaron Skonnard’s introduction to WCF 4.0