项目作者: teves-castro

项目描述 :
Do like notation for typescript using fp-ts
高级语言: TypeScript
项目地址: git://github.com/teves-castro/ts-do.git
创建时间: 2018-01-20T20:54:15Z
项目社区:https://github.com/teves-castro/ts-do

开源协议:MIT License

下载


Description

This library works as an extension for fp-ts allowing the usage of a haskell like do notation. One can use exec, bind, sequence and into to chain computations on any of the supplied monads.
Each bind or sequence in the computation chain contributes to a threaded context that is available to each subsequent step. The exec function can also be used to perform computations that add nothing to the context for their side-effects.
It is possible to use this with any monads as long as its kind is defined in fp-ts.

Installation

To install the stable version:

  1. yarn add ts-do

Using the extension

Start by importing the extension:

  1. import { some, map, option } from "fp-ts/lib/Option"
  2. import { pipe } from "fp-ts/lib/pipeable"
  3. import { array } from "fp-ts/lib/Array"
  4. import { range, sum } from "ramda"
  5. import * as Do from "ts-do"
  6. const bind = Do.bind(option)
  7. const into = Do.into(option)
  8. const exec = Do.exec(option)
  9. const sequence = Do.sequence(array, option)
  10. const result = pipe(
  11. some(3),
  12. into("x"), // Chains the computation. Creates a context with { x: 3 }
  13. exec(() => some(undefined)), // Chains the computation. Adds nothing to the context
  14. sequence("ys", ({ x }) => range(0, x).map(() => some(1))), // Sequences computations. Adds { ys: [1, 1, 1] } to the context
  15. map(({ x, ys }) => x - sum(ys)),
  16. )
  17. // result === some(0)

Check the test folder for a few more examples.

Building

Clone the repo

  1. git clone git@github.com:teves-castro/ts-do.git

Install dependencies

  1. yarn

Test

  1. yarn run test

Compile

  1. yarn run build

Disclaimer

These kind of operations (do notation) should be done with compiler support, like the special case of async/await for promises, that is included in most major languages these days.

Although these languages are adopting more and more functional programming constructs, sadly more advanced concepts are left out due to not having critical mass to demand it’s implementation.

So, this is an experiment on what can be accomplished without that compiler support. Meaning that if/when this is supported natively by the language itself, certainly with different syntax, this will become obsolete.

Also I make no commitment to evolve the library beyond my own needs, so bear these warnings in mind when using the library.
And of course I appreciate any comments and suggestions on how to improve or on how I completely blundered something.