F#: Railway-Oriented Programming


Documenting interpretation of Railway-Oriented Programming.

The “Railway” provides a “Success Track” and a “Failure Track”. The Success Track is defined as the track of the “Happy Path”. This means that the objective of a function was completed successfully without errors. There also exists an alternate track that isn’t exposed initially. This track is known as the Failure Track. The Failure Track represents the “Sad Path”.

The railway starts off on one track which is known as the Success track. If any errors occur, this one track will spawn a fork. This fork exposes a separate track as the new execution path that is to be taken. This track is known as the Failure Track.

Track Foundation

The following code reflects the Tracks foundation:

module Core.Validation.Railway
type Result<'TSuccess,'TFailure> = 
    | Success of 'TSuccess
    | Failure of 'TFailure
let bind nextFunction lastFunctionResult = 
    match lastFunctionResult with
    | Success input -> nextFunction input
    | Failure f -> Failure f


module Validators
open Core.Validation.Railway
type Request = {name:string; email:string}
let validate1 input =
   if input.name = "" then Failure "Name must not be blank"
   else Success input
let validate2 input =
   if input.name.Length > 50 then Failure "Name must not be longer than 50 chars"
   else Success input
let validate3 input =
   if input.email = "" then Failure "Email must not be blank"
   else Success input;;
let Validate = 
    >> bind validate2 
    >> bind validate3;;
// Setup
let goodInput = {name="Alice"; email="abc@abc.com"}
let badInput = {name=""; email="abc@abc.com"};;
// Test
Validate goodInput |> printfn "%A";;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: