origamitower / folktale

[not actively maintained!] A standard library for functional programming in JavaScript
https://folktale.origamitower.com/
MIT License
2.04k stars 102 forks source link

Add Haskell-like Record as ADT with derivation #206

Open JSMonk opened 6 years ago

JSMonk commented 6 years ago

Description

To create new data structure in JavaScript we also need to create a constructor function(class syntax sugar). But this way has a couple of problems like a lot of side effects, creating mutable instance and etc. With folktale library i want to use also derivation pattern for my custom data structure to make more consistent and eloquent code. I propose Record as solve of class problem. Haskell example:

    data Person = Person { firstName :: String
                     , lastName :: String
                     , age :: Int
                     } deriving (Show)

   tarantino = Person { firstName = "Quentin"
                 , lastName = "Tarantino"
                 , age = 55 
                 }

    putStrLn . show $ tarantino
    -- ==> Person {firstName = "Quentin", lastName = "Tarantino", age = 55}

Folktale example:

    const { record } = require('folktale/adt/record');
    const Show = require('folktale/adt/record/derivations/debug-representation');

    const Person = record('Person', {
      firstName: String,
      lastName: String,
      age: Number,
    }).derive(Show);

    const tarantino = Person({
      firstName: 'Quentin',
      lastName: 'Tarantino',
      age: 55,
    });

    tarantino.age = 56; // throw TypeError

    console.log(tarantino)
    // ==> Person({ firstName: 'Quentin', lastName: 'Tarantino', age: 55 })

Why?

Folktale provide developer to use type coproduct, but developer has not ability to use type product. We also have union type inside folktale. Developer will have consistence inside project and will lose a way to write mutable data structure with record . In additional, developer will get a stricter and declarative way for type definition.

Additional resources

https://blog.kentcdodds.com/classes-complexity-and-functional-programming-a8dd86903747 https://v1.realworldocaml.org/v1/en/html/records.html - OCaml Records