Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Being Fluent, Fluid and Functional with Monads.net

Today's project, monads.net by Sergey Zwezdin, is brought to us by a post from Ryan Skurkis.

Do you really like writing If after If after If? && after && after || after ||? Do you really like writing that same event method? Do you really like writing all that usual exception handling code? Empty catches?

Like the thought of continuing to incorporate fluent, fluid and functional programing into your coding practices?

Or maybe you just like the thought of saying "monad?" Smiley

Thinking Functionally in C# with monads.net

Functional concepts have worked their way into C# most notably through linq and lambda expressions, but the benefits of functional concepts in C# don’t have to stop there. This post will exemplify how functional concepts can be used to manage boilerplate code, such as if/else statements, null checks, and logging. The examples below are written using extension methods from the GitHub project, monads.net. monads.net isn’t required or even endorsed for working more functional goodness into your C# code, but it’s a great tool to start learning and sparking ideas with.

Before we dive into the code pit, please read my painless, oversimplified explanation of what monads are:
Monads are utility functions that accept and conditionally pass the result of functionX() to functionY().

Let’s start by reaching into a deeply nested object structure while doing null checks along the way.

image

...

What if we don’t care about storing the phone number in a variable. What if instead we just want to dial the number if it’s found.

image

...

Cool. If we find a manager and the manager is at work and we have the managers telephone number, we’re dialing it. But what if we want to log to a server or file along the way? An elegant way to handle this is to create our own logging “Monad,” which is another chainable extension method that can be used anywhere in our logic chain.

Our Log() looks like this. It will log the current value and a message if the current value isn’t null. This method will always return the value passed into it even if that value is null. This allows the chaining to continue similar to With(), Do(), and If().

image

sergun / monads.net

Monads for .NET is helpers for C# which makes easier every day of your developer life. Now supports .NET 3.5-4.0, Silverlight 3-5 and Windows Phone 7.

In functional programming, a monad is a programming structure that represents computations. Monads are a kind of abstract data type constructor that encapsulate program logic instead of data in the domain model. A defined monad allows the programmer to chain actions together to build a pipeline to process data in various steps, in which each action is decorated with additional processing rules provided by the monad. Programs written in functional style can make use of monads to structure procedures that include sequenced operations, or to define some arbitrary control flows (like handling concurrency, continuations, side effects such as input/output, or exceptions).

Monads for objects

image

  • Do
  • With
  • Return
  • If/IfNot
  • Recover
  • TryDo/Catch
  • Checking exception type (via Type)
  • Checking exception type (via predicate)
  • Ignore exceptions
  • TryWith/Catch

Monads for collections

image

  • CheckNull
  • CheckNullWithDefault
  • Check
  • CheckWithDefault

Argument checking

image

  • CheckNull
  • CheckNullWithDefault
  • Check
  • CheckWithDefault

Events

image

  • Events invoking

Want to know more about monads?

Functors, Applicatives, And Monads In Pictures

...

Conclusion

  1. A functor is a data type that implements the Functor typeclass.
  2. An applicative is a data type that implements the Applicative typeclass.
  3. A monad is a data type that implements the Monad typeclass.
  4. A Maybe implements all three, so it is a functor, an applicative, and a monad.

What is the difference between the three?

image

  • functors: you apply a function to a wrapped value using fmap or <$>
  • applicatives: you apply a wrapped function to a wrapped value using <*> or liftA
  • monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM

So, dear friend (I think we are friends by this point), I think we both agree that monads are easy and a SMART IDEA(tm). Now that you’ve wet your whistle on this guide, why not pull a Mel Gibson and grab the whole bottle. Check out LYAH’s section on Monads. There’s a lot of things I’ve glossed over because Miran does a great job going in-depth with this stuff.

Here’s a russian translation of this post. For more monads and pictures, check out three useful monads.

Now, you've seen them in action, you've seen what's behind them and, by now, I'm sure you've seen how these can make your coding life that much easier...

Tags:

Follow the Discussion

  • This looks great, does it support .net 4.5 ?

  • Quote: "monads.net isn't required or even endorsed for working more functional goodness into your C# code, but it's a great tool to start learning and sparking ideas with."

    Wait, what? How is it not endorsed?

     

  • DerpDerp

    Great, so it's the vb.net keywords flipped on the 90 degree bias to be fluent. Also grammar.

  • Nice stuff, thanks for sharing. Smiley

    Note that for events handlers there is a trick to avoid checking for null:

    public event EventHandler Updated = delegate{};
    
    public void Update()
    {
        Updated(this, EventArgs.Empty);
    }

    So from the start you have at least one empty delegate to execute, and a priori even a malicious code can't remove the original empty delegate so you always have one.

    You can consider this an application of the "null object" pattern.

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.