pathterminuspages/snippets/aboutcontactabout me

Monads in Fsharp - Maybe

27.09.2019

So I have learned about monads in a Haskell course. After being forced to play around with them, they make sense. The idea exists in Fsharp as well, here it is called a computational expression. This is a series of translating Haskell monads into Fsharp ones. Beginning with the maybe monad.

type Maybe<'a> = | Nothing | Just of 'a type MaybeClass() = member this.Return a = Just a member this.Bind (a:Maybe<'a>,f:'a -> Maybe<'b>) = match a with | Nothing -> Nothing | Just a -> f a let fmap f a = match a with | Nothing -> Nothing | Just a -> Just (f a) let maybe = MaybeClass()

Along some testing

type Maybe<'a> = | Nothing | Just of 'a type MaybeClass() = member this.Return a = Just a member this.Bind (a:Maybe<'a>,f:'a -> Maybe<'b>) = match a with | Nothing -> Nothing | Just a -> f a let fmap f a = match a with | Nothing -> Nothing | Just a -> Just (f a)

fmap comes along functors in Haskell. A monad is a functor. The core idea is to have some computation in which a lot of details are hidden. The functionality of the monad is provided to manipulate with the inside of this computation.

CommentsGuest Name:Comment: