My Technical Notes

Tuesday, 19 August 2014

The "Null" monad in F#

In F#, we can use computation expressions to implement monads. Here is a definition of null' which is our monad:


type NullBuilder() =
    member __.Return (x: 'a option) = x
    member __.Return (x: 'a) = if (box x = null) then None else Some(x)

    member __.Bind(x: 'a option, f) =
        match x with
        | None -> None
        | Some x -> f x

    member this.Bind(x: 'a, f) =
        this.Bind(this.Return(x), f)

let null' = new NullBuilder()

Given a C# class definition of Student below, which contains an instance of Course which in turn has a property CourseId: string:


namespace ClassLibrary1
{
    public class Student
    {
        public Course Course { get; set; }
    }

    public class Course
    {
        public string CourseId { get; set; }
    }
}

Here is how we would safely extract the CourseId from a given student:


null' { 
    let! s = student
    let! c = s.Course
    return c.CourseId 
}

No comments: