Monads! Mike Hadlow @mikehadlow http://mikehadlow.blogspot.com - - PowerPoint PPT Presentation

monads
SMART_READER_LITE
LIVE PREVIEW

Monads! Mike Hadlow @mikehadlow http://mikehadlow.blogspot.com - - PowerPoint PPT Presentation

Monads! Mike Hadlow @mikehadlow http://mikehadlow.blogspot.com mikehadlow@suteki.co.uk What well talk about What is a Monad? A (very) brief history of Monads. Lots of C# code Thoughts on C# vs F# vs Haskell.


slide-1
SLIDE 1

Monads!

Mike Hadlow @mikehadlow http://mikehadlow.blogspot.com mikehadlow@suteki.co.uk

slide-2
SLIDE 2

What we’ll talk about…

  • What is a Monad?
  • A (very) brief history of Monads.
  • Lots of C# code 
  • Thoughts on C# vs F# vs Haskell.

https://github.com/mikehadlow/Suteki.Monads

slide-3
SLIDE 3

“Amplified Types”

  • Collections: IEnumerable<string>, IList<int>
  • Nullable<int>
  • Task<string>
  • They wrap and ‘enhance’ simple types.
  • They all require boiler plate to access their

wrapped values.

slide-4
SLIDE 4

Amplified type composition

  • Monads allow us to compose amplified types

naturally without boiler plate.

  • To be a Monad, a Whatever<T> must implement

two methods:

Whatever<T> ToWhatever<T>(T value) // AKA unit Whatever<B> Bind<A,B>(Whatever<A> a, Func<A, Whatever<B>> func)

slide-5
SLIDE 5

Maths!

  • Category theory 1940s.
  • You need to understand Category theory to

understand Monads.

slide-6
SLIDE 6

Haskell

  • Haskell is a pure lazy functional programming

language.

  • No side effects. No guaranteed order of

execution.

  • Monads first introduced by Eugenio Moggi

and Philip Wadler to enable side effecting functions.

  • Many applications of Monads in Haskell.
slide-7
SLIDE 7

Code!

slide-8
SLIDE 8

The limitations of Linq & C#

  • No control structures (if/else, loops)
  • We can’t define a Monad in C# because we don’t

have “types of types”.

M<T>

This is generic This can’t be generic

slide-9
SLIDE 9

F# Computation Expressions

type Identity<'a> = Identity of 'a let getValue (a : Identity<'a>) = match a with Identity x -> x let mreturn x = Identity x let bind (a : Identity<'a>) (f : 'a -> Identity<'b>) = f (getValue a) type IdentityBuilder() = member x.Bind(a, f) = bind a f member x.Return(a) = mreturn a let identity = new IdentityBuilder() let result = identity { let! a = Identity 4 let! b = Identity 3 return a + b } printfn "result = %A" (getValue result)

slide-10
SLIDE 10

Haskell ‘do’ notation

data Identity a = Identity a getValue (Identity a) = a instance Monad Identity where return a = Identity a (>>=) a f = f $ getValue a main = putStrLn $ show $ getValue $ do a <- Identity 4 b <- Identity 3 return (a + b)

slide-11
SLIDE 11

Where next?

  • My Monad series on Code Rant
  • Wikipedia Monad Page
  • Wes Dyer – The Marvel of Monads
  • Read a good Haskell Book:

– Learn you a Haskell for Great Good – Read World Haskell

slide-12
SLIDE 12

Questions?