Monads

From bibbleWiki
Revision as of 01:51, 24 September 2025 by Iwiseman (talk | contribs) (Reviewing Code)
Jump to navigation Jump to search

Introduction

Heard about this with a friend and never really revisited it. With my attention at home on Rust, thought I might write something down

The Maybe Monad

Well possibly the Option monad for me. To make one of these you need define something to wrap your thing with and a function which could fail that returns the wrapper type

return :: a => Maybe a
>>= :: Maybe a

This was explained to me a little better with this picture.

What's the Point

  • Same idea works for other effects, e.g. reading from environments, input/output
  • Supports pure programming with effects
  • Use of effects explicit in types
  • Functions that work for any effect

Second Time Through

Really want to get this into my head. It is another Mathy thing that just requires me to have a light bulb moment.

Step 1 - Starting Code

So the YouTube started off with this which I might need to change

function square(x: number): number {
    return x * x;
}

function addOne(x: number): number {
    return x + 1;
}

// Which allows us to chain the two together. e.g.
addOne(square(2)) => 5

// I think this is the goal. To do something extra which uses the input data
// This example confused me because it is not valid typescript
addOne(square(2)) => {
    result: 5,
    logs: [
        "square(2) => 4",
        "addOne(4) => 5"
    ]
}

I think what they were suggest is they want the two functions to return an object with logs e.g.

const result = addOneWithLogs(squareWithLogs(2))
// Where result is
{
    result: 5,
    logs: [
        "square(2) => 4",
        "addOne(4) => 5"
    ]
}

Step 2 - Implement new Funcs

First we define an interface to hold the result we are after. i.e. the result and logs

interface NumberWithLogs {
    result: number;
    logs: string[];
}

Now we make our new addOneWithLogs and squareWithLogs to get our result

function squareWithLogs(x: number): NumberWithLogs {
    const result = x * x;
    return {
        result,
        logs: [`Squared ${x} to get ${result}`]
    };
}

function addOneWithLogs(x: NumberWithLogs): NumberWithLogs {
    const result = x.result + 1
    return {
        result, 
        logs: x.logs.concat([
            `Added one to ${x.result} to get ${x.result + 1}`
        ])
    };
}

const result2 = addOneWithLogs(squareWithLogs(2));

// Gives
{
  result: 5,
  logs: [ 'Squared 2 to get 4', 'Added one to 4 to get 5' ]
}

Step 3 - Identifying real Requirements

They want to be able to do this

squareWithLogs(squareWithLogs(2))
addOneWithLogs(5)

This is not possible with the current implementation as addOneWithLogs and squareWithLogs functions both take a ``NumberWithLogs``` as an argument not a ```number```

Step 4 - Wrapping the arguments

The next thing we do is to create a function which does take a number and converts it to a NumberWithLogs so we can call squareWithLogs(squareWithLogs(2)) and addOneWithLogs(5)

function wrapWithLogs(x: number): NumberWithLogs {
    return {
        result: x,
        logs: []
    };
}

We can now looking at squareWithLogs we can change the argument from number to squareWithLogs

function squareWithLogs(x: NumberWithLogs): NumberWithLogs {
    const result = x.result * x.result;
    return {
        result,
        logs: x.logs.concat([
            `Squared ${x.result} to get ${result}`
        ])
    };
}

Now we can call squareWithLogs

const result = squareWithLogs(squareWithLogs(wrapWithLogs(2)))

// Gives
{ result: 16, logs: [ 'Squared 2 to get 4', 'Squared 4 to get 16' ] }

Reviewing Code

We need to look at our code for duplication.

function addOneWithLogs(x: NumberWithLogs): NumberWithLogs {
    const result = x.result + 1
    return {
        result, 
        logs: x.logs.concat([
            `Added one to ${x.result} to get ${x.result + 1}`
        ])
    };
}

function squareWithLogs(x: NumberWithLogs): NumberWithLogs {
    const result = x.result * x.result;
    return {
        result,
        logs: x.logs.concat([
            `Squared ${x.result} to get ${result}`
        ])
    };
}

Let's change the return on both to calculate the logs outside of the return then the return function will look the same.

function addOneWithLogs(x: NumberWithLogs): NumberWithLogs {
    const result = x.result + 1
    const thisLogs = x.logs.concat([
        `Added one to ${x.result} to get ${result}`
    ]);
    return {
        result, 
        logs: x.logs.concat(thisLogs)
    };
}

function squareWithLogs(x: NumberWithLogs): NumberWithLogs {
    const result = x.result * x.result;
    const thisLogs = x.logs.concat([
        `Squared ${x.result} to get ${result}`
    ]);

    return {
        result,
        logs: x.logs.concat(thisLogs)
    };
}