Skip to content

afrankevych/fp-ts-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fp-ts-demo

Functional programming pillars:

  • Pure functions (referentially transparent)
  • Function composition

Functional program = composition of pure functions

input 
  |> f1() 
  |> f2() 
  |> f3()
output

Fp-ts pipe() and flow() to the rescue!

import {flow} from "fp-ts/functions"

const program = flow(
    f1,
    f2,
    f3
)

program(input)

@see src/pipeFlow.ts

Billion dollar mistake fixed

Considering this code

const data = fetchRemoteData(id)

Is it data? Is it null? Is it undefined? It's superman?

It's Option!

type Option<T> = { _tag: "none" } | { _tag: "some", value: T }

@see src/option.ts

Purifying errors

Considering this code

const compute = (n: number) => n * 2;

compute is pure because it's referentially transparent

const x = compute(3)
const y = 6;

console.log(x === y); // true

What about errors?

const computeF = (n: number) => {
    if (n >= 3) {
        throw new Error("Value too high!")
    }
    
    return n * 2;
};

computeF is not pure because it's not referentially transparent

const x = computeF(3)
const y = 6;

console.log(x === y); // false

Red pill or blue pill?

type Either<T1, T2> = {_tag: "left", value: T1} | {_tag: "right", value: T2};

@see src/either.ts

TODO

  • Add Task examples
  • Add IO examples
  • Add Reader examples
  • Add Magma/Semigroup/Monoid examples
  • Add Functor/Applicative/Monad examples

Resources

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published