Skip to content

Instantly share code, notes, and snippets.

@dvdsgl
dvdsgl / Monads for a C# dev.md
Last active January 8, 2024 06:11
Monads explained (sort of) to a C# developer

A monad is a fancy word for a generic type of the form MyMonad<T> (a generic type of arity 1).

A monad is special because it adds 'special powers' to the T that it wraps. These 'special powers' won't sound very special to an imperative programmer, so you have to squint to see them but bear with me.

  • IEnumerable<T> is a monad that gives values of type T the special power of nondeterminism, or the ability to 'be' multiple values at once.
  • Nullable<T> is a monad that gives values of type T the special power of nullability, or the ability to be absent.
  • Task<T> is a monad that gives values of type T the special power of asynchronicity, or the ability to be used before they are computed.

The trick with monads comes when you want to play with the T values, because they are inside another type. C# introduced language changes to make dealing with values inside these monads easier:

@swlaschin
swlaschin / SourceLineCount_Roslyn.fsx
Last active December 27, 2015 21:48
F# scripts for analysis of Roslyn vs F# compiler
(*
This script counts lines in C# and F# projects.
It is used to compare the "useful lines" in F# projects with those in C# projects.
Copied from Kit Eason's code at http://www.fssnip.net/h4
REQUIRES:
* FSharp.Charting for charts
via NuGet