• This repository has been archived on 21/Dec/2023
  • Stars
    star
    391
  • Rank 107,696 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Little monad library designed for TypeScript

TsMonad

  • a simple and pragmatic monad library
  • designed for TypeScript
  • with the aim of limiting errors due to unhandled nulls

Status

Sorry folks, I don't have time to actively maintain this project. Glad it has been of help to some people and thanks everyone for your contributions!

I'm not seeking maintainer to take over - of course feel free to fork if you'd like to continue developing TsMonad.

Description

This library provides implementations of the most useful monads outside of Haskell (subjectively, this is Maybe and Either). It also provides a strongly-typed emulation of pattern matching to help enforce program correctness.

I won't presume to attempt a monad tutorial here. There are several online - I recommend Douglas Crockford's Monads & Gonads talk.

License

MIT

Usage

This library will work with vanilla ES3 JavaScript with node or in the browser. However, it is far better with TypeScript.

Node:

var TsMonad = require('tsmonad');

Browser:

<script src="node_modules/tsmonad/dist/tsmonad.js"></script>

TypeScript definitions:

/// <reference path="node_modules/tsmonad/dist/tsmonad.d.ts" />

Examples (in TypeScript)

You can see the unit tests for the examples below online here and view the source in test/examples.ts.

Pattern matching emulation

var turns_out_to_be_100 = Maybe.just(10)
    .caseOf({
        just: n => n * n,
        nothing: () => -1
    });

var turns_out_to_be_a_piano = Maybe.nothing<number>()
    .caseOf({
        just: n => n * n,
        nothing: () => -1 // joke, it's negative one not a piano
    });

var turns_out_to_throw_a_compiler_error = Maybe.just(321)
    .caseOf({
        just: n => 999,
        // tsc will tell you that this "does not implement 'nothing'"
        // helping to enforce correct handling of all possible paths
    });

General Maybe usage

The Maybe monad can simplify processing of values that may not exist:

var canRideForFree = user.getAge()  // user might not have provided age, this is a Maybe<number>
    .bind(age => getBusPass(age))   // not all ages have a bus pass, this is a Maybe<BusPass>
    .caseOf({
        just: busPass => busPass.isValidForRoute('Weston'),
        nothing: () => false
    });

Without Maybe, this would be something like:

var canRideForFree,
    age = user.getAge(); // might be null or undefined

if (age) {
    var busPass = getBusPass(age); // might be null or undefined
    if (busPass) {
        canRideForFree = busPass.isValidForRoute('Weston');
    }
}
canRideForFree = false;

Please excuse the messy var scoping and implicit any types in the above. Again, the neat thing about the caseOf method is that it forces you to consider the failure case - it's not always obvious if you're missing a branch of your if-else statement, until it blows up at runtime.

There are some convenience methods in Maybe:

user.getLikesCookies().defaulting(false); // Maybe<false>
user.getLikesCookies().valueOr(false); // false
user.getLikesCookies().valueOrCompute(() => expensiveCalculation());
user.getLikesCookies().valueOrThrow(new Error());

// Maybe.just({ three: 3, hi: 'hi'})
Maybe.sequence<number|string>({ three: Maybe.just(3), hi: Maybe.just('hi') });

// Maybe.nothing
Maybe.sequence<number>({ three: Maybe.just(3), hi: Maybe.nothing() });

General Either usage

var canRideForFree = user.getAge()  // either 42 or 'Information withheld' - type of Either<string,number>
    .bind(age => getBusPass(age))   // either busPass or 'Too young for a bus pass' - type of Either<string,BusPass>
    .caseOf({
        right: busPass => busPass.isValidForRoute('Weston'),
        left: errorMessage => { console.log(errorMessage); return false; }
    });

General Writer usage

Somewhat contrived example of recording arithmetic operations:

var is_true = Writer.writer(['Started with 0'], 0)
    .bind(x => Writer.writer(['+ 8'], x + 8))
    .bind(x => Writer.writer(['- 6', '* 8'], 8 * (x - 6)))
    .caseOf({
        writer: (s, v) => v === 16 && s.join(', ') === 'Started with 0, + 8, - 6, * 8'
    }));

The lift method (fmap)

The lift method takes a lambda, applies it to the wrapped value and calls the unit function of the monad on the result (e.g. for Maybe it calls just). Useful when you want to bind to a function that doesn't return a monad.

var turns_out_to_be_true = Maybe.just(123)
    .lift(n => n * 2)
    .caseOf({
        just: n => n === 246,
        nothing: () => false
    });

Note that for Maybe, if the lifted function returns null or undefined then it returns Nothing rather than wrapping a null in a Just, which is perverse.

FAQ and apologies

Why only Maybe, Either and Writer (so far)?

These monads are the most obviously useful in JavaScript's world of unrestricted mutable state and side effects. I'm currently evaluating which other common monads offer enough benefit to be worth implementing in TypeScript.

Where's monad transformers?

Sorry. One day. But for the moment it's not practicable to do this without support for higher-kinded types.

Is it Fantasy Land conformant?

Yes - there are aliases for Fantasy Land interfaces of Functor and Monad.

"Fantasy land logo"

More Repositories

1

daemons.el

An Emacs UI for managing init system services
Emacs Lisp
99
star
2

Config

Configuration files
Lua
22
star
3

doc2vec-pytorch

Tutorial: implementing doc2vec (paragraph vectors) from scratch in PyTorch
Jupyter Notebook
12
star
4

Computer-Vision-Theremin

An instrument you play by waving your hand in space.
C++
4
star
5

DecomposeGIF

Objective-C
3
star
6

gif-image

Racket code for manipulating GIF images
Racket
3
star
7

cljs-deps-figwheel-main-cider

Example of how to run ClojureScript with tools-deps (CLI tools), figwheel-main and CIDER
Emacs Lisp
3
star
8

ddl-diff

Generates SQL migrations by parsing and diffing DDL
Scala
2
star
9

Bashistrano

A remote server automation and deployment tool in 100 lines of Bash
Shell
2
star
10

K-Nearest-Neighbour

Classifying flowers with KNN in C++11
C++
2
star
11

TweetFilter

Bayesian Filtering for Twitter Spam
Haskell
2
star
12

Regression-Racket

Simple regression machine (Typed) Racket
Racket
1
star
13

org-element-query

XPath-like queries for Org-mode files
Emacs Lisp
1
star
14

F1Ranking

Little experiment applying Elo rating system to F1 drivers
F#
1
star
15

Utilities-Library

All my utility functions, classes, scripts, etc
Racket
1
star
16

Montgomery

Time tracker
TypeScript
1
star
17

CfgMgmt

Personal repository of Personal repository of Chef cookbooks, Vagrantfiles, shell scripts, etc.
Ruby
1
star
18

chancejs---TypeScript-defs

TypeScript
1
star
19

FANN---Languages

Classifying languages with a neural network
Haskell
1
star
20

K-Nearest-Neighbour-Haskell

Classifying flowers with KNN in Haskell
Haskell
1
star
21

ChineseZodiac

Demo project for ASP.NET MVC 2 and SQLite basics
C#
1
star
22

Hnefatafl

Viking chess!
JavaScript
1
star
23

CurryDistribution

Business economics simulation game
Haskell
1
star
24

TDOP

Monadic Pratt parser
Haskell
1
star
25

LoadingPlanes

Passenger embarkment simulated and visualized with OpenGL.
Haskell
1
star