Repository: gcanti/fp-ts Branch: master Commit: 09045f5819af Files: 429 Total size: 3.9 MB Directory structure: gitextract_97f0v62q/ ├── .editorconfig ├── .eslintrc.json ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── Bug_report.md │ │ ├── Documentation.md │ │ └── Feature_request.md │ ├── PULL_REQUEST_TEMPLATE.md │ └── workflows/ │ └── main.yml ├── .gitignore ├── .prettierrc ├── .vscode/ │ └── settings.json ├── CHANGELOG.md ├── Do.md ├── LICENSE ├── README.md ├── code2comment.html ├── docs/ │ ├── _config.yml │ ├── _sass/ │ │ └── custom/ │ │ └── custom.scss │ ├── ecosystem.md │ ├── guides/ │ │ ├── HKT.md │ │ ├── code-conventions.md │ │ ├── do-notation.md │ │ ├── index.md │ │ ├── purescript.md │ │ └── upgrade-to-v2.md │ ├── index.md │ ├── learning-resources.md │ └── modules/ │ ├── Alt.ts.md │ ├── Alternative.ts.md │ ├── Applicative.ts.md │ ├── Apply.ts.md │ ├── Array.ts.md │ ├── Bifunctor.ts.md │ ├── BooleanAlgebra.ts.md │ ├── Bounded.ts.md │ ├── BoundedDistributiveLattice.ts.md │ ├── BoundedJoinSemilattice.ts.md │ ├── BoundedLattice.ts.md │ ├── BoundedMeetSemilattice.ts.md │ ├── Category.ts.md │ ├── Chain.ts.md │ ├── ChainRec.ts.md │ ├── Choice.ts.md │ ├── Comonad.ts.md │ ├── Compactable.ts.md │ ├── Console.ts.md │ ├── Const.ts.md │ ├── Contravariant.ts.md │ ├── Date.ts.md │ ├── DistributiveLattice.ts.md │ ├── Either.ts.md │ ├── EitherT.ts.md │ ├── Endomorphism.ts.md │ ├── Eq.ts.md │ ├── Extend.ts.md │ ├── Field.ts.md │ ├── Filterable.ts.md │ ├── FilterableWithIndex.ts.md │ ├── Foldable.ts.md │ ├── FoldableWithIndex.ts.md │ ├── FromEither.ts.md │ ├── FromIO.ts.md │ ├── FromReader.ts.md │ ├── FromState.ts.md │ ├── FromTask.ts.md │ ├── FromThese.ts.md │ ├── Functor.ts.md │ ├── FunctorWithIndex.ts.md │ ├── Group.ts.md │ ├── HKT.ts.md │ ├── HeytingAlgebra.ts.md │ ├── IO.ts.md │ ├── IOEither.ts.md │ ├── IOOption.ts.md │ ├── IORef.ts.md │ ├── Identity.ts.md │ ├── Invariant.ts.md │ ├── JoinSemilattice.ts.md │ ├── Json.ts.md │ ├── Lattice.ts.md │ ├── Magma.ts.md │ ├── Map.ts.md │ ├── MeetSemilattice.ts.md │ ├── Monad.ts.md │ ├── MonadIO.ts.md │ ├── MonadTask.ts.md │ ├── MonadThrow.ts.md │ ├── Monoid.ts.md │ ├── NaturalTransformation.ts.md │ ├── NonEmptyArray.ts.md │ ├── Option.ts.md │ ├── OptionT.ts.md │ ├── Ord.ts.md │ ├── Ordering.ts.md │ ├── Pointed.ts.md │ ├── Predicate.ts.md │ ├── Profunctor.ts.md │ ├── Random.ts.md │ ├── Reader.ts.md │ ├── ReaderEither.ts.md │ ├── ReaderIO.ts.md │ ├── ReaderT.ts.md │ ├── ReaderTask.ts.md │ ├── ReaderTaskEither.ts.md │ ├── ReadonlyArray.ts.md │ ├── ReadonlyMap.ts.md │ ├── ReadonlyNonEmptyArray.ts.md │ ├── ReadonlyRecord.ts.md │ ├── ReadonlySet.ts.md │ ├── ReadonlyTuple.ts.md │ ├── Record.ts.md │ ├── Refinement.ts.md │ ├── Ring.ts.md │ ├── Semigroup.ts.md │ ├── Semigroupoid.ts.md │ ├── Semiring.ts.md │ ├── Separated.ts.md │ ├── Set.ts.md │ ├── Show.ts.md │ ├── State.ts.md │ ├── StateReaderTaskEither.ts.md │ ├── StateT.ts.md │ ├── Store.ts.md │ ├── Strong.ts.md │ ├── Task.ts.md │ ├── TaskEither.ts.md │ ├── TaskOption.ts.md │ ├── TaskThese.ts.md │ ├── These.ts.md │ ├── TheseT.ts.md │ ├── Traced.ts.md │ ├── Traversable.ts.md │ ├── TraversableWithIndex.ts.md │ ├── Tree.ts.md │ ├── Tuple.ts.md │ ├── Unfoldable.ts.md │ ├── ValidationT.ts.md │ ├── Witherable.ts.md │ ├── Writer.ts.md │ ├── WriterT.ts.md │ ├── Zero.ts.md │ ├── boolean.ts.md │ ├── function.ts.md │ ├── index.md │ ├── index.ts.md │ ├── number.ts.md │ ├── pipeable.ts.md │ ├── string.ts.md │ ├── struct.ts.md │ └── void.ts.md ├── docs-ts.json ├── dtslint/ │ ├── Applicative.ts │ ├── Apply.ts │ ├── Array.ts │ ├── Console.ts │ ├── Const.ts │ ├── Either.ts │ ├── Eq.ts │ ├── Functor.ts │ ├── IO.ts │ ├── IOEither.ts │ ├── Identity.ts │ ├── Json.ts │ ├── Map.ts │ ├── Monoid.ts │ ├── NonEmptyArray.ts │ ├── Option.ts │ ├── Ord.ts │ ├── Reader.ts │ ├── ReaderEither.ts │ ├── ReaderT.ts │ ├── ReaderTask.ts │ ├── ReaderTaskEither.ts │ ├── ReadonlyArray.ts │ ├── ReadonlyMap.ts │ ├── ReadonlyNonEmptyArray.ts │ ├── ReadonlyRecord.ts │ ├── ReadonlySet.ts │ ├── Record.ts │ ├── Ring.ts │ ├── Semigroup.ts │ ├── Set.ts │ ├── Show.ts │ ├── StateReaderTaskEither.ts │ ├── Task.ts │ ├── TaskEither.ts │ ├── TaskOption.ts │ ├── Traversable.ts │ ├── Tree.ts │ ├── constrained.ts │ ├── function.ts │ ├── index.d.ts │ ├── index.ts │ ├── pipeable.ts │ └── tsconfig.json ├── examples/ │ ├── fp-ts-to-the-max-I.ts │ ├── fp-ts-to-the-max-II.ts │ └── tsconfig.json ├── package.json ├── perf/ │ ├── Either/ │ │ └── sequenceArray.ts │ ├── IO/ │ │ └── sequenceArray.ts │ ├── Option/ │ │ └── sequenceArray.ts │ ├── ReaderTask/ │ │ └── traverseReadonlyArrayWithIndexSeq.ts │ ├── ReaderTaskEither/ │ │ └── traverseReadonlyArrayWithIndexSeq.ts │ ├── ReadonlyNonEmptyArray.ts/ │ │ └── reverse.ts │ ├── StateReaderTaskEither/ │ │ └── sequenceArray.ts │ ├── Task/ │ │ ├── sequenceArray.ts │ │ ├── stack.ts │ │ └── traverseReadonlyArrayWithIndexSeq.ts │ ├── TaskEither/ │ │ └── traverseReadonlyArrayWithIndexSeq.ts │ ├── TaskOption/ │ │ └── traverseReadonlyArrayWithIndexSeq.ts │ ├── TaskOption.ts/ │ │ └── traverseReadonlyArrayWithIndexSeq.ts │ └── function/ │ ├── flow.ts │ └── pipe.ts ├── scripts/ │ ├── FileSystem.ts │ ├── build.ts │ ├── linter.ts │ ├── pre-publish.ts │ ├── release.ts │ └── run.ts ├── src/ │ ├── Alt.ts │ ├── Alternative.ts │ ├── Applicative.ts │ ├── Apply.ts │ ├── Array.ts │ ├── Bifunctor.ts │ ├── BooleanAlgebra.ts │ ├── Bounded.ts │ ├── BoundedDistributiveLattice.ts │ ├── BoundedJoinSemilattice.ts │ ├── BoundedLattice.ts │ ├── BoundedMeetSemilattice.ts │ ├── Category.ts │ ├── Chain.ts │ ├── ChainRec.ts │ ├── Choice.ts │ ├── Comonad.ts │ ├── Compactable.ts │ ├── Console.ts │ ├── Const.ts │ ├── Contravariant.ts │ ├── Date.ts │ ├── DistributiveLattice.ts │ ├── Either.ts │ ├── EitherT.ts │ ├── Endomorphism.ts │ ├── Eq.ts │ ├── Extend.ts │ ├── Field.ts │ ├── Filterable.ts │ ├── FilterableWithIndex.ts │ ├── Foldable.ts │ ├── FoldableWithIndex.ts │ ├── FromEither.ts │ ├── FromIO.ts │ ├── FromReader.ts │ ├── FromState.ts │ ├── FromTask.ts │ ├── FromThese.ts │ ├── Functor.ts │ ├── FunctorWithIndex.ts │ ├── Group.ts │ ├── HKT.ts │ ├── HeytingAlgebra.ts │ ├── IO.ts │ ├── IOEither.ts │ ├── IOOption.ts │ ├── IORef.ts │ ├── Identity.ts │ ├── Invariant.ts │ ├── JoinSemilattice.ts │ ├── Json.ts │ ├── Lattice.ts │ ├── Magma.ts │ ├── Map.ts │ ├── MeetSemilattice.ts │ ├── Monad.ts │ ├── MonadIO.ts │ ├── MonadTask.ts │ ├── MonadThrow.ts │ ├── Monoid.ts │ ├── NaturalTransformation.ts │ ├── NonEmptyArray.ts │ ├── Option.ts │ ├── OptionT.ts │ ├── Ord.ts │ ├── Ordering.ts │ ├── Pointed.ts │ ├── Predicate.ts │ ├── Profunctor.ts │ ├── Random.ts │ ├── Reader.ts │ ├── ReaderEither.ts │ ├── ReaderIO.ts │ ├── ReaderT.ts │ ├── ReaderTask.ts │ ├── ReaderTaskEither.ts │ ├── ReadonlyArray.ts │ ├── ReadonlyMap.ts │ ├── ReadonlyNonEmptyArray.ts │ ├── ReadonlyRecord.ts │ ├── ReadonlySet.ts │ ├── ReadonlyTuple.ts │ ├── Record.ts │ ├── Refinement.ts │ ├── Ring.ts │ ├── Semigroup.ts │ ├── Semigroupoid.ts │ ├── Semiring.ts │ ├── Separated.ts │ ├── Set.ts │ ├── Show.ts │ ├── State.ts │ ├── StateReaderTaskEither.ts │ ├── StateT.ts │ ├── Store.ts │ ├── Strong.ts │ ├── Task.ts │ ├── TaskEither.ts │ ├── TaskOption.ts │ ├── TaskThese.ts │ ├── These.ts │ ├── TheseT.ts │ ├── Traced.ts │ ├── Traversable.ts │ ├── TraversableWithIndex.ts │ ├── Tree.ts │ ├── Tuple.ts │ ├── Unfoldable.ts │ ├── ValidationT.ts │ ├── Witherable.ts │ ├── Writer.ts │ ├── WriterT.ts │ ├── Zero.ts │ ├── boolean.ts │ ├── function.ts │ ├── index.ts │ ├── internal.ts │ ├── number.ts │ ├── pipeable.ts │ ├── string.ts │ ├── struct.ts │ └── void.ts ├── test/ │ ├── Alternative.ts │ ├── Applicative.ts │ ├── Apply.ts │ ├── Array.ts │ ├── BooleanAlgebra.ts │ ├── Bounded.ts │ ├── BoundedDistributiveLattice.ts │ ├── Choice.ts │ ├── Compactable.ts │ ├── Console.ts │ ├── Const.ts │ ├── Date.ts │ ├── Either.ts │ ├── EitherT.ts │ ├── Endomorphism.ts │ ├── Eq.ts │ ├── Field.ts │ ├── Filterable.ts │ ├── Foldable.ts │ ├── FoldableWithIndex.ts │ ├── Functor.ts │ ├── FunctorWithIndex.ts │ ├── IO.ts │ ├── IOEither.ts │ ├── IOOption.ts │ ├── IORef.ts │ ├── Identity.ts │ ├── Json.ts │ ├── Magma.ts │ ├── Map.ts │ ├── Monoid.ts │ ├── NonEmptyArray.ts │ ├── Option.ts │ ├── OptionT.ts │ ├── Ord.ts │ ├── Ordering.ts │ ├── Predicate.ts │ ├── Random.ts │ ├── Reader.ts │ ├── ReaderEither.ts │ ├── ReaderIO.ts │ ├── ReaderT.ts │ ├── ReaderTask.ts │ ├── ReaderTaskEither.ts │ ├── ReadonlyArray.ts │ ├── ReadonlyMap.ts │ ├── ReadonlyNonEmptyArray.ts │ ├── ReadonlyRecord.ts │ ├── ReadonlySet.ts │ ├── ReadonlyTuple.ts │ ├── Record.ts │ ├── Refinement.ts │ ├── Ring.ts │ ├── Semigroup.ts │ ├── Separated.ts │ ├── Set.ts │ ├── Show.ts │ ├── State.ts │ ├── StateReaderTaskEither.ts │ ├── Store.ts │ ├── Strong.ts │ ├── Task.ts │ ├── TaskEither.ts │ ├── TaskOption.ts │ ├── TaskThese.ts │ ├── These.ts │ ├── Traced.ts │ ├── Traversable.ts │ ├── Tree.ts │ ├── Tuple.ts │ ├── ValidationT.ts │ ├── Witherable.ts │ ├── Writer.ts │ ├── boolean.ts │ ├── function.ts │ ├── index.ts │ ├── number.ts │ ├── pipeable.ts │ ├── string.ts │ ├── struct.ts │ └── util.ts ├── tsconfig.build-es6.json ├── tsconfig.build.json ├── tsconfig.eslint.json ├── tsconfig.json └── vite.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ [*] indent_style = space indent_size = 2 ================================================ FILE: .eslintrc.json ================================================ { "parserOptions": { "project": "./tsconfig.eslint.json" }, "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ], "plugins": ["deprecation", "import", "simple-import-sort"], "rules": { "@typescript-eslint/array-type": ["warn", { "default": "generic", "readonly": "generic" }], "@typescript-eslint/prefer-readonly": "warn", "@typescript-eslint/member-delimiter-style": 0, "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/ban-types": "off", "@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-empty-interface": "off", "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], "prefer-rest-params": "off", "prefer-spread": "off", "deprecation/deprecation": "off", "import/first": "error", "import/no-cycle": "error", "import/newline-after-import": "error", "import/no-duplicates": "error", "import/no-unresolved": "off", "import/order": "off", "simple-import-sort/imports": "error", "no-restricted-syntax": [ "error", { "selector": "CallExpression[callee.property.name='push'] > SpreadElement.arguments", "message": "Do not use spread arguments in Array.push" } ] } } ================================================ FILE: .github/FUNDING.yml ================================================ github: [gcanti] ================================================ FILE: .github/ISSUE_TEMPLATE/Bug_report.md ================================================ --- name: "\U0001F41B Bug report" about: Create a report to help make fp-ts better --- ## 🐛 Bug report ### Current Behavior ### Expected behavior ### Reproducible example ### Suggested solution(s) ### Additional context ### Your environment Which versions of fp-ts are affected by this issue? Did this work in previous versions of fp-ts? | Software | Version(s) | | ---------- | ---------- | | fp-ts | | | TypeScript | | ================================================ FILE: .github/ISSUE_TEMPLATE/Documentation.md ================================================ --- name: "\U0001F41B Documentation" about: Improvements or suggestions of fp-ts documentation --- ## 📖 Documentation ================================================ FILE: .github/ISSUE_TEMPLATE/Feature_request.md ================================================ --- name: "\U0001F680Feature request" about: Suggest an idea for fp-ts --- ## 🚀 Feature request ### Current Behavior ### Desired Behavior ### Suggested Solution ### Who does this impact? Who is this for? ### Describe alternatives you've considered ### Additional context ### Your environment | Software | Version(s) | | ---------- | ---------- | | fp-ts | | | TypeScript | | ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ **Before submitting a pull request,** please make sure the following is done: - Fork [the repository](https://github.com/gcanti/fp-ts) and create your branch from `master`. - Run `npm install` in the repository root. - If you've fixed a bug or added code that should be tested, add tests! - Ensure the test suite passes (`npm test`). **Note**. If you've fixed a bug please link the related issue or, if missing, open an issue before sending a PR. **Note**. If you find a typo in the **documentation**, make sure to modify the corresponding source (docs are generated). **Note**. If you want to send a PR related to `fp-ts@1.x` please create your branch from `1.x` ================================================ FILE: .github/workflows/main.yml ================================================ name: Node.js CI on: push: branches: [master] pull_request: branches: [master] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: jobs: build: runs-on: ubuntu-latest strategy: matrix: node-version: [20.12.2] steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm run build --if-present - run: npm test ================================================ FILE: .gitignore ================================================ *.log node_modules /dist dev .idea coverage docs/examples ================================================ FILE: .prettierrc ================================================ { "semi": false, "singleQuote": true, "printWidth": 120, "trailingComma": "none" } ================================================ FILE: .vscode/settings.json ================================================ { "typescript.tsdk": "./node_modules/typescript/lib", "editor.defaultFormatter": "esbenp.prettier-vscode", "eslint.validate": ["typescript"], "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, "files.insertFinalNewline": true } ================================================ FILE: CHANGELOG.md ================================================ # Changelog > **Tags:** > > - [New Feature] > - [Bug Fix] > - [Breaking Change] > - [Documentation] > - [Internal] > - [Polish] > - [Experimental] > - [Deprecation] **Note**: Gaps between patch versions are faulty/broken releases. **Note**: A feature tagged as Experimental is in a high state of flux, you're at risk of it changing without notice. # 2.16.11 **Bug Fix** Fix Option.getOrd definition, #1963 # 2.16.10 **Polish** Add apFirstW and apSecondW to ReaderTask, #1958 # 2.16.9 **Polish** Support `strictBuiltinIteratorReturn`, #1949 # 2.16.8 **Polish** Remove useless pure comment, closes #1937 # 2.16.7 **Polish** Add tap for Identity #1943 # 2.16.6 **Polish** Allow dependencies to be widen when using orLeft #1938 # 2.16.5 **Polish** Resolved a RangeError where the maximum call stack size was exceeded when invoking `chainWithIndex`, #1931 # 2.16.4 **Polish** Fix `__PURE__` annotation placement, closes #1926 # 2.16.3 **Polish** `Either.ts`: `toError`: Don't fail when a value can't be converted to a primitive, #1924 # 2.16.2 **Polish** Fix `"__PURE__"` annotation placement #1919, closes #1916 # 2.16.1 **Bug Fix** - fix type signature of `ReaderTaskEither.tapReaderIO`, #1895 # 2.16.0 - `tapEither` (dual) (aka `chainFirstEitherK` / `chainFirstEitherKW`) https://github.com/gcanti/fp-ts/pull/1864 - `tapIO` (dual) (aka `chainFirstIOK`) https://github.com/gcanti/fp-ts/pull/1865 - `as` / `asUnit` https://github.com/gcanti/fp-ts/pull/1867 - `tapTask` (dual) (aka `chainFirstTaskK`) https://github.com/gcanti/fp-ts/pull/1869 - `mapError` (dual) (aka `mapLeft`) https://github.com/gcanti/fp-ts/pull/1870 - `mapBoth` (dual) (aka `bimap`) https://github.com/gcanti/fp-ts/pull/1872 - `tapReader` (dual) (aka `chainFirstReaderK` / `chainFirstIReaderKW`) https://github.com/gcanti/fp-ts/pull/1871 - `tapReaderEither` (dual) (aka `chainFirstReaderEitherK` / `chainFirstEitherKW`) https://github.com/gcanti/fp-ts/pull/1873 - `tapReaderIO` (dual) (aka `chainFirstReaderIOK`) https://github.com/gcanti/fp-ts/pull/1873 - `tapReaderTask` (dual) (aka `chainFirstReaderTaskK`) https://github.com/gcanti/fp-ts/pull/1873 - `tapTaskEither` (dual) (aka `chainFirstTaskEitherK` / `chainFirstTaskEitherKW`) https://github.com/gcanti/fp-ts/pull/1873 - `flatMapReaderTask` (dual) (aka `chainReaderTaskK` / `chainReaderTaskKW`) https://github.com/gcanti/fp-ts/pull/1874 - `flatMapTaskEither` (dual) (aka `chainTaskEitherK` / `chainTaskEitherKW`) https://github.com/gcanti/fp-ts/pull/1874 - `flatMapIO` (dual) (aka `chainIOK`) https://github.com/gcanti/fp-ts/pull/1874 - `Option.orElse` (dual) (aka `alt` / `altW`) https://github.com/gcanti/fp-ts/pull/1868 - `flatMapTask` (dual) (aka `chainTaskK`) https://github.com/gcanti/fp-ts/pull/1876 - `flatMapReader` (dual) (aka `chainReaderK` / `chainReaderKW`) https://github.com/gcanti/fp-ts/pull/1876 - `flatMapReaderIO` (dual) (aka `chainReaderIOK` / `chainReaderIOKW`) https://github.com/gcanti/fp-ts/pull/1879 - `flatMap*` (aka `chain*K` / `chain*KW`) https://github.com/gcanti/fp-ts/pull/1880 # 2.15.0 **New Feature** - `function` - add `LazyArg` - add `tap` to - `Either` - `IO` - `IOEither` - `IOOption` - `Option` - `Reader` - `ReaderEither` - `ReaderIO` - `ReaderTask` - `ReaderTaskEither` - `State` - `StateReaderTaskEither` - `Task` - `TaskEither` - `TaskOption` - add `flatMapNullable` (dual) to - `Either` - `IOEither` - `ReaderEither` - `ReaderTaskEither` - `StateReaderTaskEither` - `TaskEither` - add `flatMapOption` (dual) to - `Either` - `IOEither` - `ReaderEither` - `ReaderTaskEither` - `StateReaderTaskEither` - `TaskEither` - add `liftNullable` to - `Either` - `IOEither` - `ReaderEither` - `ReaderTaskEither` - `StateReaderTaskEither` - `TaskEither` - add `liftOption` to - `Either` - `IOEither` - `ReaderEither` - `ReaderTaskEither` - `StateReaderTaskEither` - `TaskEither` - add `flatMapEither` (dual) to - `IOEither` - `ReaderEither` - `ReaderTaskEither` - `TaskEither` - `Array` - add index to `flatMap` - `NonEmptyArray` - add index to `flatMap` - `ReadonlyArray` - add index to `flatMap` - `ReadonlyNonEmptyArray` - add index to `flatMap` # 2.14.0 **New Feature** - add `flatMap` to - `Either` - `IOEither` - `Reader` - `ReaderEither` - `ReaderIO` - `ReaderTask` - `ReaderTaskEither` - `StateReaderTaskEither` - `TaskEither` - `NonEmptyArray` - `ReadonlyNonEmptyArray` - `Tree` - `Array` - `Identity` - `IO` - `IOOption` - `Option` - `ReadonlyArray` - `State` - `Task` - `TaskOption` # 2.13.2 - add `chainOptionKW`, #1846 (@DenisFrezzato) # 2.13.1 - **New Feature** - new modules: - `ReaderIO`, #1738 (@sukovanej) - do notation: - add `let` helpers, #1725 (@Punie) - `Alternative` - add `getAlternativeMonoid`, #1717 (@willheslam) - `function` - `flip` is now curried, #1748 (@thewilkybarkid) - `pipeable` - add pipeable helpers, #1764 (@gcanti) - `alt` - `ap` - `bimap` - `chain` - `compose` - `contramap` - `extend` - `filter` - `filterMap` - `filterMapWithIndex` - `filterWithIndex` - `foldMap` - `foldMapWithIndex` - `map` - `mapLeft` - `mapWithIndex` - `partition` - `partitionMap` - `partitionMapWithIndex` - `partitionWithIndex` - `promap` - `reduce` - `reduceRight` - `reduceRightWithIndex` - `reduceWithIndex` - `ReaderTask` - add `ReaderIO` constructors/combinators, #1773 (@thewilkybarkid) - `ReaderTaskEither` - add `ReaderIO` constructors/combinators, #1774 (@thewilkybarkid) - `TaskEither` - add `chainTaskOptionKW`, #1744 (@AmirabbasJ) - **Polish** - backport from v3 some handy defaults defined in natural transformations/combinators/constructors (@gcanti) - fix wrong type parameter order: - `FromIO` - `chainIOK` - `FromTask` - `chainTaskK` - `chainFirstTaskK` - `Whiterable` - `FilterE1` - `TheseT` - `both` - `Either` - `apFirstW` - `apSecondW` - `IOEither` - `apFirstW` - `apSecondW` - `Reader` - `apFirstW` - `apSecondW` - `ReaderEither` - `apFirstW` - `apSecondW` - `ReaderTaskEither` - `apFirstW` - `apSecondW` - `StateReaderTaskEither` - `apFirstW` - `apSecondW` - `TaskEither` - `apFirstW` - `apSecondW` - `Apply` - add `ap` overloadings, #1721 (@waynevanson) - `Either` - remove useless type parameter in `exists` (@gcanti) - `ReadonlyRecord` - fix `fromEntries` return type, closes #1745 (@gcanti) - `TaskEither` - fix `fromPredicate` signature (@gcanti) - `These` - add missing `fromPredicate` (@gcanti) - remove useless type parameter in `exists` (@gcanti) - `Traversable` - add more overloadings to traverse / sequence helpers, #1758 (@gcanti) - `Writer` - `getChain` requires a `Semigroup` instead of a `Monoid` (@gcanti) - **Deprecation** - `function` - deprecate uncurried `flip` function, #1748 (@thewilkybarkid) # 2.12.2 - **Polish** - `ReadonlyRecord` / `Record` - add `Applicative4` overloadings to `traverse` / `traverseWithIndex`, #1733 (@mlegenhausen) # 2.12.1 - **Bug Fix** - `ReadonlyRecord` - fix `traverseWithIndex` implementation, #1704 (@waynevanson) # 2.12.0 - **New Feature** - add `IOOption` module (@gcanti) - `Array` - add `intercalate`, #1678 (@thewilkybarkid) - `Bounded` - add `clamp` (@gcanti) - add `reverse` (@gcanti) - `Either` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - `EitherT` - add `chainNullableK`, #1619 (@cwstra) - add `fromNullable`, #1619 (@cwstra) - add `fromNullableK`, #1619 (@cwstra) - `FromEither` - add `chainFirstEitherK` (@gcanti) - `IOEither` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - add `chainFirstEitherK` (@gcanti) - add `chainFirstEitherKW` (@gcanti) - add `orElseFirstIOK`, #1655 (@thewilkybarkid) - add `bracketW`, #1627 (@thomasvargiu) - `NonEmptyArray` - add `intercalate`, #1678 (@thewilkybarkid) - `Option` - add `chainFirstEitherK` (@gcanti) - `Ordering` - add `matchW`, #1535 (@mlegenhausen) - `Reader` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - `ReaderEither` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - add `chainFirstEitherK` (@gcanti) - add `chainFirstEitherKW` (@gcanti) - `ReaderTaskEither` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - add `chainFirstEitherK`, #1562 (@DenisFrezzato) - add `chainFirstEitherKW`, #1562 (@DenisFrezzato) - add `bracketW`, #1627 (@thomasvargiu) - add `chainNullableK` (@gcanti) - add `fromNullable` (@gcanti) - add `fromNullableK` (@gcanti) - `ReadonlyArray` - add `intercalate`, #1678 (@thewilkybarkid) - `ReadonlyNonEmptyArray` - add `intercalate`, #1678 (@thewilkybarkid) - `ReadonlyRecord` - add `toEntries`, #1552 (@bravely) - add `fromEntries`, #1552 (@bravely) - `Record` - add `toEntries`, #1552 (@bravely) - add `fromEntries`, #1552 (@bravely) - `StateReaderTaskEither` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - add `chainFirstEitherK` (@gcanti) - add `chainFirstEitherKW` (@gcanti) - `TaskEither` - add `apFirstW`, #1564 (@DenisFrezzato) - add `apSecondW`, #1564 (@DenisFrezzato) - add `chainFirstEitherK`, #1659 (@vinassefranche) - add `chainFirstEitherKW`, #1659 (@vinassefranche) - add `orElseFirstIOK`, #1655 (@thewilkybarkid) - add `orElseFirstTaskK`, #1655 (@thewilkybarkid) - add `bracketW`, #1627 (@thomasvargiu) - add `chainNullableK`, #1619 (@cwstra) - add `fromNullable`, #1619 (@cwstra) - add `fromNullableK`, #1619 (@cwstra) - `TaskOption` - add `fromEitherK` (@gcanti) - add `chainEitherK` (@gcanti) - add `chainFirstEitherK` (@gcanti) # 2.11.10 - **Polish** - `TaskEither` / `TaskOption` - now `tryCatch` / `tryCatchK` will catch synchronous errors too, #1676 (@thewilkybarkid) # 2.11.9 - **Polish** - add `Refinement` overload to 'every' functions, #1681 (@mlegenhausen) # 2.11.8 - **Polish** - Add missing pure annotations, #1658 (@OliverJAsh) # 2.11.7 - **Polish** - more `Functor.map` overloadings, closes #1623 (@gcanti) # 2.11.6 - **Polish** - `ReaderEither` - `orElseFirstW`: intersect dependencies like `orElseW` (@gcanti) - `ReaderTaskEither` - `orElseFirstW`: intersect dependencies like `orElseW`, #1635 (@OliverJAsh) # 2.11.5 - **Polish** - more curried `elem` overloads, #1602 (@ammut) # 2.11.4 - **Polish** - fix `chainNullableK` signature, #1589 (@bwlt) - stack safety for `Task` via microtasks suspension, #1591 (@mikearnaldi) # 2.11.3 - **Polish** - pipe: fix v8 performance cliff for >10 case stmts, #1585 (@pbadenski) # 2.11.2 - **Polish** - Add/fix pure comments, #1555 (@OliverJAsh) # 2.11.1 - **Deprecation** - `Array` - deprecate `range`, use `NonEmptyArray` module instead. - `function` - deprecate `Endomorphism`, use `Endomorphism` module instead. - deprecate `getEndomorphismMonoid`, use `Endomorphism` module instead. - deprecate `Predicate`, use `Predicate` module instead. - deprecate `not`, use `Predicate` module instead. - deprecate `Refinement`, use `Refinement` module instead. - `Monoid` - deprecate `monoidVoid`, use `void` module instead. - `NonEmptyArray` - deprecate `groupSort` (it's just `sort` followed by `group`) - `Option` - deprecate `getRefinement`, use `Refinement` module instead. - deprecate `getFirstMonoid`, use `getMonoid` module instead. - deprecate `getLastMonoid`, use `getMonoid` module instead. - `ReadonlyArray` - deprecate `range`, use `ReadonlyNonEmptyArray` module instead. - `ReadonlyNonEmptyArray` - deprecate `groupSort` (it's just `sort` followed by `group`) - `Record` / `ReadonlyRecord`: deprecate overloads without `Ord` constraint (@anthonyjoeseph): - `collect` - `reduce` - `foldMap` - `reduceRight` - `reduceWithIndex` - `foldMapWithIndex` - `reduceRightWithIndex` - `getShow` - deprecate `Foldable` in favour of `getFoldable` (@anthonyjoeseph) - deprecate `FoldableWithIndex` in favour of `getFoldableWithIndex` (@anthonyjoeseph) - deprecate `Traversable` in favour of `getTraversable` (@anthonyjoeseph) - deprecate `TraversableWithIndex` in favour of `getTraversableWithIndex` (@anthonyjoeseph) - deprecate `Witherable` in favour of `getWitherable` (@anthonyjoeseph) - `Semigroup` - deprecate `semigroupVoid`, use `void` module instead. - **New Feature** - add `Endomorphism` module - add `Predicate` module - add `Refinement` module - add `FromState` module - add `FromThese` module - add `void` module - add `FromReader` module - add `NaturalTransformation` module - add `Zero` module - `Alt` - add `altAll` - `Alternative` - add `altAll` - `Array` - add `prependW`, `appendW` (@thewilkybarkid) - add `fromOption`, `fromPredicate` (@cdimitroulas) - add `filterE` - add `ChainRecDepthFirst` instance (@qlonik) - add `chainRecDepthFirst` - add `ChainRecBreadthFirst` instance (@qlonik) - add `chainRecBreadthFirst` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `fromEither` - add `FromEither` instance - add `fromEitherK` - make `isEmpty` a user defined guard - add `concat` / `concatW` - add `match`, `matchW`, `matchLeftW`, `matchRightW` - add `fromOptionK` - add `Zero` instance - add `guard` constructor - add `exists` alias - `boolean` - add `isBoolean` - `Either` - add `chainOptionK` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `EitherT` - add `orElseFirst` - add `orLeft` - `function` - add `SK` (@cdimitroulas) - add `apply` - `IO` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `IOEither` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `Magma` - add `reverse` - add `filterFirst` - add `filterSecond` - add `endo` - add `concatAll` - `Map` - add `union` - add `intersection` - add `difference` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `getFoldable` - add `foldMap` - add `reduceRight` - add `reduceWithIndex` - add `foldMapWithIndex` - add `reduceRightWithIndex` - `NonEmptyArray` - add `matchLeft`, `matchRight`, `modifyHead`, `modifyLast` (@cdimitroulas) - add `union` - add `getUnionSemigroup` - add `makeBy` - add `range` - make `concat` pipeable - `number` - add `MagmaSub` - add `isNumber` - `string` - add `isString` - `Option` - add `FromEither` instance - add `fromEitherK` - add `chainEitherK` - add `Zero` instance - add `guard` constructor - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `Ord` - add `trivial` instance - add `equals` - `Reader` - add `asksReaderW`, `asksReader` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `ReaderEither` - add `asksReaderEitherW`, `asksReaderEither` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `chainReaderKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `ReaderTask` - add `asksReaderTaskW`, `asksReaderTask` - add `chainReaderKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `ReaderTaskEither` - add `asksReaderTaskEitherW`, `asksReaderTaskEither` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `fromReaderTaskK` - add `fromReaderEitherK` - add `chainReaderKW` - add `chainReaderTaskK`, `chainReaderTaskKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `chainFirstReaderTaskK`, `chainFirstReaderTaskKW` - add `chainReaderEitherK`, `chainReaderEitherKW` - add `chainFirstReaderEitherK`, `chainFirstReaderEitherKW` - add `chainFirstTaskEitherK`, `chainFirstTaskEitherKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `ReadonlyArray` - add `prependW`, `appendW` (@thewilkybarkid) - add `filterE` - add `ChainRecDepthFirst` instance (@qlonik) - add `chainRecDepthFirst` - add `ChainRecBreadthFirst` instance (@qlonik) - add `chainRecBreadthFirst` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `fromOption` - add `fromPredicate` - add `fromEither` - add `FromEither` instance - add `fromEitherK` - make `isEmpty` a user defined guard - add `concat` / `concatW` - add `match`, `matchW`, `matchLeftW`, `matchRightW` - add `fromOptionK` - add `Zero` instance - add `guard` constructor - add `exists` alias - `ReadonlyMap` - add `union` - add `intersection` - add `difference` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `reduce` - add `foldMap` - add `reduceRight` - add `reduceWithIndex` - add `foldMapWithIndex` - add `reduceRightWithIndex` - `ReadonlyNonEmptyArray` - add `matchLeft`, `matchRight`, `modifyHead`, `modifyLast` (@cdimitroulas) - add `union` - add `getUnionSemigroup` - add `makeBy` - add `range` - make `concat` pipeable - `ReadonlyRecord` - add `union` (@anthonyjoeseph) - add `intersection` (@anthonyjoeseph) - add `difference` (@anthonyjoeseph) - add `getUnionSemigroup` (@anthonyjoeseph) - add `getUnionMonoid` (@anthonyjoeseph) - add `getIntersectionSemigroup` (@anthonyjoeseph) - add `getDifferenceMagma` (@anthonyjoeseph) - `ReadonlySet` - add `getUnionSemigroup` - add `getDifferenceMagma` - `Record` - add `union` - add `intersection` - add `difference` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - `Set` - add `getUnionSemigroup` - add `getDifferenceMagma` - `State` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `StateReaderTaskEither` - add `fromStateK` - add `chainStateK` - add `local` - add `asksStateReaderTaskEitherW`, `asksStateReaderTaskEither` - add `chainReaderKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `string` - add `toUpperCase` - add `toLowerCase` - add `replace` - add `split` - add `trim` - add `trimLeft` - add `trimRight` - add `includes` - add `startsWith` - add `endsWith` - add `slice` - `struct` - add `evolve` - `Task` - add `ApT` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `TaskEither` - add `fromTaskOption` (@thewilkybarkid) - add `fromTaskOptionK` - add `chainTaskOptionK` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `TaskOption` - add `fromTaskEither` (@thewilkybarkid) - add `Zero` instance - add `guard` constructor - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - add missing `FromEither` instance - `TaskThese` - add `ApT` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `These` - add `elem` - add `exists` - add `ApT` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `Tree` - add `exists` - `Witherable` - add `filterE`, #1458 (@vinassefranche) - add `wiltDefault` - add `witherDefault` - **Polish** - remove unnecessary type parameters - `Either` - `isLeft` - `isRight` - `Option` - `isNone` - `These` - `isLeft` - `isRight` # 2.11.0-rc.2 - `string` - `split` now returns a `ReadonlyNonEmptyArray` - `TaskOption` - add missing `FromEither` instance - some signature changes in `2.11.0-rc.1` caused type inference issues - `Array` / `ReadonlyArray` - revert `isOutOfBound` signature change - revert `isEmpty` signature change - revert `size` signature change - `Either` - revert `exists` signature change - revert `elem` signature change - `These` - revert `exists` signature change - revert `elem` signature change - `NonEmptyArray` / `ReadonlyNonEmptyArray` - revert `isOutOfBound` signature change - `Set` / `ReadonlySet` - revert `isEmpty` signature change - revert `size` signature change - `Map` / `ReadonlyMap` - revert `isEmpty` signature change - revert `size` signature change # 2.11.0-rc.1 - **Deprecation** - `Array` - deprecate `range`, use `NonEmptyArray` module instead. - `function` - deprecate `Endomorphism`, use `Endomorphism` module instead. - deprecate `getEndomorphismMonoid`, use `Endomorphism` module instead. - deprecate `Predicate`, use `Predicate` module instead. - deprecate `not`, use `Predicate` module instead. - deprecate `Refinement`, use `Refinement` module instead. - `Monoid` - deprecate `monoidVoid`, use `void` module instead. - `NonEmptyArray` - deprecate `groupSort` (it's just `sort` followed by `group`) - `Option` - deprecate `getRefinement`, use `Refinement` module instead. - deprecate `getFirstMonoid`, use `getMonoid` module instead. - deprecate `getLastMonoid`, use `getMonoid` module instead. - `ReadonlyArray` - deprecate `range`, use `ReadonlyNonEmptyArray` module instead. - `ReadonlyNonEmptyArray` - deprecate `groupSort` (it's just `sort` followed by `group`) - `Record` / `ReadonlyRecord`: deprecate overloads without `Ord` constraint (@anthonyjoeseph): - `collect` - `reduce` - `foldMap` - `reduceRight` - `reduceWithIndex` - `foldMapWithIndex` - `reduceRightWithIndex` - `getShow` - deprecate `Foldable` in favour of `getFoldable` (@anthonyjoeseph) - deprecate `FoldableWithIndex` in favour of `getFoldableWithIndex` (@anthonyjoeseph) - deprecate `Traversable` in favour of `getTraversable` (@anthonyjoeseph) - deprecate `TraversableWithIndex` in favour of `getTraversableWithIndex` (@anthonyjoeseph) - deprecate `Witherable` in favour of `getWitherable` (@anthonyjoeseph) - `Semigroup` - deprecate `semigroupVoid`, use `void` module instead. - **New Feature** - add `Endomorphism` module - add `Predicate` module - add `Refinement` module - add `FromState` module - add `FromThese` module - add `void` module - add `FromReader` module - add `NaturalTransformation` module - add `Zero` module - `Alt` - add `altAll` - `Alternative` - add `altAll` - `Array` - add `prependW`, `appendW` (@thewilkybarkid) - add `fromOption`, `fromPredicate` (@cdimitroulas) - add `filterE` - add `ChainRecDepthFirst` instance (@qlonik) - add `chainRecDepthFirst` - add `ChainRecBreadthFirst` instance (@qlonik) - add `chainRecBreadthFirst` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `fromEither` - add `FromEither` instance - add `fromEitherK` - make `isEmpty` a user defined guard - add `concat` / `concatW` - add `match`, `matchW`, `matchLeftW`, `matchRightW` - add `fromOptionK` - add `Zero` instance - add `guard` constructor - add `exists` alias - `boolean` - add `isBoolean` - `Either` - add `chainOptionK` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `EitherT` - add `orElseFirst` - add `orLeft` - `function` - add `SK` (@cdimitroulas) - add `apply` - `IO` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `IOEither` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `Magma` - add `reverse` - add `filterFirst` - add `filterSecond` - add `endo` - add `concatAll` - `Map` - add `union` - add `intersection` - add `difference` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `getFoldable` - add `foldMap` - add `reduceRight` - add `reduceWithIndex` - add `foldMapWithIndex` - add `reduceRightWithIndex` - `NonEmptyArray` - add `matchLeft`, `matchRight`, `modifyHead`, `modifyLast` (@cdimitroulas) - add `union` - add `getUnionSemigroup` - add `makeBy` - add `range` - make `concat` pipeable - `number` - add `MagmaSub` - add `isNumber` - `string` - add `isString` - `Option` - add `FromEither` instance - add `fromEitherK` - add `chainEitherK` - add `Zero` instance - add `guard` constructor - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `Ord` - add `trivial` instance - add `equals` - `Reader` - add `asksReaderW`, `asksReader` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `ReaderEither` - add `asksReaderEitherW`, `asksReaderEither` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `chainReaderKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `ReaderTask` - add `asksReaderTaskW`, `asksReaderTask` - add `chainReaderKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `ReaderTaskEither` - add `asksReaderTaskEitherW`, `asksReaderTaskEither` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `fromReaderTaskK` - add `fromReaderEitherK` - add `chainReaderKW` - add `chainReaderTaskK`, `chainReaderTaskKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `chainFirstReaderTaskK`, `chainFirstReaderTaskKW` - add `chainReaderEitherK`, `chainReaderEitherKW` - add `chainFirstReaderEitherK`, `chainFirstReaderEitherKW` - add `chainFirstTaskEitherK`, `chainFirstTaskEitherKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `ReadonlyArray` - add `prependW`, `appendW` (@thewilkybarkid) - add `filterE` - add `ChainRecDepthFirst` instance (@qlonik) - add `chainRecDepthFirst` - add `ChainRecBreadthFirst` instance (@qlonik) - add `chainRecBreadthFirst` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `fromOption` - add `fromPredicate` - add `fromEither` - add `FromEither` instance - add `fromEitherK` - make `isEmpty` a user defined guard - add `concat` / `concatW` - add `match`, `matchW`, `matchLeftW`, `matchRightW` - add `fromOptionK` - add `Zero` instance - add `guard` constructor - add `exists` alias - `ReadonlyMap` - add `union` - add `intersection` - add `difference` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - add `reduce` - add `foldMap` - add `reduceRight` - add `reduceWithIndex` - add `foldMapWithIndex` - add `reduceRightWithIndex` - `ReadonlyNonEmptyArray` - add `matchLeft`, `matchRight`, `modifyHead`, `modifyLast` (@cdimitroulas) - add `union` - add `getUnionSemigroup` - add `makeBy` - add `range` - make `concat` pipeable - `ReadonlyRecord` - add `union` (@anthonyjoeseph) - add `intersection` (@anthonyjoeseph) - add `difference` (@anthonyjoeseph) - add `getUnionSemigroup` (@anthonyjoeseph) - add `getUnionMonoid` (@anthonyjoeseph) - add `getIntersectionSemigroup` (@anthonyjoeseph) - add `getDifferenceMagma` (@anthonyjoeseph) - `ReadonlySet` - add `getUnionSemigroup` - add `getDifferenceMagma` - `Record` - add `union` - add `intersection` - add `difference` - add `getUnionSemigroup` - add `getUnionMonoid` - add `getIntersectionSemigroup` - add `getDifferenceMagma` - `Set` - add `getUnionSemigroup` - add `getDifferenceMagma` - `State` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `StateReaderTaskEither` - add `fromStateK` - add `chainStateK` - add `local` - add `asksStateReaderTaskEitherW`, `asksStateReaderTaskEither` - add `chainReaderKW` - add `chainFirstReaderK`, `chainFirstReaderKW` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `string` - add `toUpperCase` - add `toLowerCase` - add `replace` - add `split` - add `trim` - add `trimLeft` - add `trimRight` - add `includes` - add `startsWith` - add `endsWith` - add `slice` - `struct` - add `evolve` - `Task` - add `ApT` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `TaskEither` - add `fromTaskOption` (@thewilkybarkid) - add `fromTaskOptionK` - add `chainTaskOptionK` - add `orElseFirst` / `orElseFirstW` - add `orLeft` - add `flattenW` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `TaskOption` - add `fromTaskEither` (@thewilkybarkid) - add `Zero` instance - add `guard` constructor - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `TaskThese` - add `ApT` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - add `traverseReadonlyNonEmptyArrayWithIndexSeq` - add `traverseReadonlyArrayWithIndexSeq` - `These` - add `elem` - add `exists` - add `ApT` - add `traverseReadonlyNonEmptyArrayWithIndex` - add `traverseReadonlyArrayWithIndex` - `Tree` - add `exists` - `Witherable` - add `filterE`, #1458 (@vinassefranche) - add `wiltDefault` - add `witherDefault` - **Polish** - remove unnecessary type parameters - `Either` - `exists` - `isLeft` - `isRight` - `elem` - `Option` - `isNone` - `These` - `isLeft` - `isRight` - `Set` / `ReadonlySet` - `isEmpty` - `size` - `Array` / `ReadonlyArray` - `isEmpty` - `isOutOfBound` - `size` - `Map` / `ReadonlyMap` - `isEmpty` - `size` - `NonEmptyArray` / `ReadonlyNonEmptyArray` - `isOutOfBound` # 2.10.5 - **Bug Fix** - `StateT` - fix typo in `fromF`, #1503 (@DKurilo) # 2.10.4 - **Bug Fix** - `altW` left type is too wide in `Either`-based data types, #1488 (@wmaurer) # 2.10.3 - **Bug Fix** - `StateReaderTaskEither` - `traverseArrayWithIndex` does not pass the output state from each step to the subsequent step, #1486 # 2.10.2 - **Bug Fix** - `Record` - `hasOwnProperty` should be an alias of `ReadonlyRecord.hasOwnProperty` # 2.10.1 - **Bug Fix** - rename `hasOwnProperty` in `internal` module, #1481 (@OliverJAsh) # 2.10.0 - **Deprecations** - deprecate `pipeable` module, use the specific helpers instead - deprecate `ValidationT` module, use `EitherT` instead - deprecate "mega instances", use small, specific instances instead - deprecate the old monad transformers, use the specific helpers instead - `Applicative` - deprecate `getApplicativeComposition`, use `ap` helper instead - `Array` - deprecate `prependToAll`, use `prependAll` instead - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - deprecate `empty` - `BooleanAlgebra` - deprecate `booleanAlgebraBoolean`, use `boolean.BooleanAlgebra` instead - deprecate `getFunctionBooleanAlgebra`, use `function.getBooleanAlgebra` instead - deprecate `getDualBooleanAlgebra`, use `reverse` instead - `Bounded` - deprecate `boundedNumber`, use `number.Bounded` instead - `Choice` - deprecate `splitChoice` in favour of `split` - deprecate `fanin` in favour of `fanIn` - `Compactable` - deprecate `getCompactableComposition`, use `compact`, `separate` helpers instead - deprecate `Separated`, use `Separated.Separated` instead - `Either` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getValidationSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getValidationMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getValidation`, use `getApplicativeValidation` and `getAltValidation` instead - deprecate `Json` type, use the `Json` module instead - deprecate `parseJSON` type, use the `Json` module instead - deprecate `stringifyJSON` type, use the `Json` module instead - `Eq` - deprecate `eqBoolean`, use `boolean.Eq` instead - deprecate `eqString`, use `string.Eq` instead - deprecate `eqNumber`, use `number.Eq` instead - deprecate `eqDate`, use `Date.Eq` instead - deprecate `getStructEq`, use `struct` instead - deprecate `getTupleEq`, use `tuple` instead - `Filterable` - deprecate `getFilterableComposition`, use `filter`, `filterMap`, `partition`, `partitionMap` helpers instead - `Foldable` - deprecate `toArray` in favour of `toReadonlyArray` - deprecate `getFoldableComposition`, use `reduce`, `foldMap`, `reduceRight` helpers instead - `FoldableWithIndex` - deprecate `getFoldableWithIndexComposition`, use `reduceWithIndex`, `foldMapWithIndex`, `reduceRightWithIndex` helpers instead - `Functor` - deprecate `getFunctorComposition`, use `map` helper instead - `FunctorWithIndex` - deprecate `getFunctorWithIndexComposition`, use `mapWithIndex` helper instead - `IO` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `fromIO` - `IOEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - daprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getIOValidation`, use `getApplicativeIOValidation` and `getAltIOValidation` instead - `Map` - deprecate `insertAt` in favour of `upsertAt` - deprecate `empty` - `Monoid` - deprecate `monoidAll`, use `boolean.MonoidAll` instead - deprecate `monoidAny`, use `boolean.MonoidAny` instead - deprecate `getFunctionMonoid`, use `function.getMonoid` instead - deprecate `getEndomorphismMonoid`, use `function.getEndomorphismMonoid` instead (**Note**. The execution order in `function.getEndomorphismMonoid` is reversed) - deprecate `monoidString`, use `string.Monoid` instead - deprecate `monoidSum`, use `number.MonoidSum` instead - deprecate `monoidProduct`, use `number.MonoidProduct` instead - deprecate `fold`, use `concatAll` instead - deprecate `getMeetMonoid`, use `min` instead - deprecate `getJoinMonoid`, use `max` instead - deprecate `getDualMonoid`, use `reverse` instead - deprecate `getStructMonoid`, use `struct` instead - deprecate `getTupleMonoid`, use `tuple` instead - `NonEmptyArray` - deprecate `fold`, use `concatAll` instead - deprecate `prependToAll`, use `prependAll` instead - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - deprecate `uncons` in favour of `unprepend` - deprecate `unsnoc` in favour of `unappend` - deprecate `filter` in favour of `Array`'s `filter` - deprecate `filterWithIndex` in favour of `Array`'s `filterWithIndex` - `Option` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - `Ord` - deprecate `ordBoolean`, use `boolean.Ord` instead - deprecate `ordString`, use `string.Ord` instead - deprecate `ordNumber`, use `number.Ord` instead - deprecate `ordDate`, use `Date.Ord` instead - deprecate `getDualOrd`, use `reverse` instead - deprecate `getTupleOrd`, use `tuple` instead - `Ordering` - deprecate `eqOrdering`, use `Eq` instead - deprecate `monoidOrdering`, use `Monoid` instead - deprecate `invert` in favour of `reverse` - `Ring` - deprecate `getFunctionRing`, use `function.getRing` instead - `Reader` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - `ReaderEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getReaderValidation`, use `getApplicativeReaderValidation` and `getAltReaderValidation` instead - deprecate `local`, Use `Reader`'s `local` instead - `ReaderTask` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `run` - deprecate `local`, Use `Reader`'s `local` instead - `ReaderTaskEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getReaderTaskValidation`, use `getApplicativeReaderTaskValidation` and `getAltReaderTaskValidation` instead - deprecate `run` - deprecate `local`, Use `Reader`'s `local` instead - `ReaderTaskEither` - deprecate `run` - `ReadonlyArray` - deprecate `prependToAll`, use `prependAll` instead - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - `ReadonlyNonEmptyArray` - deprecate `fold`, use `concatAll` instead - deprecate `prependToAll`, use `prependAll` instead - deprecate `insertAt`, Use `ReadonlyArray`'s `insertAt` instead - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - deprecate `uncons` in favour of `unprepend` - deprecate `unsnoc` in favour of `unappend` - deprecate `filter` in favour of `ReadonlyArray`'s `filter` - deprecate `filterWithIndex` in favour of `ReadonlyArray`'s `filterWithIndex` - `ReadonlyMap` - deprecate `insertAt` in favour of `upsertAt` - `ReadonlyRecord` - deprecate `hasOwnProperty`, use `has` instead - deprecate `insertAt` in favour of `upsertAt` - `ReadonlySet` - deprecate `fromArray` in favour of `fromReadonlyArray` - `ReadonlyTuple` - deprecate `mapLeft` in favour of `mapSnd` - deprecate `map` in favour of `mapFst` - `Record` - deprecate `hasOwnProperty`, use `has` instead - deprecate `insertAt` in favour of `upsertAt` - deprecate `empty` - `Ring` - deprecate `getTupleRing`, use `tuple` instead - `Semigroup` - deprecate `semigroupAll`, use `boolean.SemigroupAll` instead - deprecate `semigroupAny`, use `boolean.SemigroupAny` instead - deprecate `getFunctionSemigroup`, use `function.getSemigroup` instead - deprecate `semigroupString`, use `string.Semigroup` instead - deprecate `semigroupSum`, use `number.SemigroupSum` instead - deprecate `semigroupProduct`, use `number.SemigroupProduct` instead - deprecate `fold`, use `concatAll` instead - deprecate `getIntercalateSemigroup`, use `intercalate` instead - deprecate `getMeetSemigroup`, use `min` instead - deprecate `getJoinSemigroup`, use `max` instead - deprecate `getDualSemigroup`, use `reverse` instead - deprecate `getStructSemigroup`, use `struct` instead - deprecate `getTupleSemigroup`, use `tuple` instead - deprecate `getFirstSemigroup`, use `first` instead - deprecate `getLastSemigroup`, use `last` instead - deprecate `getObjectSemigroup`, use `assign` instead - `Set` - deprecate `subset` in favour of `isSubset` - `Show` - deprecate `showBoolean`, use `boolean.Show` instead - deprecate `showString`, use `string.Show` instead - deprecate `showNumber`, use `number.Show` instead - deprecate `getStructShow`, use `struct` instead - deprecate `getTupleShow`, use `tuple` instead - `Strong` - deprecate `splitStrong` in favour of `split` - deprecate `fanout` in favour of `fanOut` - `Task` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `fromTask` - `TaskEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getTaskValidation`, use `getApplicativeTaskValidation` and `getAltTaskValidation` instead - `TaskThese` - deprecate `functorTaskThese` instance in favour of `Functor` - deprecate `bifunctorTaskThese` instance in favour of `Bifunctor` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `toTuple` in favour of `toTuple2` - `These` - deprecate `toTuple` in favour of `toTuple2` - `Traversable` - deprecate `getTraversableComposition`, use `traverse`, `sequence` helpers instead - `Tuple` - deprecate `mapLeft` in favour of `mapSnd` - deprecate `map` in favour of `mapFst` - **New Feature** - add `Pointed` type class - add `FromEither` type class - add `FromIO` type class - add `FromTask` type class - add `TaskOption` module - add `string` module - add `number` module - add `Separated` module (@YBogomolov) - add `Json` module - `Apply` - add `ap` helper - add `apS` helper - add `apFirst` helper - add `apSecond` helper - add `getApplySemigroup` - `Applicative` - add `getApplicativeMonoid` - `Array` - add `Pointed` instance - add `Apply` instance - add `matchLeft` alias - add `matchRight` alias - add `size` - better `unsafeInsertAt` signature - better `chunksOf` signature - add `getSemigroup` - `boolean` - add `foldW` - add `match` alias - add `matchW` alias - add `Eq` instance - add `BooleanAlgebra` instance - add `SemigroupAll` instance - add `SemigroupAny` instance - add `MonoidAll` instance - add `MonoidAny` instance - add `Ord` instance - add `Show` instance - `BooleanAlgebra` - add `reverse` - `Chain` - add `bind` helper - add `chainFirst` helper - `Compactable` - add `compact` helper - add `separate` helper - add `separated` constructor - `Date` - add `Eq` instance - add `Ord` instance - `Filterable` - add `filter` helper - add `filterMap` helper - add `partition` helper - add `partitionMap` helper - `Foldable` - add `reduce` helper - add `foldaMap` helper - add `reduceRight` helper - `FoldableWithIndex` - add `reduceWithIndex` helper - add `foldaMapWithIndex` helper - add `reduceRightWithIndex` helper - `function` - add `getBooleanAlgebra` - add `getSemigroup` - add `getMonoid` - add `getSemiring` - add `getRing` - add `getEndomorphismMonoid` - `Functor` - add `map` helper - add `bindTo` helper - add `flap` derivable, #1393 (@williamareynolds) - `FunctorWithIndex` - add `mapWithIndex` helper - `Either` - add `Pointed` instance - add `Apply` instance - add `getCompactable` - add `getFilterable` - add `FromEither` instance - add `toUnion`, closes #1362 - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `tryCatchK` - add `fromOptionK` - add `chainOptionK` - `EitherT` - split `getEitherM` into separated functions - `Eq` - add `getSemigroup` - add `struct` - add `tuple` - `Identity` - add `Pointed` instance - add `Apply` instance - `IO` - add `Pointed` instance - add `Apply` instance - add `FromIO` instance - `IOEither` - add `Pointed` instance - add `getCompactable` - add `FromIO` instance - add `FromEither` instance - add `tryCatchK` combinator - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - `Map` - add `filterWithIndex` combinator - add `filterMapWithIndex` combinator - add `partitionWithIndex` combinator - add `partitionMapWithIndex` combinator - add `getTraversableWithIndex` instance - add `getFoldableWithIndex` instance - `Monoid` - add `concatAll` - add `min` - add `max` - add `reverse` - add `struct` - add `tuple` - `NonEmptyArray` - add `Pointed` instance - add `Apply` instance - add `concatAll` - add `isNonEmpty` guard - add `fromReadonlyNonEmptyArray` constructor - add `chainWithIndex` combinator - add `chop` - add `splitAt` - add `chunksOf` - `Option` - add `Pointed` instance - add `Apply` instance - add `foldW` - add `match` alias - add `matchW` alias - add `tryCatchK` - `OptionT` - split `getOptionM` into separated functions - `Ord` - add `equalsDefault` - add `reverse` - add `tuple` - `Ordering` - add `Eq` instance - add `Semigroup` instance - add `Monoid` instance - add `match` - `Random` - add `randomElem` - `Reader` - add `Pointed` instance - add `Apply` instance - export `first`, `second`, `left`, `right` - `ReaderT` - split `getReaderM` into separated functions - `ReaderEither` - add `Pointed` instance - add `Apply` instance - add `FromEither` instance - add `getCompactable` - add `getFilterable` - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - `ReaderTask` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `FromIO` instance - add `FromTask` instance - add `traverseSeqArrayWithIndex` - add `traverseSeqArray` - add `sequenceSeqArray` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - `ReaderTaskEither` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `FromIO` instance - add `FromTask` instance - add `FromEither` instance - add `getCompactable` - add `getFilterable` - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - export `MonadThrow` instance - `ReadonlyArray` - add `Pointed` instance - add `Apply` instance - add `getSemigroup` - add `matchLeft` instance - add `matchRight` instance - add `size` - better `unsafeInsertAt` signature - better `chunksOf` signature, closes #1407 - `ReadonlyMap` - add `filterWithIndex` combinator - add `filterMapWithIndex` combinator - add `partitionWithIndex` combinator - add `partitionMapWithIndex` combinator - add `getFunctorWithIndex` - add `getFoldable` - add `getFoldableWithIndex` - add `getTraversable` - add `getTraversableWithIndex` - `ReadonlyNonEmptyArray` - add `Pointed` instance - add `Apply` instance - add `concatAll` - add `isNonEmpty` - add `chainWithIndex` - add `chop` - add `splitAt` - add `chunksOf` - `ReadonlySet` - add `isEmpty` - add `size` - add `toggle` - `Ring` - add `tuple` - `Set` - add `isEmpty` - add `size` - `Semigroup` - add `constant` - add `concatAll` - add `intercalate` - add `min` - add `max` - add `struct` - add `tuple` - add `first` - add `last` - add `assign` - `Show` - add `struct` - add `tuple` - `State` - add `Pointed` instance - add `Apply` instance - `StateT` - split `getStateM` into separated functions - `StateReaderTaskEither` - add `Pointed` instance - add `Apply` instance - add `Monad` instance - add `FromIO` instance - add `FromTask` instance - add `FromEither` instance - add `fromOptionK` - add `chainOptionK` - export `MonadIO` instance - export `MonadTask` instance - export `MonadThrow` instance - `Task` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `FromIO` instance - add `FromTask` instance - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - `TaskEither` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `getCompactable` - add `FromIO` instance - add `FromTask` instance - add `FromEither` instance - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - export `MonadThrow` instance - `TaskThese` - add `Functor` instance - add `Pointed` instance - add `Bifunctor` instance - add `toTuple2` - add `getApply` - add `FromIO` instance - add `FromTask` instance - add `fromEither` function - add `FromEither` instance - add `getChain` instance - add `foldW` - add `match` alias - add `matchW` alias - add `fromOption` - add `fromOptionK` - add `fromPredicate` - `These` - add `Pointed` instance - add `of` function - add `getApply` - add `toTuple2` - add `FromEither` instance - add `fromOption` constructor - add `foldW` - add `match` alias - add `matchW` alias - add `fromOptionK` - `TaskOption` - export `Chain` instance - export `Monad` instance - `TheseT` - split `getTheseM` into separated functions - `Traversable` - add `traverse` helper - add `sequence` helper - `Tree` - add `Pointed` instance - add `Apply` instance - `Writer` - add `getPointed` - add `getApply` - add `getApplicative` - add `getChain` - **Bug Fix** - `ReadonlyRecord` / `Record`: remove `extends string` constraints in `singleton` / `insertAt`, closes #1413 - `TaskOption` - fix `getOrElseW` signature - **Internal** - add `internal` module - **Polish** - the scope in `bindTo`, `bind`, `bindW`, `apS`, `apSW` is now correctly `readonly` - fix `FromEither` type parameter order - `Array` / `ReadonlyArray` - assert arrays as non-empty when using `some`, #1424 (@thewilkybarkid) - fix `matchLeft`, `matchRight` type parameter order - `EitherT` - add overloads for `Kind2`, `Kind3`, `Kind4` - `OptionT` - add overloads for `Kind2`, `Kind3`, `Kind4` - `ReaderT` - add overloads for `Kind2`, `Kind3`, `Kind4` - `ReadonlyMap` - sort keys in `getShow` - `ReadonlySet` - sort keys in `getShow` - `StateT` - add overloads for `Kind2`, `Kind3` - `TheseT` - add overloads for `Kind2`, `Kind3`, `Kind4` # 2.10.0-rc.8 - **Polish** - the scope in `bindTo`, `bind`, `bindW`, `apS`, `apSW` is now correctly `readonly` - fix `FromEither` type parameter order # 2.10.0-rc.7 - **Breaking Change** (with respect to `2.10.0-rc`) - rename module `object` to `struct` # 2.10.0-rc.6 - **Bug Fix** - `ReadonlyNonEmptyArray` - remove circular dependency on `NonEmptyArray`, closes #1443 - **Breaking Change** (with respect to `2.10.0-rc`) - `EitherT` - rename `match` to `matchE` and add `match` - `IOEither` - rename `match` / `matchW` to `matchE` / `matchWE` and add `match` / `matchW` - `OptionT` - rename `match` to `matchE` and add `match` - `ReaderEither` - rename `match` / `matchW` to `matchE` / `matchWE` and add `match` / `matchW` - `ReaderTaskEither` - rename `match` / `matchW` to `matchE` / `matchWE` and add `match` / `matchW` - `TheseT` - rename `match` to `matchE` and add `match` - `TaskEither` - rename `match` / `matchW` to `matchE` / `matchWE` and add `match` / `matchW` - `TaskOption` - rename `match` / `matchW` to `matchE` / `matchWE` and add `match` / `matchW` - `TaskThese` - rename `match` / `matchW` to `matchE` / `matchWE` and add `match` / `matchW` # 2.10.0-rc.5 - **Bug Fix** - `TaskOption` - fix `getOrElseW` signature - **Breaking Change** (with respect to `2.10.0-rc`) - `OptionT` - rename `none` to `zero` and change signature - `ReaderT` - remove `ask`, `asks` (they will be derived from the `FromReader` type-class in `2.11`) - `Semigroup` - move `assign` to `object` module and rename to `getAssignSemigroup` - `ReaderT` - remove `get`, `put`, `modify`, `gets` (they will be derived from the `FromState` type-class in `2.11`) - **Deprecation** - `Tuple` - deprecate `mapLeft` in favour of `mapSnd` - deprecate `map` in favour of `mapFst` - `ReadonlyTuple` - deprecate `mapLeft` in favour of `mapSnd` - deprecate `map` in favour of `mapFst` - **Polish** - `Array` / `ReadonlyArray` - assert arrays as non-empty when using `some`, #1424 (@thewilkybarkid) - fix `matchLeft`, `matchRight` type parameter order - `EitherT` - add overloads for `Kind2`, `Kind3`, `Kind4` - `OptionT` - add overloads for `Kind2`, `Kind3`, `Kind4` - `ReaderT` - add overloads for `Kind2`, `Kind3`, `Kind4` - `ReadonlyMap` - sort keys in `getShow` - `ReadonlySet` - sort keys in `getShow` - `StateT` - add overloads for `Kind2`, `Kind3` - `TheseT` - add overloads for `Kind2`, `Kind3`, `Kind4` - **Internal** - add `internal` module # 2.10.0-rc.4 - **Deprecations** - `Array` - deprecate `empty` - `Map` - deprecate `empty` - `NonEmptyArray` - deprecate `filter` in favour of `Array`'s `filter` - deprecate `filterWithIndex` in favour of `Array`'s `filterWithIndex` - `ReadonlyNonEmptyArray` - deprecate `filter` in favour of `ReadonlyArray`'s `filter` - deprecate `filterWithIndex` in favour of `ReadonlyArray`'s `filterWithIndex` - `Record` - deprecate `empty` - **Polish** - `NonEmptyArray` - remove duplicated `append`, `prepend`, `isNonEmpty` - `ReadonlyNonEmptyArray` - remove duplicated `append`, `prepend`, `isNonEmpty` # 2.10.0-rc.3 - **Deprecations** - `Array` - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - `Ordering` - deprecate `invert` in favour of `reverse` - `ReadonlyMap` - deprecate `insertAt` in favour of `upsertAt` - `ReadonlyRecord` - deprecate `insertAt` in favour of `upsertAt` - `Map` - deprecate `insertAt` in favour of `upsertAt` - `NonEmptyArray` - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - deprecate `uncons` in favour of `unprepend` - deprecate `unsnoc` in favour of `unappend` - `Record` - deprecate `insertAt` in favour of `upsertAt` - `ReadonlyArray` - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - `ReadonlyNonEmptyArray` - deprecate `insertAt`, Use `ReadonlyArray`'s `insertAt` instead - deprecate `cons` in favour of `prepend` - deprecate `snoc` in favour of `append` - deprecate `uncons` in favour of `unprepend` - deprecate `unsnoc` in favour of `unappend` - `ReadonlySet` - deprecate `fromArray` in favour of `fromReadonlyArray` - `Set` - deprecate `subset` in favour of `isSubset` - **New Feature** - `Array` - add `size` - better `unsafeInsertAt` signature - better `chunksOf` signature - add `getSemigroup` - `Map` - add `filterWithIndex` combinator - add `filterMapWithIndex` combinator - add `partitionWithIndex` combinator - add `partitionMapWithIndex` combinator - add `getTraversableWithIndex` instance - add `getFoldableWithIndex` instance - `NonEmptyArray` - add `isNonEmpty` guard - add `fromReadonlyNonEmptyArray` constructor - add `chainWithIndex` combinator - add `chop` - add `splitAt` - add `chunksOf` - `Ordering` - add `match` - `ReadonlyArray` - add `size` - better `unsafeInsertAt` signature - better `chunksOf` signature, closes #1407 - `ReadonlyNonEmptyArray` - add `isNonEmpty` - add `chainWithIndex` - add `chop` - add `splitAt` - add `chunksOf` - `ReadonlySet` - add `isEmpty` - add `size` - add `toggle` - `Set` - add `isEmpty` - add `size` - `string` - add `empty` - add `isEmpty` - add `size` - **Bug Fix** - `ReadonlyRecord` / `Record`: remove `extends string` constraints in `singleton` / `insertAt`, closes #1413 # 2.10.0-rc.2 - **Deprecations** - `Choice` - deprecate `splitChoice` in favour of `split` - deprecate `fanin` in favour of `fanIn` - `Strong` - deprecate `splitStrong` in favour of `split` - deprecate `fanout` in favour of `fanOut` - **New Feature** - `Reader` - export `first`, `second`, `left`, `right` - `ReaderTask` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - `ReaderTaskEither` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - export `MonadThrow` instance - `StateReaderTaskEither` - export `MonadIO` instance - export `MonadTask` instance - export `MonadThrow` instance - `Task` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - `TaskEither` - export `Chain` instance - export `Monad` instance - export `MonadIO` instance - export `MonadTask` instance - export `MonadThrow` instance - `TaskOption` - export `Chain` instance - export `Monad` instance - **Polish** - `Compactable` - split `compact` / `separate` constraints # 2.10.0-rc.1 - **Deprecations** - deprecate `pipeable` module, use the specific helpers instead - deprecate `ValidationT` module, use `EitherT` instead - deprecate "mega instances", use small, specific instances instead - deprecate the old monad transformers, use the specific helpers instead - `Applicative` - deprecate `getApplicativeComposition`, use `ap` helper instead - `Array` - deprecate `prependToAll`, use `prependAll` instead - `BooleanAlgebra` - deprecate `booleanAlgebraBoolean`, use `boolean.BooleanAlgebra` instead - deprecate `getFunctionBooleanAlgebra`, use `function.getBooleanAlgebra` instead - deprecate `getDualBooleanAlgebra`, use `reverse` instead - `Bounded` - deprecate `boundedNumber`, use `number.Bounded` instead - `Compactable` - deprecate `getCompactableComposition`, use `compact`, `separate` helpers instead - deprecate `Separated`, use `Separated.Separated` instead - `Either` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getValidationSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getValidationMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getValidation`, use `getApplicativeValidation` and `getAltValidation` instead - deprecate `Json` type, use the `Json` module instead - deprecate `parseJSON` type, use the `Json` module instead - deprecate `stringifyJSON` type, use the `Json` module instead - `Eq` - deprecate `eqBoolean`, use `boolean.Eq` instead - deprecate `eqString`, use `string.Eq` instead - deprecate `eqNumber`, use `number.Eq` instead - deprecate `eqDate`, use `Date.Eq` instead - deprecate `getStructEq`, use `struct` instead - deprecate `getTupleEq`, use `tuple` instead - `Filterable` - deprecate `getFilterableComposition`, use `filter`, `filterMap`, `partition`, `partitionMap` helpers instead - `Foldable` - deprecate `toArray` in favour of `toReadonlyArray` - deprecate `getFoldableComposition`, use `reduce`, `foldMap`, `reduceRight` helpers instead - `FoldableWithIndex` - deprecate `getFoldableWithIndexComposition`, use `reduceWithIndex`, `foldMapWithIndex`, `reduceRightWithIndex` helpers instead - `Functor` - deprecate `getFunctorComposition`, use `map` helper instead - `FunctorWithIndex` - deprecate `getFunctorWithIndexComposition`, use `mapWithIndex` helper instead - `IO` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `fromIO` - `IOEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getIOValidation`, use `getApplicativeIOValidation` and `getAltIOValidation` instead - `Monoid` - deprecate `monoidAll`, use `boolean.MonoidAll` instead - deprecate `monoidAny`, use `boolean.MonoidAny` instead - deprecate `getFunctionMonoid`, use `function.getMonoid` instead - deprecate `getEndomorphismMonoid`, use `function.getEndomorphismMonoid` instead (**Note**. The execution order in `function.getEndomorphismMonoid` is reversed) - deprecate `monoidString`, use `string.Monoid` instead - deprecate `monoidSum`, use `number.MonoidSum` instead - deprecate `monoidProduct`, use `number.MonoidProduct` instead - deprecate `fold`, use `concatAll` instead - deprecate `getMeetMonoid`, use `min` instead - deprecate `getJoinMonoid`, use `max` instead - deprecate `getDualMonoid`, use `reverse` instead - deprecate `getStructMonoid`, use `struct` instead - deprecate `getTupleMonoid`, use `tuple` instead - `NonEmptyArray` - deprecate `fold`, use `concatAll` instead - deprecate `prependToAll`, use `prependAll` instead - `Option` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - `Ord` - deprecate `ordBoolean`, use `boolean.Ord` instead - deprecate `ordString`, use `string.Ord` instead - deprecate `ordNumber`, use `number.Ord` instead - deprecate `ordDate`, use `Date.Ord` instead - deprecate `getDualOrd`, use `reverse` instead - deprecate `getTupleOrd`, use `tuple` instead - `Ordering` - deprecate `eqOrdering`, use `Eq` instead - deprecate `monoidOrdering`, use `Monoid` instead - `Ring` - deprecate `getFunctionRing`, use `function.getRing` instead - `Reader` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - `ReaderEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getReaderValidation`, use `getApplicativeReaderValidation` and `getAltReaderValidation` instead - deprecate `local`, Use `Reader`'s `local` instead - `ReaderTask` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `run` - deprecate `local`, Use `Reader`'s `local` instead - `ReaderTaskEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getReaderTaskValidation`, use `getApplicativeReaderTaskValidation` and `getAltReaderTaskValidation` instead - deprecate `run` - deprecate `local`, Use `Reader`'s `local` instead - `ReaderTaskEither` - deprecate `run` - `ReadonlyArray` - deprecate `prependToAll`, use `prependAll` instead - `ReadonlyNonEmptyArray` - deprecate `fold`, use `concatAll` instead - deprecate `prependToAll`, use `prependAll` instead - `ReadonlyRecord` - deprecate `hasOwnProperty`, use `has` instead - `Record` - deprecate `hasOwnProperty`, use `has` instead - `Ring` - deprecate `getTupleRing`, use `tuple` instead - `Semigroup` - deprecate `semigroupAll`, use `boolean.SemigroupAll` instead - deprecate `semigroupAny`, use `boolean.SemigroupAny` instead - deprecate `getFunctionSemigroup`, use `function.getSemigroup` instead - deprecate `semigroupString`, use `string.Semigroup` instead - deprecate `semigroupSum`, use `number.SemigroupSum` instead - deprecate `semigroupProduct`, use `number.SemigroupProduct` instead - deprecate `fold`, use `concatAll` instead - deprecate `getIntercalateSemigroup`, use `intercalate` instead - deprecate `getMeetSemigroup`, use `min` instead - deprecate `getJoinSemigroup`, use `max` instead - deprecate `getDualSemigroup`, use `reverse` instead - deprecate `getStructSemigroup`, use `struct` instead - deprecate `getTupleSemigroup`, use `tuple` instead - deprecate `getFirstSemigroup`, use `first` instead - deprecate `getLastSemigroup`, use `last` instead - deprecate `getObjectSemigroup`, use `assign` instead - `Show` - deprecate `showBoolean`, use `boolean.Show` instead - deprecate `showString`, use `string.Show` instead - deprecate `showNumber`, use `number.Show` instead - deprecate `getStructShow`, use `struct` instead - deprecate `getTupleShow`, use `tuple` instead - `Task` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `fromTask` - `TaskEither` - deprecate `getApplySemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getApplyMonoid` in favour of `Applicative.getApplicativeMonoid` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `getTaskValidation`, use `getApplicativeTaskValidation` and `getAltTaskValidation` instead - `TaskThese` - deprecate `functorTaskThese` instance in favour of `Functor` - deprecate `bifunctorTaskThese` instance in favour of `Bifunctor` - deprecate `getSemigroup` in favour of `Apply.getApplySemigroup` - deprecate `toTuple` in favour of `toTuple2` - `These` - deprecate `toTuple` in favour of `toTuple2` - `Traversable` - deprecate `getTraversableComposition`, use `traverse`, `sequence` helpers instead - **New Feature** - add `Pointed` type class - add `FromEither` type class - add `FromIO` type class - add `FromTask` type class - add `TaskOption` module - add `string` module - add `number` module - add `Separated` module (@YBogomolov) - add `Json` module - `Apply` - add `ap` helper - add `apS` helper - add `apFirst` helper - add `apSecond` helper - add `getApplySemigroup` - `Applicative` - add `getApplicativeMonoid` - `Array` - add `Pointed` instance - add `Apply` instance - add `matchLeft` alias - add `matchRight` alias - `boolean` - add `foldW` - add `match` alias - add `matchW` alias - add `Eq` instance - add `BooleanAlgebra` instance - add `SemigroupAll` instance - add `SemigroupAny` instance - add `MonoidAll` instance - add `MonoidAny` instance - add `Ord` instance - add `Show` instance - `BooleanAlgebra` - add `reverse` - `Chain` - add `bind` helper - add `chainFirst` helper - `Compactable` - add `compact` helper - add `separate` helper - add `separated` constructor - `Date` - add `Eq` instance - add `Ord` instance - `Filterable` - add `filter` helper - add `filterMap` helper - add `partition` helper - add `partitionMap` helper - `Foldable` - add `reduce` helper - add `foldaMap` helper - add `reduceRight` helper - `FoldableWithIndex` - add `reduceWithIndex` helper - add `foldaMapWithIndex` helper - add `reduceRightWithIndex` helper - `function` - add `getBooleanAlgebra` - add `getSemigroup` - add `getMonoid` - add `getSemiring` - add `getRing` - add `getEndomorphismMonoid` - `Functor` - add `map` helper - add `bindTo` helper - add `flap` derivable, #1393 (@williamareynolds) - `FunctorWithIndex` - add `mapWithIndex` helper - `Either` - add `Pointed` instance - add `Apply` instance - add `getCompactable` - add `getFilterable` - add `FromEither` instance - add `toUnion`, closes #1362 - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `tryCatchK` - add `fromOptionK` - add `chainOptionK` - `EitherT` - split `getEitherM` into separated functions - `Eq` - add `getSemigroup` - add `struct` - add `tuple` - `Identity` - add `Pointed` instance - add `Apply` instance - `IO` - add `Pointed` instance - add `Apply` instance - add `FromIO` instance - `IOEither` - add `Pointed` instance - add `getCompactable` - add `FromIO` instance - add `FromEither` instance - add `tryCatchK` combinator - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - `Monoid` - add `concatAll` - add `min` - add `max` - add `reverse` - add `struct` - add `tuple` - `NonEmptyArray` - add `Pointed` instance - add `Apply` instance - add `concatAll` - `Option` - add `Pointed` instance - add `Apply` instance - add `foldW` - add `match` alias - add `matchW` alias - add `tryCatchK` - `OptionT` - split `getOptionM` into separated functions - `Ord` - add `equalsDefault` - add `reverse` - add `tuple` - `Ordering` - add `Eq` instance - add `Semigroup` instance - add `Monoid` instance - `Random` - add `randomElem` - `Reader` - add `Pointed` instance - add `Apply` instance - `ReaderT` - split `getReaderM` into separated functions - `ReaderEither` - add `Pointed` instance - add `Apply` instance - add `FromEither` instance - add `getCompactable` - add `getFilterable` - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - `ReaderTask` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `FromIO` instance - add `FromTask` instance - add `traverseSeqArrayWithIndex` - add `traverseSeqArray` - add `sequenceSeqArray` - `ReaderTaskEither` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `FromIO` instance - add `FromTask` instance - add `FromEither` instance - add `getCompactable` - add `getFilterable` - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - `ReadonlyArray` - add `Pointed` instance - add `Apply` instance - add `getSemigroup` - add `matchLeft` instance - add `matchRight` instance - `ReadonlyMap` - add `filterWithIndex` combinator - add `filterMapWithIndex` combinator - add `partitionWithIndex` combinator - add `partitionMapWithIndex` combinator - add `getFunctorWithIndex` - add `getFoldable` - add `getFoldableWithIndex` - add `getTraversable` - add `getTraversableWithIndex` - `ReadonlyNonEmptyArray` - add `Pointed` instance - add `Apply` instance - add `concatAll` - `Ring` - add `tuple` - `Semigroup` - add `constant` - add `concatAll` - add `intercalate` - add `min` - add `max` - add `struct` - add `tuple` - add `first` - add `last` - add `assign` - `Show` - add `struct` - add `tuple` - `State` - add `Pointed` instance - add `Apply` instance - `StateT` - split `getStateM` into separated functions - `StateReaderTaskEither` - add `Pointed` instance - add `Apply` instance - add `Monad` instance - add `FromIO` instance - add `FromTask` instance - add `FromEither` instance - add `fromOptionK` - add `chainOptionK` - `Task` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `FromIO` instance - add `FromTask` instance - `TaskEither` - add `Pointed` instance - add `ApplyPar` instance - add `ApplySeq` instance - add `getCompactable` - add `FromIO` instance - add `FromTask` instance - add `FromEither` instance - add `toUnion` - add `foldW` - add `match` alias - add `matchW` alias - add `orElseW` - add `fromOptionK` - add `chainOptionK` - `TaskThese` - add `Functor` instance - add `Pointed` instance - add `Bifunctor` instance - add `toTuple2` - add `getApply` - add `FromIO` instance - add `FromTask` instance - add `fromEither` function - add `FromEither` instance - add `getChain` instance - add `foldW` - add `match` alias - add `matchW` alias - add `fromOption` - add `fromOptionK` - add `fromPredicate` - `These` - add `Pointed` instance - add `of` function - add `getApply` - add `toTuple2` - add `FromEither` instance - add `fromOption` constructor - add `foldW` - add `match` alias - add `matchW` alias - add `fromOptionK` - `TheseT` - split `getTheseM` into separated functions - `Traversable` - add `traverse` helper - add `sequence` helper - `Tree` - add `Pointed` instance - add `Apply` instance - `Writer` - add `getPointed` - add `getApply` - add `getApplicative` - add `getChain` # 2.9.5 - **Polish** - `Array`, `ReadonlyArray`: change `scanLeft` and `scanRight` to return `NonEmptyArray`, `ReadonlyNonEmptyArray`, #1391 (@willheslam) # 2.9.4 - **Bug Fix** - fix `filter` overloads in `NonEmptyArray` / `ReadonlyNonEmptyArray`, closes #1388 (@gcanti) # 2.9.3 - **Polish** - add more `/*#__PURE__*/` comments to improve tree shaking, #1370 (@OliverJAsh) # 2.9.2 - **Polish** - add more `/*#__PURE__*/` comments to improve tree shaking, #1368 (@OliverJAsh) # 2.9.1 - **Polish** - `Array` / `ReadonlyArray` - `sort`: return the input when length <= 1, closes #1357 (@gcanti) - `uniq`: return the input when length <= 1 (@gcanti) # 2.9.0 - **New Feature** - `Array` - add `altW` (@gcanti) - add `intersperse` (@marcotoniut) - add `prependToAll` (@marcotoniut) - add `every` (@gcanti) - add `some` (@gcanti) - add `Do` (@gcanti) - `Either` - add `altW` (@gcanti) - add `fromNullableK` (@gcanti) - add `chainNullableK` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - add `filterOrElseW` (@gcanti) - `Identity` - add `altW` (@gcanti) - add `Do` (@gcanti) - `IO` - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - `IOEither` - add `altW` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `traverseSeqArrayWithIndex` (@mohaalak @iamomiid) - add `traverseSeqArray` (@mohaalak @iamomiid) - add `sequenceSeqArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - add `filterOrElseW` (@gcanti) - `NonEmptyArray` - add `altW` (@gcanti) - add `uncons` (@marcotoniut) - add `unsnoc` (@marcotoniut) - add `intersperse` (@marcotoniut) - add `prependToAll` (@marcotoniut) - add `Do` (@gcanti) - `Option` - add `altW` (@gcanti) - add `fromNullableK` (@gcanti) - add `chainNullableK` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - `Reader` - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - `ReaderEither` - add `altW` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - add `filterOrElseW` (@gcanti) - `ReaderTask` - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `traverseSeqArrayWithIndex` (@mohaalak @iamomiid) - add `traverseSeqArray` (@mohaalak @iamomiid) - add `sequenceSeqArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - `ReaderTaskEither` - add `altW` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `traverseSeqArrayWithIndex` (@mohaalak @iamomiid) - add `traverseSeqArray` (@mohaalak @iamomiid) - add `sequenceSeqArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - add `filterOrElseW` (@gcanti) - `ReadonlyArray` - add `altW` (@gcanti) - add `intersperse` (@marcotoniut) - add `prependToAll` (@marcotoniut) - add `every` (@gcanti) - add `some` (@gcanti) - add `Do` (@gcanti) - `ReadonlyNonEmptyArray` - add `altW` (@gcanti) - add `uncons` (@marcotoniut) - add `unsnoc` (@marcotoniut) - add `intersperse` (@marcotoniut) - add `prependToAll` (@marcotoniut) - add `Do` (@gcanti) - `State` - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - `StateReaderTaskEither` - add `altW` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `filterOrElseW` (@gcanti) - `Task` - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `traverseSeqArrayWithIndex` (@mohaalak @iamomiid) - add `traverseSeqArray` (@mohaalak @iamomiid) - add `sequenceSeqArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - `TaskEither` - add `altW` (@gcanti) - add `traverseArrayWithIndex` (@mohaalak @iamomiid) - add `traverseArray` (@mohaalak @iamomiid) - add `sequenceArray` (@mohaalak @iamomiid) - add `traverseSeqArrayWithIndex` (@mohaalak @iamomiid) - add `traverseSeqArray` (@mohaalak @iamomiid) - add `sequenceSeqArray` (@mohaalak @iamomiid) - add `Do` (@gcanti) - add `filterOrElseW` (@gcanti) - `Tree` - add `Do` (@gcanti) - **Deprecation** - `Option` - deprecate `mapNullable` in favour of `chainNullableK` (@gcanti) - `StateReaderTaskEither` - deprecate `stateReaderTaskEitherSeq` because is useless, `stateReaderTaskEither` is already sequential (@gcanti) # 2.8.6 - **Bug Fix** - fix #1350 (@gcanti) # 2.8.5 - **Polish** - `IOEither` - export missing `of` function (@gcanti) - `ReaderEither` - export missing `of` function (@gcanti) # 2.8.4 - **Polish** - `IOEither` - add `ApplicativePar` instance (@gcanti) - add `ApplicativeSeq` instance (@gcanti) - **Deprecation** - `IOEither` - deprecate `Applicative` in favour of `ApplicativePar` (@gcanti) # 2.8.3 - **Polish** - `Reader` - export `Strong` instance (@urgent) - export `Choice` instance (@gcanti) # 2.8.2 - **Polish** - increase the supported number of arguments of pipe function (@heka1024) - **Bug fix** - revert `groupBy` change in #1286 (@gcanti) - **Internal** - define all non-pipeable internal functions in terms of the corresponding pipeable versions (@gcanti) # 2.8.1 - **Polish** - fix `HKT` typings duplication (which might break module augmentation) # 2.8.0 - **New Feature** - expose `fp-ts` modules without lib/es6 prefix, #1241 (@StefanoMagrassi) - `Array` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `Either` - add `apW` (@gcanti) - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - add `chainFirstW`, #1273 (@leemhenson) - add `getFilterable` (@gcanti) - `Foldable` - add `toArray`, #1272 (@newswim) - add `reduceM` (@gcanti) - `Identity` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `IO` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `IOEither` - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - add `chainFirstW`, #1273 (@leemhenson) - `NonEmptyArray` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - relax `group` signature (@gcanti) - relax `groupBy` signature (@gcanti) - relax `groupSort` signature (@gcanti) - relax `sort` signature (@gcanti) - `Option` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `Reader` - add `apW` (@gcanti) - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - `ReaderEither` - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - add `chainFirstW`, #1273 (@leemhenson) - `ReaderTask` - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - `ReaderTaskEither` - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - add `chainFirstW`, #1273 (@leemhenson) - `ReadonlyArray` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `ReadonlyNonEmptyArray` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - relax `group` signature (@gcanti) - relax `groupBy` signature (@gcanti) - relax `groupSort` signature (@gcanti) - relax `sort` signature (@gcanti) - `State` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `evaluate` (@gcanti) - add `execute` (@gcanti) - `StateReaderTaskEither` - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - add `chainFirstW`, #1273 (@leemhenson) - add `evaluate` (@gcanti) - add `execute` (@gcanti) - `Task` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `TaskEither` - add `apS` (@gcanti) - add `apSW` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - add `bindW` (@gcanti) - add `chainFirstW`, #1273 (@leemhenson) - `Tree` - add `apS` (@gcanti) - add `bind` (@gcanti) - add `bindTo` (@gcanti) - `Writer` - add `evaluate` (@gcanti) - add `execute` (@gcanti) - **Deprecation** - `Foldable` - deprecate `foldM` in favour of `reduceM` (@gcanti) - `State` - deprecate `evalState` in favour of `evaluate` (@gcanti) - deprecate `execState` in favour of `execute` (@gcanti) - `StateReaderTaskEither` - deprecate `evalState` in favour of `evaluate` (@gcanti) - deprecate `execState` in favour of `execute` (@gcanti) - `Writer` - deprecate `evalWriter` in favour of `evaluate` (@gcanti) - deprecate `execWriter` in favour of `execute` (@gcanti) # 2.7.1 - **Bug Fix** - `ReadonlyArray` - fix `FunctorWithIndex` instance name (@gcanti) - fix `Functor` instance name (@gcanti) - **Polish** - `Array` - relax `sort` signature (@gcanti) - relax `sortBy` signature (@gcanti) - `Map` - export `mapWithIndex` (@gcanti) - `ReadonlyArray` - relax `sort` signature (@gcanti) - relax `sortBy` signature (@gcanti) - `ReadonlyMap` - export `mapWithIndex` (@gcanti) # 2.7.0 - **Bug Fix** - `These` - fix `ap` implementation in `getMonad` function (@gcanti) - **Polish** - improve performance of sequenceT and sequenceS, fix #1255 (@gcanti) - **New Feature** - `function` - add `hole` (type hole simulation) (@gcanti) - `Array` - add `chainWithIndex`, #1256 (@OliverJAsh) - add `Functor` instance (@gcanti) - add `FunctorWithIndex` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Unfoldable` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Alternative` instance (@gcanti) - add `Extend` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - add `FilterableWithIndex` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `FoldableWithIndex` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `TraversableWithIndex` instance (@gcanti) - add `Witherable` instance (@gcanti) - `Const` - add `Functor` instance (@gcanti) - add `Contravariant` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - `Either` - add `getApplicativeValidation` constrained instance (@gcanti) - add `getAltValidation` constrained instance (@gcanti) - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Extend` instance (@gcanti) - add `ChainRec` instance (@gcanti) - add `MonadThrow` instance (@gcanti) - `Eq` - add `Contravariant` instance (@gcanti) - `Identity` - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Comonad` instance (@gcanti) - add `ChainRec` instance (@gcanti) - `IO` - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `MonadIO` instance (@gcanti) - add `ChainRec` instance (@gcanti) - `IOEither` - add `getApplicativeIOValidation` constrained instance (@gcanti) - add `getAltIOValidation` constrained instance (@gcanti) - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Alt` instance (@gcanti) - add `MonadIO` instance (@gcanti) - add `MonadThrow` instance (@gcanti) - `Map` - add `Functor` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - `NonEmptyArray` - add `Functor` instance (@gcanti) - add `FunctorWithIndex` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `FoldableWithIndex` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `TraversableWithIndex` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Comonad` instance (@gcanti) - `Option` - add `Functor` instance (@gcanti) - add `Applicativ` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Alternative` instance (@gcanti) - add `Extend` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `Witherable` instance (@gcanti) - add `MonadThrow` instance (@gcanti) - `Ord` - add `ContravariantOrd` instance (@gcanti) - `Reader` - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Profunctor` instance (@gcanti) - add `Category` instance (@gcanti) - add `String` instance (@gcanti) - add `Choice` instance (@gcanti) - `ReaderEither` - add `getApplicativeReaderValidation` constrained instance (@gcanti) - add `getAltReaderValidation` constrained instance (@gcanti) - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Alt` instance (@gcanti) - add `MonadThrow` instance (@gcanti) - `ReaderTask` - add `Functor` instance (@gcanti) - add `ApplicativePar` instance (@gcanti) - add `ApplicativeSeq` instance (@gcanti) - `ReaderTaskEither` - add `getApplicativeReaderTaskValidation` constrained instance (@gcanti) - add `getAltReaderTaskValidation` constrained instance (@gcanti) - add `Functor` instance (@gcanti) - add `ApplicativePar` instance (@gcanti) - add `ApplicativeSeq` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Alt` instance (@gcanti) - `ReadonlyArray` - add `chainWithIndex`, #1256 (@OliverJAsh) - add `Functor` instance (@gcanti) - add `FunctorWithIndex` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Unfoldable` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Alternative` instance (@gcanti) - add `Extend` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - add `FilterableWithIndex` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `FoldableWithIndex` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `TraversableWithIndex` instance (@gcanti) - add `Witherable` instance (@gcanti) - `ReadonlyMap` - add `Functor` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - `ReadonlyNonEmptyArray` - add `Functor` instance (@gcanti) - add `FunctorWithIndex` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `FoldableWithIndex` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `TraversableWithIndex` instance (@gcanti) - add `Alt` instance (@gcanti) - add `Comonad` instance (@gcanti) - `ReadonlyRecord` - add `Functor` instance (@gcanti) - add `FunctorWithIndex` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - add `FilterableWithIndex` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `TraversableWithIndex` instance (@gcanti) - add `Witherable` instance (@gcanti) - `ReadonlyTuple` - add `Functor` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Semigroupoid` instance (@gcanti) - add `Comonad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Traversable` instance (@gcanti) - `Record` - add `Functor` instance (@gcanti) - add `FunctorWithIndex` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Compactable` instance (@gcanti) - add `Filterable` instance (@gcanti) - add `FilterableWithIndex` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `TraversableWithIndex` instance (@gcanti) - add `Witherable` instance (@gcanti) - `State` - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - `Store` - add `Functor` instance (@gcanti) - add `Comonad` instance (@gcanti) - `StateReaderTaskEither` - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Alt` instance (@gcanti) - `Task` - add `Functor` instance (@gcanti) - add `ApplicativePar` instance (@gcanti) - add `ApplicativeSeq` instance (@gcanti) - `TaskEither` - add `getApplicativeTaskValidation` constrained instance (@gcanti) - add `getAltTaskValidation` constrained instance (@gcanti) - add `Functor` instance (@gcanti) - add `ApplicativePar` instance (@gcanti) - add `ApplicativeSeq` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Alt` instance (@gcanti) - `TaskThese` - add `Functor` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - `These` - add `getApplicative` constrained instance (@gcanti) - add `Functor` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Traversable` instance (@gcanti) - `Traced` - rename `traced` to `Functor` for consistency (@gcanti) - `Tree` - add `Functor` instance (@gcanti) - add `Applicative` instance (@gcanti) - add `Monad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Traversable` instance (@gcanti) - add `Comonad` instance (@gcanti) - `Writer` - add `Functor` instance (@gcanti) - `Tuple` - add `Functor` instance (@gcanti) - add `Bifunctor` instance (@gcanti) - add `Semigroupoid` instance (@gcanti) - add `Comonad` instance (@gcanti) - add `Foldable` instance (@gcanti) - add `Traversable` instance (@gcanti) # 2.6.7 - **Polish** - refine `Either.parseJSON` return type, #1252 (@OliverJAsh) - add missing `chainW` to `ReaderTask`, #1254 (@adameier) # 2.6.6 - **Polish** - `Array` - export `unfold` (@gcanti) - make `lookup` data-last (@gcanti) - make `elem` data-last (@gcanti) - make `difference` data-last (@gcanti) - make `intersection` data-last (@gcanti) - make `union` data-last (@gcanti) - make `zip` data-last (@gcanti) - make `cons` data-last (@gcanti) - `Map` - make `member` data-last (@gcanti) - make `elem` data-last (@gcanti) - make `lookup` data-last (@gcanti) - make `lookupWithKey` data-last (@gcanti) - make `isSubmap` data-last (@gcanti) - `NonEmptyArray` - make `zip` data-last (@gcanti) - `ReadonlyArray` - export `unfold` (@gcanti) - make `lookup` data-last (@gcanti) - make `elem` data-last (@gcanti) - make `difference` data-last (@gcanti) - make `intersection` data-last (@gcanti) - make `union` data-last (@gcanti) - make `zip` data-last (@gcanti) - make `cons` data-last (@gcanti) - `ReadonlyMap` - make `member` data-last (@gcanti) - make `elem` data-last (@gcanti) - make `lookup` data-last (@gcanti) - make `lookupWithKey` data-last (@gcanti) - make `isSubmap` data-last (@gcanti) - `ReadonlyNonEmptyArray` - make `zip` data-last (@gcanti) - `ReadonlyRecord` - make `isSubrecord` data-last (@gcanti) - make `lookup` data-last (@gcanti) - make `elem` data-last (@gcanti) - `ReadonlySet` - make `isSubset` data-last (@gcanti) - make `elem` data-last (@gcanti) - make `union` data-last (@gcanti) - make `intersection` data-last (@gcanti) - make `difference` data-last (@gcanti) - `Record` - make `isSubrecord` data-last (@gcanti) - make `lookup` data-last (@gcanti) - make `elem` data-last (@gcanti) - `Set` - make `subset` data-last (@gcanti) - make `elem` data-last (@gcanti) - make `union` data-last (@gcanti) - make `intersection` data-last (@gcanti) - make `difference` data-last (@gcanti) - `Semigroup` - make `fold` data-last (@gcanti) # 2.6.5 - **Polish** - export a pipeable `wither` function from all modules which admit a `Witherable` instance (@gcanti) - export a pipeable `wilt` function from all modules which admit a `Witherable` instance (@gcanti) # 2.6.4 - **Bug Fix** - `ReadonlyMap` - `traverseWithIndex` should sort the keys (@gcanti) - `ReadonlyRecord` - `traverseWithIndex` should sort the keys (@gcanti) # 2.6.3 - **Polish** - change `ReadonlyNonEmptyArray` definition to get better type inference (@gcanti) - move `pipe` to `function` module (@gcanti) - export `sequence` from all modules which admit a `Traversable` instance (@gcanti) - export a pipeable `traverse` function from all modules which admit a `Traversable` instance (@gcanti) - export a pipeable `traverseWithIndex` function from all modules which admit a `TraversableWithIndex` instance (@gcanti) - remove monad transformers imports from all modules (@gcanti) # 2.6.2 The goal of this release is to make `fp-ts` more "tree shaking" friendly. - **Polish** - add `/*@__PURE__*/` comments to pipeables (@gcanti) - add `/*@__PURE__*/` comments to transformers (@gcanti) - remove `pipeable.ts` module imports (@gcanti) # 2.6.1 - **New Feature** - add W variants, closes #904 (@gcanti) - `Const` - add missing instances, #1201 (@gcanti) - `Date` - add `eqDate`, `eqMonth`, `eqYear` (@gcanti) - `Either` - add `getOrElseW` (@gcanti) - add `chainW` (@gcanti) - `Eq` - add `getMonoid` (@gcanti) - `IOEither` - add `getOrElseW` (@gcanti) - add `chainW` (@gcanti) - add `chainEitherKW` (@giogonzo) - `Option` - add `getOrElseW` (@gcanti) - `Reader` - add `chainW` (@gcanti) - `ReaderEither` - add `getOrElseW` (@gcanti) - add `chainW` (@gcanti) - add `chainEitherKW` (@giogonzo) - `ReaderTaskEither` - add `getOrElseW` (@gcanti) - add `chainW` (@gcanti) - add `chainEitherKW` (@giogonzo) - add `chainTaskEitherKW` (@giogonzo) - add `chainIOEitherKW` (@giogonzo) - `StateReaderTaskEither` - add `chainW` (@gcanti) - add `chainEitherKW` (@giogonzo) - add `chainTaskEitherKW` (@giogonzo) - add `chainReaderTaskEitherKW` (@giogonzo) - add `chainIOEitherKW` (@giogonzo) - `TaskEither` - add `getOrElseW` (@gcanti) - add `chainW` (@gcanti) - add `chainEitherKW` (@giogonzo) - add `chainIOEitherKW` (@giogonzo) - `Tree` - add `fold` function (@gcanti) # 2.5.4 - **Polish** - `StateT` - add missing `StateM2C` and `StateM3C` (@qlonik) # 2.5.3 - **Polish** - `Either` - add missing instances to `getValidation` (@gcanti) - `IOEither` - relax `Bifunctor2C` to `Bifunctor2` in `getIOValidation` (@gcanti) - `ReaderEither` - relax `Bifunctor3C` to `Bifunctor3` in `getReaderValidation` (@gcanti) - `ReaderTaskEither` - relax `Bifunctor3C` to `Bifunctor3` in `getReaderTaskValidation` (@gcanti) - `TaskEither` - relax `Bifunctor2C` to `Bifunctor2` in `getTaskValidation` (@gcanti) # 2.5.1 - **New Feature** - `Eq` - add `eqStrict`, closes #965 (@gcanti) - `NonEmptyArray` - add `fold` (@vicrac) - add `zip`, `zipWith` and `unzip`, closes #1109 (@gcanti) - `Semigroup` - add `getIntercalateSemigroup` (@gcanti) - `Set` - add `toggle` (@ryota-ka) - `TaskEither` - add `tryCatchK` (@DenisFrezzato) - `These` - add missing `MonadThrow` instance (@gcanti) - `ReaderTaskEither` - add missing `leftReaderTask`, `rightReaderTask` functions (@gcanti) - `StateReaderTaskEither` - add missing `Bifunctor`, `Alt` instances (@gcanti) - **Experimental** - add `ReadonlyArray` module (@gcanti) - add `ReadonlyNonEmptyArray` module (@gcanti) - add `ReadonlySet` module (@gcanti) - add `ReadonlyMap` module (@gcanti) - add `ReadonlyRecord` module (@gcanti) - add `ReadonlyTuple` module (@gcanti) # 2.4.4 - **Polish** - add missing `MonadIO4` (@mlegenhausen) - add missing `MonadTask4` (@mlegenhausen) - `StateReaderTaskEither` - add missing `MonadTask4` instance (@mlegenhausen) - add missing `filterOrElse`, `fromPredicate` combinators (@mlegenhausen) # 2.4.3 - **Bug Fix** - don't set `target: es6` in `tsconfig.build-es6.json`, fix #1110 (@gcanti) # 2.4.2 - **Bug Fix** - fix `Invariant` definition (@gcanti) # 2.4.1 - **Polish** - `NonEmptyArray` - add overloading to `group` managing non empty arrays, closes #831 (@gcanti) - `foldMap` and `foldMapWithIndex` now require a `Semigroup` instead of a `Monoid` (@gcanti) # 2.4.0 - **New Feature** - add `WriterT` module, closes #1050 (@gcanti) - add `TheseT` module (@gcanti) - add `TaskThese` module (@gcanti) - `function` - add `tupled`, `untupled` functions, closes #1062 (@gcanti) - `IOEither` - add `fromEitherK`, `chainEitherK` (@gcanti) - `ReaderEither` - add `fromEitherK`, `chainEitherK` (@gcanti) - `ReaderTask` - add `run` (@gcanti) - add `fromIOK`, `chainIOK`, `fromTaskK`, `chainTaskK` (@gcanti) - `ReaderTaskEither` - add `fromEitherK`, `chainEitherK`, `fromIOEitherK`, `chainIOEitherK`, `fromTaskEitherK`, `chainTaskEitherK` (@gcanti) - `These` - add `swap` (@gcanti) - `Ord` - add `getMonoid` (@vicrac) - `Ordering` - add `monoidOrdering` (@gcanti) - `StateReaderTaskEither` - add `fromEitherK`, `chainEitherK`, `fromIOEitherK`, `chainIOEitherK`, `fromTaskEitherK`, `chainTaskEitherK`, `fromReaderTaskEitherK`, `chainReaderTaskEitherK` (@gcanti) - `Task` - add `fromIOK`, `chainIOK` (@gcanti) - `TaskEither` - add `fromEitherK`, `chainEitherK`, `fromIOEitherK`, `chainIOEitherK` (@gcanti) - **Deprecation** - `Ord` - deprecate `getSemigroup` in favor of `getMonoid` (@gcanti) - `Ordering` - deprecate `semigroupOrdering` in favor of `monoidOrdering` (@gcanti) - **Internal** - use native `Promise.race` in `Task.getRaceMonoid` (@gcanti) # 2.3.1 - **Bug Fix** - `Array.ts` - fix `sortBy` failing on empty list of ords, #1046 (@vicrac) # 2.3.0 - **New Feature** - add `ReaderTask` module (@sledorze) - `ReaderTaskEither` - add `getReaderTaskValidation` (@sledorze) - `ReaderEither` - add `getReaderValidation` (@gcanti) - `TaskEither` - improve `getTaskValidation` (@gcanti) - `IOEither` - improve `getIOValidation` (@gcanti) # 2.2.0 - **New Feature** - add `boolean` module, closes #930 (@giogonzo) - add `ChainRec` instance to `IO` (@gcanti) - `NonEmptyArray` - add `init` (@steida) - add `Alt` instance (@gcanti) - **Internal** - add new 3C variants and related overloads (@sledorze) # 2.1.2 - **Bug Fix** - `fromNullable` now uses `NonNullable` in its return type, fixes #1004 (@gcanti) # 2.1.1 - **Bug Fix** - add `sequenceT` and `sequenceS` overload signatures for `Kind4`, fixes #969 (@pfgray) # 2.1.0 - **New Feature** - add constrained `Filterable` instance to `IOEither`, `TaskEither`, #959 (@giogonzo) # 2.0.5 - **Bug Fix** - fix `PipeableApply2C` definition (@gcanti) # 2.0.4 - **Polish** - `ReaderTaskEither` - add missing `bracket` function (@mlegenhausen) # 2.0.3 - **Bug Fix** - fix `sequenceT`, `sequenceS` implementations, closes #914 (@gcanti) # 2.0.2 - **Bug Fix** - add `reduce` to `FoldableComposition2C1` (@anilanar) # 2.0.1 - **Bug Fix** - fix `PipeableBifunctor` definition (@gcanti) - fix `chunksOf` implementation, #897 (@gcanti) # 2.0.0 - **Breaking Change** - remove deprecated APIs (@gcanti) - remove classes (@gcanti) - remove all phantom fields (@gcanti) ================================================ FILE: Do.md ================================================ # Do notation **Cheatsheet** | Haskell | TypeScript | | ------------- | ------------------------------ | | `a <- action` | `bind('a', (scope) => action)` | | `_ <- action` | `tap((scope) => action)` | | `return ...` | `map((scope) => ...)` | **Example** Haskell ```Haskell nameDo :: IO () nameDo = do putStrLn "What is your first name? " first <- getLine putStrLn "And your last name? " last <- getLine let full = first ++ " " ++ last putStrLn ("Pleased to meet you, " ++ full ++ "!") ``` TypeScript ```ts import { pipe } from 'fp-ts/function' import * as T from 'fp-ts/Task' declare const putStrLn: (s: string) => T.Task declare const getLine: T.Task const nameDo: T.Task = pipe( T.Do, T.tap(() => putStrLn('What is your first name? ')), T.bind('first', () => getLine), T.tap(() => putStrLn('And your last name? ')), T.bind('last', () => getLine), T.bind('full', ({ first, last }) => T.of(first + ' ' + last)), T.flatMap(({ full }) => putStrLn('Pleased to meet you, ' + full + '!')) ) ``` ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017-present Giulio Canti Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================

Functional programming in TypeScript

build status npm downloads

**📢 Important Announcement: fp-ts is Joining the Effect-TS Ecosystem!** We are excited to announce that the `fp-ts` project is officially merging with the Effect-TS ecosystem. This is a significant step forward in the functional programming landscape, bringing together two powerful libraries under one roof. Giulio Canti, the author of `fp-ts`, is being welcomed into the Effect organization, promising an exciting future with enhanced capabilities and support. **What This Means for New Users:** Effect-TS can be regarded as the successor to `fp-ts v2` and embodies what would be considered `fp-ts v3`. This merger marks a significant evolution in the library's capabilities, integrating more features and functionalities tailored towards robust, type-safe, and scalable functional programming. For more details on this merger and what it entails, please refer to the official [announcement here](https://dev.to/effect/a-bright-future-for-effect-455m). Additionally, you can explore more about Effect-TS and its offerings on our [website and documentation](https://effect.website/). # Introduction `fp-ts` is a library for _typed functional programming_ in TypeScript. `fp-ts` aims to allow developers to use _popular patterns and abstractions_ that are available in most functional languages. For this, it includes the most popular data types, type classes and abstractions such as [Option](https://gcanti.github.io/fp-ts/modules/Option.ts), [Either](https://gcanti.github.io/fp-ts/modules/Either.ts), [IO](https://gcanti.github.io/fp-ts/modules/IO.ts), [Task](https://gcanti.github.io/fp-ts/modules/Task.ts), [Functor](https://gcanti.github.io/fp-ts/modules/Functor.ts), [Applicative](https://gcanti.github.io/fp-ts/modules/Applicative.ts), [Monad](https://gcanti.github.io/fp-ts/modules/Monad.ts) to empower users to write pure FP apps and libraries built atop higher order abstractions. A distinctive feature of `fp-ts` with respect to other functional libraries is its implementation of [Higher Kinded Types](), which TypeScript doesn't support natively. **Inspired by** - [Haskell](https://www.haskell.org) - [PureScript](https://www.purescript.org) - [Scala](https://www.scala-lang.org) # Sponsors
Unsplash
Unsplash
https://unsplash.com/

The internet’s source for visuals.
Powered by creators everywhere.

# Installation To install the stable version: ``` npm install fp-ts ``` Make sure to always have a single version of `fp-ts` installed in your project. Multiple versions are known to cause `tsc` to hang during compilation. You can check the versions currently installed using `npm ls fp-ts` (make sure there's a single version and all the others are marked as `deduped`). ## TypeScript compatibility **Strictness** – This library is conceived, tested and is supposed to be consumed by TypeScript with the `strict` flag turned on. | `fp-ts` version | required `typescript` version | | --------------- | ----------------------------- | | 2.0.x+ | 3.5+ | | 1.15.x+ | 3.1+ | | <= 1.14.4 | 2.8+ (\*) | (\*) If you are running `< typescript@3.0.1` you have to polyfill the `unknown` type. You can use [unknown-ts](https://github.com/gcanti/unknown-ts) as a polyfill. # Documentation **Disclaimer**. Teaching functional programming is out of scope of this project, so the documentation assumes you already know what FP is. - [Docs](https://gcanti.github.io/fp-ts) - [Learning Resources](https://gcanti.github.io/fp-ts/learning-resources/) - [Ecosystem](https://gcanti.github.io/fp-ts/ecosystem/) - API Reference - [version 2.x (current)](https://gcanti.github.io/fp-ts/modules/) - [version 1.x](https://github.com/gcanti/fp-ts/tree/1.x/docs/modules/) # Help If you need help with `fp-ts` check out: - this [Discord server](https://discord.gg/HVWmBBXM8A) - the `#fp-ts` channel on [FP slack](https://fpslack.com/). # Development - [Code conventions](https://gcanti.github.io/fp-ts/guides/code-conventions) # License The MIT License (MIT) ================================================ FILE: code2comment.html ================================================ code 2 comment
================================================ FILE: docs/_config.yml ================================================ remote_theme: pmarsceill/just-the-docs # Enable or disable the site search search_enabled: true # Aux links for the upper right navigation aux_links: "Docs": - "//gcanti.github.io/fp-ts/" "API Reference": - "//gcanti.github.io/fp-ts/modules/" "GitHub": - "//github.com/gcanti/fp-ts" ================================================ FILE: docs/_sass/custom/custom.scss ================================================ $fp-ts-blue-000: #0088e6; $fp-ts-blue-100: #0075c5; $link-color: $fp-ts-blue-000; $btn-primary-color: $fp-ts-blue-100; ================================================ FILE: docs/ecosystem.md ================================================ --- title: Ecosystem permalink: /ecosystem/ nav_order: 3 has_children: false has_toc: false --- # Ecosystem ## Tooling - [create-fp-ts-lib](https://github.com/no-day/create-fp-ts-lib) - Bootstrap libraries that follow common fp-ts coding, documentation and testing patterns - [docs-ts](https://github.com/gcanti/docs-ts) - Documentation generator used by fp-ts and many fp-ts libraries ## Libraries - [fp-ts-contrib](https://github.com/gcanti/fp-ts-contrib) - A community driven utility package for fp-ts - [fp-ts-codegen](https://github.com/gcanti/fp-ts-codegen) - TypeScript code generation from a haskell-like syntax for ADT - [io-ts](https://github.com/gcanti/io-ts) - TypeScript compatible runtime type system for IO validation - [monocle-ts](https://github.com/gcanti/monocle-ts) - Functional optics: a (partial) porting of scala monocle to TypeScript - [spectacles-ts](https://github.com/anthonyjoeseph/spectacles-ts/) - A simple facade built on top of monocle-ts (autocompletes possible combinators) - [newtype-ts](https://github.com/gcanti/newtype-ts) - Implementation of newtypes in TypeScript - [logging-ts](https://github.com/gcanti/logging-ts) - Composable loggers for TypeScript - [logger-fp-ts](https://github.com/thewilkybarkid/logger-fp-ts) - Logger built on top of logging-ts - [fp-ts-routing](https://github.com/gcanti/fp-ts-routing) - A type-safe bidirectional routing library for TypeScript - [parser-ts](https://github.com/gcanti/parser-ts) - String parser combinators for TypeScript - [remote-data-ts](https://github.com/devex-web-frontend/remote-data-ts) - RemoteData type (check [this article](https://medium.com/@gcanti/slaying-a-ui-antipattern-with-flow-5eed0cfb627b)) - [retry-ts](https://github.com/gcanti/retry-ts) - Retry combinators for monadic actions that may fail - [fp-ts-local-storage](https://github.com/gcanti/fp-ts-local-storage) - fp-ts bindings for LocalStorage - [circuit-breaker-monad](https://github.com/YBogomolov/circuit-breaker-monad) - Circuit Breaker pattern as a monad - [waveguide](https://github.com/rzeigler/waveguide) - Bifunctor effect type and concurrent data structures. - [kleisli-ts](https://github.com/YBogomolov/kleisli-ts) - Kleisli arrows for bifunctor MonadThrow (IOEither, TaskEither) - [@nll/datum](https://github.com/nullpub/datum) - Datum and DatumEither types, another take on RemoteData and [flow](https://medium.com/@gcanti/slaying-a-ui-antipattern-with-flow-5eed0cfb627b) - [fetcher-ts](https://github.com/YBogomolov/fetcher-ts) - Type-safe REST HTTP client with io-ts response validation - [alga-ts](https://github.com/algebraic-graphs/typescript) – Algebraic encoding for graphs, which makes invalid graphs unrepresentable - [morphic-ts](https://github.com/sledorze/morphic-ts) - Code first Domain modeling with extensive pattern supports (matchers, predicates, lenses) with useful, extensible, customisable derivations (Show, Eq, io-ts, fast-check, jsonSchema, ..). - [graphics-ts](https://github.com/gcanti/graphics-ts) - A porting of purescript-{canvas, drawing} featuring fp-ts - [expressive-ts](https://github.com/IMax153/expressive-ts) - Comonadic builders for writing complex regular expressions - [fp-fetch](https://github.com/monstasat/fp-fetch) - Functional style, non-throwing utils for data fetching - [fp-ts-std](https://github.com/samhh/fp-ts-std) - The missing pseudo-standard library for fp-ts. - [fp-ts-lcg](https://github.com/no-day/fp-ts-lcg) - A seeded pseudorandom number generator - [fp-ts-graph](https://github.com/no-day/fp-ts-graph) - Immutable, functional graph data structure - [fp-ts-bigint](https://github.com/ericcrosson/fp-ts-bigint) - Opt-in BigInt functions - [fp-ts-generators](https://github.com/no-day/fp-ts-generators) - Seeded pseudorandom generators for structured data - [fp-ts-sized-vectors](https://github.com/no-day/fp-ts-sized-vectors) - Fixed size generic vector type carrying its length at the typelevel - [fp-ts-number-instances](https://github.com/no-day/fp-ts-number-instances) - Not fully law abiding instances for the number type - [fp-ts-react-stable-hooks](https://github.com/mblink/fp-ts-react-stable-hooks) - Reduce unnecessary rerenders when using fp-ts data types with React hooks ## Bindings - [fp-ts-rxjs](https://github.com/gcanti/fp-ts-rxjs) - fp-ts bindings for [RxJS](https://rxjs-dev.firebaseapp.com/) - [fp-ts-fluture](https://github.com/gcanti/fp-ts-fluture) - fp-ts bindings for [Fluture](https://github.com/fluture-js/Fluture) - [fp-ts-most](https://github.com/joshburgess/fp-ts-most) - fp-ts bindings for [@most/core](https://github.com/cujojs/most) - [fp-ts-ixjs](https://github.com/werk85/fp-ts-ixjs) - fp-ts bindings for [IxJS](https://github.com/ReactiveX/IxJS) ## Plugins - [fastify-funky](https://github.com/fastify/fastify-funky) - plugin that adds support for returning fp-ts Either and Task entities as handler execution results for [fastify](https://github.com/fastify/fastify) web framework ================================================ FILE: docs/guides/HKT.md ================================================ --- title: Write type class instances parent: Guides nav_order: 2 --- # How to write type class instances for your data type Let's start from a simple data structure: `Identity` ```ts // Identity.ts export type Identity = A ``` ## Functor instance Let's see how to add an instance of the `Functor` type class for `Identity` ```ts // Identity.ts import { Functor1 } from 'fp-ts/Functor' export const URI = 'Identity' export type URI = typeof URI declare module 'fp-ts/HKT' { interface URItoKind { readonly Identity: Identity } } export type Identity = A // Functor instance export const Functor: Functor1 = { URI, map: (ma, f) => f(ma) } ``` Here's the definition of `Functor1` ```ts // fp-ts/Functor.ts export interface Functor1 { readonly URI: F readonly map: (fa: Kind, f: (a: A) => B) => Kind } ``` So what's `URItoKind`, `URIS` and `Kind`? `URItoKind` is type-level map, it maps a `URI` to a concrete data type, and is populated using the [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) feature ```ts // fp-ts/HKT.ts export interface URItoKind {} ``` ```ts // Identity.ts declare module 'fp-ts/HKT' { interface URItoKind { readonly Identity: Identity // maps the key "Identity" to the type `Identity` } } ``` `URIS` is just `keyof URItoKind` and is used as a constraint in the `Functor1` interface `Kind` is using `URItoKind` internally so is able to project an abstract data type to a concrete data type. So if `URI = 'Identity'`, then `Kind` is `Identity`. ## What about type constructors of kind `* -> * -> *`? There's another triple for that: `URItoKind2`, `URIS2` and `Kind2` Example: `Either` ```ts // Either.ts import { Functor2 } from 'fp-ts/Functor' export const URI = 'Either' export type URI = typeof URI declare module 'fp-ts/HKT' { interface URItoKind2 { readonly Either: Either } } export interface Left { readonly _tag: 'Left' readonly left: E } export interface Right { readonly _tag: 'Right' readonly right: A } export type Either = Left | Right export const right = (a: A): Either => ({ _tag: 'Right', right: a }) // Functor instance export const Functor: Functor2 = { URI, map: (ma, f) => (ma._tag === 'Left' ? ma : right(f(ma.right))) } ``` And here's the definition of `Functor2` ```ts // fp-ts/Functor.ts export interface Functor2 { readonly URI: F readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } ``` ## How to type functions which abstracts over type classes Let's see how to type `lift` ```ts import { HKT } from 'fp-ts/HKT' export function lift(F: Functor): (f: (a: A) => B) => (fa: HKT) => HKT { return (f) => (fa) => F.map(fa, f) } ``` Here's the definition of `HKT` ```ts // fp-ts/HKT.ts export interface HKT { readonly _URI: URI readonly _A: A } ``` The `HKT` type represents a type constructor of kind `* -> *`. There are other `HKT` types defined in the `fp-ts/HKT.ts`, one for each kind (up to four): - `HKT2` for type constructors of kind `* -> * -> *` - `HKT3` for type constructors of kind `* -> * -> * -> *` - `HKT4` for type constructors of kind `* -> * -> * -> * -> *` There's a problem though, this doesn't type check ```ts const double = (n: number): number => n * 2 // v-- the Functor instance of Identity const doubleIdentity = lift(identity)(double) ``` With the following error ``` Argument of type 'Functor1<"Identity">' is not assignable to parameter of type 'Functor<"Identity">' ``` We need to add some overloading, one for each kind we want to support ```ts export function lift( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2) => Kind2 export function lift(F: Functor1): (f: (a: A) => B) => (fa: Kind) => Kind export function lift(F: Functor): (f: (a: A) => B) => (fa: HKT) => HKT export function lift(F: Functor): (f: (a: A) => B) => (fa: HKT) => HKT { return (f) => (fa) => F.map(fa, f) } ``` Now we can lift `double` to both `Identity` and `Either` ```ts // v-- the Functor instance of Identity const doubleIdentity = lift(identity)(double) // v-- the Functor instance of Either const doubleEither = lift(either)(double) ``` - `doubleIdentity` has type `(fa: Identity) => Identity` - `doubleEither` has type `(fa: Either) => Either` ================================================ FILE: docs/guides/code-conventions.md ================================================ --- title: Code Conventions parent: Guides nav_order: 1 --- # Code Conventions **Table of contents** - [Module structure](#module-structure) - [FAQ](#faq) - [What a `C` suffix means, e.g. `Functor2C` vs `Functor2`](#what-a-c-suffix-means-eg-functor2c-vs-functor2) - [What an `E` suffix means, e.g. `matchE`](#what-an-e-suffix-means-eg-matche) - [What a `K` suffix means, e.g. `fromEitherK` or `chainEitherK`](#what-a-k-suffix-means-eg-fromeitherk-or-chaineitherk) - [What a `T` suffix means, e.g. `sequenceT`](#what-a-t-suffix-means-eg-sequencet) - [What a `W` suffix means, e.g. `chainW` or `chainEitherKW`](#what-a-w-suffix-means-eg-chainw-or-chaineitherkw) ## Import Statements To properly import modules from `fp-ts`, you should use the following syntax: ```ts import ... from 'fp-ts/' ``` For instance, when importing the `Option` module, you can use the following code: ```ts import * as Option from 'fp-ts/Option' ``` This ensures that you're importing the required modules correctly. ## Module structure In general a module containing the definition of a data structure has the following structure - `URI` definition and module augmentation - data structure definition - companion functions - instance functions (private) - type class instance definitions (either constants or functions) ## FAQ ### What a `C` suffix means, e.g. `Functor2C` vs `Functor2` The naming convention is: - the number means the kind - `C` means *C*onstrained | Kind | Type class | Type defunctionalization | Note | | ------------------ | -------------------- | ------------------------ | -------------------------------------------------------- | | all | `Functor` | `HKT` | | | `* -> *` | `Functor1` | `Kind` | | | `* -> * -> *` | `Functor2` | `Kind2` | | | `* -> * -> *` | `Functor2C` | `Kind2` | A variant of `Functor2` where `E` is fixed | | `* -> * -> * -> *` | `Functor3` | `Kind3` | | | `* -> * -> * -> *` | `Functor3C` | `Kind3` | A variant of `Functor3` where both `R` and `E` are fixed | **Example** `Functor` The base definition ```ts export interface Functor { readonly URI: F readonly map: (fa: HKT, f: (a: A) => B) => HKT } ``` The definition for type constructors of kind `* -> * -> *` (e.g. `Either`) ```ts export interface Functor2 { readonly URI: F // v-- here E is free readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } ``` The definition for type constructors that start with kind `* -> * -> *` but need to be constrained in order to admit an instance (e.g. `Validation`). ```ts // this fixes E --v export interface Functor2C { readonly URI: F readonly _E: E // v-- here E is fixed ---------------v readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } ``` For example, `Validation` admits a `Functor` instance only if you provide a `Semigroup` instance for the failure part ```ts // this fixes E --v v-- here E is fixed const getFunctor = (S: Semigroup): Functor2C<"Validation", E> = { ... } ``` ### What an `E` suffix means, e.g. `matchE` `E` means *E*ffect. An example of its use is in the `matchE` destructor on monad transformers like `TaskOption` or `ReaderTaskEither`. **Example** Both of these destructions result in a `Task`, but in the case of `matchE` an effect (in this case in the form of a `Task`) is returned on match. ```ts import * as T from 'fp-ts/Task' import * as TO from 'fp-ts/TaskOption' import { pipe } from 'fp-ts/function' const value = TO.of('hello') // T.Task pipe( value, TO.match( () => 0, (str) => str.length ) ) // T.Task pipe( value, TO.matchE( () => T.of(0), (str) => T.of(str.length) ) ) ``` ### What a `K` suffix means, e.g. `fromEitherK` or `chainEitherK` `K` means *K*leisli. A _Kleisli arrow_ is a function with the following signature ```ts ;(a: A) => F ``` where `F` is a type constructor. **Example** Let's say we have the following parser ```ts import * as E from 'fp-ts/Either' function parse(s: string): E.Either { const n = parseFloat(s) return isNaN(n) ? E.left(new Error(`cannot decode ${JSON.stringify(s)} to number`)) : E.right(n) } ``` and a value of type `IOEither` ```ts import * as IE from 'fp-ts/IOEither' const input: IE.IOEither = IE.right('foo') ``` how can we parse `input`? We could lift the Kleisli arrow `parse`, i.e. transform a function ```ts ;(s: string) => E.Either ``` into a function ```ts ;(s: string) => IE.IOEither ``` That's what `fromEitherK` is all about ```ts import { pipe } from 'fp-ts/function' pipe(input, IE.chain(IE.fromEitherK(parse)))() // left(new Error('cannot decode "foo" to number')) // or with less boilerplate pipe(input, IE.chainEitherK(parse))() // left(new Error('cannot decode "foo" to number')) ``` ### What a `T` suffix means, e.g. `sequenceT` in `sequenceT` means *T*uple, I borrowed the name from the corresponding [Haskell function](http://hackage.haskell.org/package/tuple-0.3.0.2/docs/Data-Tuple-Sequence.html) However usually it means *T*ransformer like in "monad transformers" (e.g. `OptionT`, `EitherT`, `ReaderT`, `StateT`) ### What a `W` suffix means, e.g. `chainW` or `chainEitherKW` `W` means *W*iden. Functions that end with `W` are able to aggregate errors into a union (for `Either` based data types) or environments into an intersection (for `Reader` based data types). **Example** ```ts import * as E from 'fp-ts/Either' import * as TE from 'fp-ts/TaskEither' import { pipe } from 'fp-ts/pipeable' declare function parseString(s: string): E.Either declare function fetchUser(id: number): TE.TaskEither // this raises an error because: Type 'string' is not assignable to type 'Error' const program_ = (s: string) => pipe(s, TE.fromEitherK(parseString), TE.chain(fetchUser)) // const program: (s: string) => TE.TaskEither const program = (s: string) => pipe(s, TE.fromEitherK(parseString), TE.chainW(fetchUser)) ``` ================================================ FILE: docs/guides/do-notation.md ================================================ --- title: Do notation parent: Guides nav_order: 4 --- # Do Notation Both [Haskell](https://wiki.haskell.org/Monad#do-notation) and [PureScript](https://github.com/purescript/documentation/blob/master/language/Syntax.md#do-notation) languages provide syntactic sugar for working with monads in the form of do notation. `fp-ts` provides it's own implementation of do notation which can help to simplify effectful code. Let's take a look at an example of how do notation can help to simplify our code. Here we have a bit of code which reads two values from the command line, prints them and stores them in an object with `x` and `y` properties. ```ts import { pipe } from 'fp-ts/function' import * as T from 'fp-ts/Task' declare const print: (s: string) => T.Task declare const readLine: T.Task const main: T.Task<{ x: string; y: string }> = pipe( readLine, T.map((x) => ({ x })), T.flatMap(({ x }) => pipe( readLine, T.map((y) => ({ x, y })) ) ), T.tap(({ x }) => print(x)), T.tap(({ y }) => print(y)) ) ``` Notice how we need a nested `pipe` to allow the combination of `x` and `y` values into a single object. Here's how we can write `main` with do notation (we'll call it `mainDo`): ```ts const mainDo: T.Task<{ x: string; y: string }> = pipe( T.Do, T.bind('x', () => readLine), T.bind('y', () => readLine), T.tap(({ x }) => print(x)), T.tap(({ y }) => print(y)) ) ``` This will look very familiar to those who have prior experience with Purescript or Haskell where we could write something like: ```haskell main :: IO (String, String) main = do x <- readLn y <- readLn print x print y return (x, y) ``` Note that due to the lack of type-classes in Typescript, when working with `fp-ts` we need to import everything from the appropriate module. In the previous example, we use specific `Do`, `bind`, `map` and `chainFirst` functions imported from the `Task` module as we were working with the `Task` type. If we were to write the same code using the `IO` monad, we would need to import everything from the `IO` module like so: ```ts import { pipe } from 'fp-ts/function' import * as IO from 'fp-ts/IO' declare const print: (s: string) => IO.IO declare const readLine: IO.IO const mainDo: IO.IO<{ x: string; y: string }> = pipe( IO.Do, IO.bind('x', () => readLine), IO.bind('y', () => readLine), IO.tap(({ x }) => print(x)), IO.tap(({ y }) => print(y)) ) ``` ## Examples Using `bindTo`: ```ts import { pipe } from 'fp-ts/function' import * as T from 'fp-ts/Task' declare const print: (s: string) => T.Task declare const readLine: T.Task pipe( readLine, T.bindTo('x'), T.bind('y', () => readLine), T.tap(({ x }) => print(x)), T.tap(({ y }) => print(y)) ) ``` Performing actions in parallel with `apS`: ```ts import { pipe } from 'fp-ts/function' import * as T from 'fp-ts/Task' declare const encryptValue: (val: string) => T.Task pipe( T.Do, T.apS('x', encryptValue('hello')), T.apS('y', encryptValue('world')), T.map(({ x, y }) => { /* ... */ }) ) ``` # FAQ > What does `IO.Do` do exactly? `IO.Do` is just an alias for `IO.of({})` where `{}` is an empty record. You build up a record using `bind` which accepts a key and a function that accepts the current state of the record and returns an effect of some value to store under the key. The record becomes kind of like a scope to put intermediate values in when you are chaining effects. ================================================ FILE: docs/guides/index.md ================================================ --- title: Guides permalink: /guides/ nav_order: 5 has_children: true has_toc: true --- # Guides ================================================ FILE: docs/guides/purescript.md ================================================ --- title: Migrate from PureScript/Haskell parent: Guides nav_order: 3 --- # Migrate from PureScript/Haskell This guide shows you how to use `fp-ts` concepts if you have prior experience with [PureScript](http://www.purescript.org/) or [Haskell](https://www.haskell.org/). --- ## Do notation PureScript ```purescript do print "foo" print "bar" x <- readLine print x ``` TypeScript ```ts import { pipe } from 'fp-ts/function' import * as T from 'fp-ts/Task' declare const print: (s: string) => T.Task declare const readLine: T.Task pipe( T.Do, T.tap(() => print('foo')), T.tap(() => print('bar')), T.bind('x', () => readLine), T.flatMap(({ x }) => print(x)) ) ``` ## Data PureScript ```purescript -- ↓-- type data Foo = Bar String | Baz Boolean -- ↑------------↑-- constructors ``` TypeScript ```ts interface Bar { readonly _tag: 'Bar' readonly value: string } interface Baz { readonly _tag: 'Baz' readonly value: boolean } // type type Foo = Bar | Baz // constructors const Bar = (value: string): Foo => ({ _tag: 'Bar', value }) const Baz = (value: boolean): Foo => ({ _tag: 'Baz', value }) ``` ## Polymorphic data PureScript ```purescript data Option a = None | Some a ``` TypeScript ```ts export const URI = 'Option' export type URI = typeof URI declare module 'fp-ts/HKT' { interface URItoKind { readonly [URI]: Option } } export interface None { readonly _tag: 'None' } export interface Some { readonly _tag: 'Some' readonly value: A } export type Option = None | Some export const none: Option = { _tag: 'None' } export const some = (a: A): Option => ({ _tag: 'Some', value: a }) ``` ## Pattern matching PureScript ```purescript maybe :: forall a b. b -> (a -> b) -> Option a -> b maybe b _ None = b maybe _ f (Some a) = f a ``` TypeScript ```ts // here TypeScript also provides exhaustiveness check const maybe = (onNone: () => B, onSome: (a: A) => B) => (fa: Option): B => { switch (fa._tag) { case 'None': return onNone() case 'Some': return onSome(fa.value) } } ``` ## Type classes PureScript ```purescript class Functor f where map :: forall a b. (a -> b) -> f a -> f b ``` TypeScript ```ts export interface Functor { readonly URI: F readonly map: (fa: HKT, f: (a: A) => B) => HKT } export interface Functor1 { readonly URI: F readonly map: (fa: Kind, f: (a: A) => B) => Kind } export interface Functor2 { readonly URI: F readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } // etc... ``` ## Instances PureScript ```purescript instance functorOption :: Functor Option where map fn (Some x) = Some (fn x) map _ _ = None ``` TypeScript ```ts import { Functor1 } from 'fp-ts/Functor' import { pipe } from 'fp-ts/function' const functorOption: Functor1 = { URI, map: (fa, f) => pipe( fa, maybe( () => none, (a) => some(f(a)) ) ) } ``` ## Type constraints PureScript ```purescript instance semigroupOption :: Semigroup a => Semigroup (Option a) where append None y = y append x None = x append (Some x) (Some y) = Some (x <> y) instance monoidOption :: Semigroup a => Monoid (Option a) where mempty = None ``` TypeScript ```ts import { Semigroup } from 'fp-ts/Semigroup' import { Monoid } from 'fp-ts/Monoid' // ↓ the constraint is implemented as an additional parameter function getMonoid(S: Semigroup): Monoid> { return { concat: (x, y) => { if (x._tag === 'Some' && y._tag === 'Some') { return some(S.concat(x.value, y.value)) } else if (x._tag === 'Some') { return y } else { return x } }, empty: none } } ``` ## Where's my `f <$> fa <*> fb`? A few options: ```ts import * as T from 'fp-ts/Task' import { pipe } from 'fp-ts/function' declare const fa: T.Task declare const fb: T.Task declare const f: (a: number) => (b: string) => boolean const result1 = pipe(fa, T.map(f), T.ap(fb)) // ..or.. const result2 = pipe(T.of(f), T.ap(fa), T.ap(fb)) ``` ================================================ FILE: docs/guides/upgrade-to-v2.md ================================================ --- title: Upgrade to fp-ts 2.x parent: Guides nav_order: 5 --- # Upgrade to version 2.x `fp-ts@2.x` brings with it some major improvements, but also breaking changes and the removal of deprecated APIs. This document will help you understand what changed and how you can upgrade your existing codebase. {: .fs-6 .fw-300 } --- The major changes in `fp-ts@2.x` are: - Requires TypeScript 3.5+ - `fp-ts@1.19.x` has been released with backported 2.x features for a gradual upgrade path - Data types are no longer implemented as classes, resulting in a new API using `pipe` - The `run()` method on `IO`, `Task`, etc. has been replaced with a thunk - Functions accepting fallback values are now always lazy (e.g. `getOrElseL` is now just `getOrElse`) - Deprecations - `HKT`: Replaced `Type` with `Kind` - Replaced `Setoid` with `Eq` - Several modules were removed, e.g. `Exception`, `Free`, `StrMap`, `Trace`, `Validation`, … - Read the [full changelog](https://github.com/gcanti/fp-ts/pull/881) for all the changes ## Upgrading from version 1.x You can gradually upgrade your existing codebase using the `fp-ts@1.19.x` release; the new `fp-ts@2.x` APIs have been backported to this release. 1. Upgrade TypeScript to version 3.5+ 1. Install `fp-ts@1.19.x`, which contains the new `fp-ts@2.x` APIs 1. Optional: activate the `@obsolete` rule for `tslint` to get guidance on what to change 1. Familiarise yourself with [the new API](https://github.com/gcanti/fp-ts/pull/881) 1. Gradually replace the existing code with the new API 1. Upgrade to `fp-ts@2.x` and make sure to also upgrade all dependencies that rely on `fp-ts` ### tslint rule In order to make easier to spot all the occurrences of chainable APIs without depending on `@deprecated`, which would force you to migrate in one shot, a custom tslint rule is provided (`@obsolete`). Add the following lines to your `tslint.json` to turn the `@obsolete` rule on: ```diff { + "rulesDirectory": ["./node_modules/fp-ts/rules"], "rules": { + "obsolete": true } } ``` This rule is available in the [1.19.x branch](https://github.com/gcanti/fp-ts/blob/1.19.5/rules/obsoleteRule.js). ### Dependencies Don't forget to update your dependencies: libraries that use `fp-ts` like [io-ts](https://github.com/gcanti/io-ts) or [monocle-ts](https://github.com/gcanti/monocle-ts) have to be upgraded to their `fp-ts@2.x` compatible versions. ## The new API In `fp-ts@2.x` data types are no longer implemented with classes; the biggest change resulting from this is that the chainable API has been removed. As an alternative, a `pipe` function is provided, along with suitable data-last top level functions (one for each deprecated method). This is best shown with an example: v1 (deprecated) {: .label .label-red .mt-5 } ```ts import * as O from 'fp-ts/Option' O.some(1) .map((n) => n * 2) .chain((n) => (n === 0 ? O.none : O.some(1 / n))) .filter((n) => n > 1) .foldL( () => 'ko', () => 'ok' ) ``` v2 (new) {: .label .label-green .mt-5 } ```ts import * as O from 'fp-ts/Option' import { pipe } from 'fp-ts/pipeable' pipe( O.some(1), O.map((n) => n * 2), O.chain((n) => (n === 0 ? O.none : O.some(1 / n))), O.filter((n) => n > 1), O.fold( () => 'ko', () => 'ok' ) ) ``` We recommend to use `pipe` even if you work with just one function, as it allows TypeScript to infer the types automatically. It's also easier to migrate existing code, because the argument order remains the same. ```ts import * as O from 'fp-ts/Option' import { pipe } from 'fp-ts/function' pipe( O.some(1), O.fold( () => 'ko', (n) => `ok: ${n}` ) ) ``` If you are interested, read about the [benefits of the new API](https://github.com/gcanti/fp-ts/issues/823#issuecomment-486066792) in the technical discussion leading to `fp-ts@2.x`. ### Replacement of the `run()` method The `run()` method on `IO`, `Task`, etc. has been replaced with a thunk: v1 (deprecated) {: .label .label-red .mt-5 } ```ts import { Task } from 'fp-ts/Task' const deepThought = new Task(() => Promise.resolve(42)) deepThought.run().then((n) => { console.log(`The answer is ${n}.`) }) ``` v2 (new) {: .label .label-green .mt-5 } ```ts import { Task } from 'fp-ts/Task' const deepThought: Task = () => Promise.resolve(42) deepThought().then((n) => { console.log(`The answer is ${n}.`) }) ``` ### Functions accepting fallback values are now always lazy In many places `fp-ts@1.x` provided two versions of methods: v1 (deprecated) {: .label .label-red .mt-5 } ```ts import * as O from 'fp-ts/Option' O.some(1).getOrElse(0) // Direct O.some(1).getOrElseL(() => 0) // Lazy, i.e. only run if needed ``` v2 (new) {: .label .label-green .mt-5 } In `fp-ts@2.x` the API has been simplified, only the lazy variants have been kept with the `L` suffix removed. ```ts import * as O from 'fp-ts/Option' import { pipe } from 'fp-ts/function' pipe( O.some(1), O.getOrElse(() => 0) ) ``` ### Removed modules - `Exception` - `Free` - `FreeGroup` - `IxIO` - `IxMonad` - `Monoidal` - `Pair` - `StrMap` (use [Record](../modules/Record.ts) instead) - `Trace` - `Validation` (use [Either](../modules/Either.ts)'s `getValidation`) - `Zipper` ## References If you're interested in reading up on how this release came to be, have a look at the following discussions: - The technical [discussion leading to v2](https://github.com/gcanti/fp-ts/issues/823) - [Version 1.19 (backport)](https://github.com/gcanti/fp-ts/pull/881) - [The 2.0.0 release](https://github.com/gcanti/fp-ts/commit/7bda18e34eed996a08afdd6a0a61025087f99593) ================================================ FILE: docs/index.md ================================================ --- title: Introduction permalink: / nav_order: 1 has_children: false has_toc: false --- fp-ts logo # Typed functional programming in TypeScript `fp-ts` provides developers with popular patterns and reliable abstractions from typed functional languages in TypeScript. {: .fs-6 .fw-300 } **Disclaimer**. Teaching functional programming is out of scope of this project, so the documentation assumes you already know what FP is. ## Core Concepts The goal of `fp-ts` is to empower developers to write pure FP apps and libraries built atop higher order abstractions. It includes the most popular data types, type classes, and abstractions from languages like [Haskell](https://www.haskell.org), [PureScript](https://www.purescript.org), and [Scala](https://www.scala-lang.org). ## Functions Functional programming is all about pure functions and how to compose them into bigger structures. `fp-ts` provides a few general [functions](./modules/function.ts.html) to support you with composition, constant functions, and more. ## Data Types Data types are the practical part of `fp-ts`: you can instantiate them with your data to gain properties and functionality that are useful for solving a specific need. Because data types all share common interfaces (through [type classes](#type-classes)), once you learn how to use one data type, you can apply the same concepts to the others. Many functions in `fp-ts` use [ad hoc polymorphism](https://en.wikipedia.org/wiki/Ad_hoc_polymorphism), meaning that they have a single implementation that can deal with arguments of different types. To make this work, it is often necessary to provide a data type _instance_ that provides functionality that is specific to the data type. **Note**. Data types are not stack safe and there is no trampolining implementation. But for traversing and sequencing lists there is a stack safe and optimized version in each data types. ## Type Classes Type classes provide the theoretical underpinnings of `fp-ts`: they describe what you can do with your data. To guarantee that they can be safely composed, they are built on laws rooted in abstract algebra and [category theory](https://en.wikipedia.org/wiki/Category_theory). ## Higher Kinded Types A distinctive feature of `fp-ts` with respect to other functional libraries is its implementation of [Higher Kinded Types](), which TypeScript doesn't support natively. The idea for emulating higher kinded types in TypeScript is based on [Lightweight higher-kinded polymorphism](https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf). ================================================ FILE: docs/learning-resources.md ================================================ --- title: Learning Resources permalink: /learning-resources/ nav_order: 2 has_children: false has_toc: false --- # Learning Resources - [Mostly adequate guide to FP](https://github.com/MostlyAdequate/mostly-adequate-guide) by [@DrBoolean](https://github.com/DrBoolean) - [The State monad](https://paulgray.net/the-state-monad/) by Paul Gray - [Functional Programming with TypeScript](https://www.youtube.com/playlist?list=PLuPevXgCPUIMbCxBEnc1dNwboH6e2ImQo) by Sahand Javid - [fp-ts Tutorial series on YouTube](https://www.youtube.com/playlist?list=PLUMXrUa_EuePN94nJ2hAui5nWDj8RO3lH) by [@MrFunctor](https://github.com/MrFunctor) ## Getting started with fp-ts series - [Interoperability with non functional code](https://dev.to/gcanti/interoperability-with-non-functional-code-using-fp-ts-432e) - [Eq](https://dev.to/gcanti/getting-started-with-fp-ts-setoid-39f3) - [Ord](https://dev.to/gcanti/getting-started-with-fp-ts-ord-5f1e) - [Semigroup](https://dev.to/gcanti/getting-started-with-fp-ts-semigroup-2mf7) - [Monoid](https://dev.to/gcanti/getting-started-with-fp-ts-monoid-ja0) - [Category](https://dev.to/gcanti/getting-started-with-fp-ts-category-4c9a) - [Functor](https://dev.to/gcanti/getting-started-with-fp-ts-functor-36ek) - [Applicative](https://dev.to/gcanti/getting-started-with-fp-ts-applicative-1kb3) - [Monad](https://dev.to/gcanti/getting-started-with-fp-ts-monad-6k) - [Either vs Validation](https://dev.to/gcanti/getting-started-with-fp-ts-either-vs-validation-5eja) - [IO](https://dev.to/gcanti/getting-started-with-fp-ts-io-36p6) - [Reader](https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5) ## Functional design series - [Combinators Part I](https://dev.to/gcanti/functional-design-combinators-14pn) - [Combinators Part II](https://dev.to/gcanti/functional-design-how-to-make-the-time-combinator-more-general-3fge) - [Tagless final](https://dev.to/gcanti/functional-design-tagless-final-332k) - [Smart constructors](https://dev.to/gcanti/functional-design-smart-constructors-14nb) - [Introduction to property based testing](https://dev.to/gcanti/introduction-to-property-based-testing-17nk) - [Algebraic Data Types](https://dev.to/gcanti/functional-design-algebraic-data-types-36kf) ## Advanced code examples - "`fp-ts` to the max" (TypeScript port of John De Goes's ["FP to the max"](https://www.youtube.com/watch?v=sxudIMiOo68) in Scala) - [Part I](https://github.com/gcanti/fp-ts/blob/master/examples/fp-ts-to-the-max-I.ts) - [Part II](https://github.com/gcanti/fp-ts/blob/master/examples/fp-ts-to-the-max-II.ts) ## Community documentation - [fp-ts recipes](https://grossbart.github.io/fp-ts-recipes/) – A collection of practical recipes for working with `fp-ts` - [Mostly adequate guide to FP-TS](https://cjonas.gitbook.io/mostly-adequate-fp-ts/) partial rewrite by ChuckJonas - [Book: Introduction to Functional Programming by Giulio Canti](https://github.com/enricopolanski/functional-programming) English translation by Enrico Polanski ## Community Blog Posts - [When An Error Is Not An Exception](https://dev.to/vncz/forewords-and-domain-model-1p13) — How we rewrote the core of Prism to make it almost totally functional - [Introduction series to FP-TS](https://ybogomolov.me/01-higher-kinded-types) by Yuriy Bogomolov - [The ReaderTaskMonad](https://andywhite.xyz/posts/) by Andy White - [FP-TS for HTTP-requests](https://kimmosaaskilahti.fi/blog/2019/08/29/using-fp-ts-for-http-requests-and-validation/) by Kimmo Sasskilahti - [Basic introduction to FP-TS](https://davetayls.me/blog/2018/06/09/fp-ts-02-handling-error-cases) by Dave Tayls - [Practical guide to FP-TS](https://rlee.dev/practical-guide-to-fp-ts-part-1) by Ryan Lee ================================================ FILE: docs/modules/Alt.ts.md ================================================ --- title: Alt.ts nav_order: 1 parent: Modules --- ## Alt overview The `Alt` type class identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`, like `Array` or `Option`, rather than concrete types like `string` or `number`. `Alt` instances are required to satisfy the following laws: 1. Associativity: `A.alt(A.alt(fa, ga), ha) <-> A.alt(fa, A.alt(ga, ha))` 2. Distributivity: `A.map(A.alt(fa, ga), ab) <-> A.alt(A.map(fa, ab), A.map(ga, ab))` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Alt (interface)](#alt-interface) - [Alt1 (interface)](#alt1-interface) - [Alt2 (interface)](#alt2-interface) - [Alt2C (interface)](#alt2c-interface) - [Alt3 (interface)](#alt3-interface) - [Alt3C (interface)](#alt3c-interface) - [Alt4 (interface)](#alt4-interface) - [utils](#utils) - [altAll](#altall) --- # model ## Alt (interface) **Signature** ```ts export interface Alt extends Functor { readonly alt:
(fa: HKT, that: LazyArg>) => HKT } ``` Added in v2.0.0 ## Alt1 (interface) **Signature** ```ts export interface Alt1 extends Functor1 { readonly alt: (fa: Kind, that: LazyArg>) => Kind } ``` Added in v2.0.0 ## Alt2 (interface) **Signature** ```ts export interface Alt2 extends Functor2 { readonly alt: (fa: Kind2, that: LazyArg>) => Kind2 } ``` Added in v2.0.0 ## Alt2C (interface) **Signature** ```ts export interface Alt2C extends Functor2C { readonly alt: (fa: Kind2, that: LazyArg>) => Kind2 } ``` Added in v2.0.0 ## Alt3 (interface) **Signature** ```ts export interface Alt3 extends Functor3 { readonly alt: (fa: Kind3, that: LazyArg>) => Kind3 } ``` Added in v2.0.0 ## Alt3C (interface) **Signature** ```ts export interface Alt3C extends Functor3C { readonly alt: (fa: Kind3, that: LazyArg>) => Kind3 } ``` Added in v2.2.0 ## Alt4 (interface) **Signature** ```ts export interface Alt4 extends Functor4 { readonly alt: (fa: Kind4, that: LazyArg>) => Kind4 } ``` Added in v2.0.0 # utils ## altAll **Signature** ```ts export declare function altAll( F: Alt4 ): (startWith: Kind4) => (as: ReadonlyArray>) => Kind4 export declare function altAll( F: Alt3 ): (startWith: Kind3) => (as: ReadonlyArray>) => Kind3 export declare function altAll( F: Alt3C ): (startWith: Kind3) => (as: ReadonlyArray>) => Kind3 export declare function altAll( F: Alt2 ): (startWith: Kind2) => (as: ReadonlyArray>) => Kind2 export declare function altAll( F: Alt2C ): (startWith: Kind2) => (as: ReadonlyArray>) => Kind2 export declare function altAll( F: Alt1 ): (startWith: Kind) => (as: ReadonlyArray>) => Kind export declare function altAll(F: Alt): (startWith: HKT) => (as: ReadonlyArray>) => HKT ``` Added in v2.11.0 ================================================ FILE: docs/modules/Alternative.ts.md ================================================ --- title: Alternative.ts nav_order: 2 parent: Modules --- ## Alternative overview The `Alternative` type class extends the `Alt` type class with a value that should be the left and right identity for `alt`. It is similar to `Monoid`, except that it applies to types of kind `* -> *`, like `Array` or `Option`, rather than concrete types like `string` or `number`. `Alternative` instances should satisfy the following laws: 1. Left identity: `A.alt(zero, fa) <-> fa` 2. Right identity: `A.alt(fa, zero) <-> fa` 3. Annihilation: `A.map(zero, f) <-> zero` 4. Distributivity: `A.ap(A.alt(fab, gab), fa) <-> A.alt(A.ap(fab, fa), A.ap(gab, fa))` 5. Annihilation: `A.ap(zero, fa) <-> zero` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Alternative (interface)](#alternative-interface) - [Alternative1 (interface)](#alternative1-interface) - [Alternative2 (interface)](#alternative2-interface) - [Alternative2C (interface)](#alternative2c-interface) - [Alternative3 (interface)](#alternative3-interface) - [Alternative3C (interface)](#alternative3c-interface) - [Alternative4 (interface)](#alternative4-interface) - [utils](#utils) - [altAll](#altall) - [getAlternativeMonoid](#getalternativemonoid) --- # model ## Alternative (interface) **Signature** ```ts export interface Alternative extends Applicative, Alt, Zero {} ``` Added in v2.0.0 ## Alternative1 (interface) **Signature** ```ts export interface Alternative1 extends Applicative1, Alt1, Zero1 {} ``` Added in v2.0.0 ## Alternative2 (interface) **Signature** ```ts export interface Alternative2 extends Applicative2, Alt2, Zero2 {} ``` Added in v2.0.0 ## Alternative2C (interface) **Signature** ```ts export interface Alternative2C extends Applicative2C, Alt2C, Zero2C {} ``` Added in v2.0.0 ## Alternative3 (interface) **Signature** ```ts export interface Alternative3 extends Applicative3, Alt3, Zero3 {} ``` Added in v2.0.0 ## Alternative3C (interface) **Signature** ```ts export interface Alternative3C extends Applicative3C, Alt3C, Zero3C {} ``` Added in v2.10.0 ## Alternative4 (interface) **Signature** ```ts export interface Alternative4 extends Applicative4, Alt4, Zero4 {} ``` Added in v2.10.0 # utils ## altAll **Signature** ```ts export declare function altAll( F: Alternative4 ): (as: ReadonlyArray>) => Kind4 export declare function altAll( F: Alternative3 ): (as: ReadonlyArray>) => Kind3 export declare function altAll( F: Alternative3C ): (as: ReadonlyArray>) => Kind3 export declare function altAll( F: Alternative2 ): (as: ReadonlyArray>) => Kind2 export declare function altAll( F: Alternative2C ):
(as: ReadonlyArray>) => Kind2 export declare function altAll(F: Alternative1): (as: ReadonlyArray>) => Kind export declare function altAll(F: Alternative): (as: ReadonlyArray>) => HKT ``` Added in v2.11.0 ## getAlternativeMonoid Lift a semigroup into a monoid alternative 'F', the inner values are concatenated using the provided `Semigroup`. **Signature** ```ts export declare function getAlternativeMonoid( F: Alternative4 ): (S: Semigroup) => Monoid> export declare function getAlternativeMonoid( F: Alternative3 ): (S: Semigroup) => Monoid> export declare function getAlternativeMonoid( F: Alternative3C ): (S: Semigroup) => Monoid> export declare function getAlternativeMonoid( F: Alternative2 ): (S: Semigroup) => Monoid> export declare function getAlternativeMonoid( F: Alternative2C ): (S: Semigroup) => Monoid> export declare function getAlternativeMonoid( F: Alternative1 ): (S: Semigroup) => Monoid> export declare function getAlternativeMonoid(F: Alternative): (S: Semigroup) => Monoid> ``` Added in v2.13.0 ================================================ FILE: docs/modules/Applicative.ts.md ================================================ --- title: Applicative.ts nav_order: 3 parent: Modules --- ## Applicative overview The `Applicative` type class extends the `Apply` type class with a `of` function, which can be used to create values of type `f a` from values of type `a`. Where `Apply` provides the ability to lift functions of two or more arguments to functions whose arguments are wrapped using `f`, and `Functor` provides the ability to lift functions of one argument, `pure` can be seen as the function which lifts functions of _zero_ arguments. That is, `Applicative` functors support a lifting operation for any number of function arguments. Instances must satisfy the following laws in addition to the `Apply` laws: 1. Identity: `A.ap(A.of(a => a), fa) <-> fa` 2. Homomorphism: `A.ap(A.of(ab), A.of(a)) <-> A.of(ab(a))` 3. Interchange: `A.ap(fab, A.of(a)) <-> A.ap(A.of(ab => ab(a)), fab)` Note. `Functor`'s `map` can be derived: `A.map(x, f) = A.ap(A.of(f), x)` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Applicative (interface)](#applicative-interface) - [Applicative1 (interface)](#applicative1-interface) - [Applicative2 (interface)](#applicative2-interface) - [Applicative2C (interface)](#applicative2c-interface) - [Applicative3 (interface)](#applicative3-interface) - [Applicative3C (interface)](#applicative3c-interface) - [Applicative4 (interface)](#applicative4-interface) - [utils](#utils) - [getApplicativeMonoid](#getapplicativemonoid) - [zone of death](#zone-of-death) - [~~ApplicativeComposition11~~ (interface)](#applicativecomposition11-interface) - [~~ApplicativeComposition12C~~ (interface)](#applicativecomposition12c-interface) - [~~ApplicativeComposition12~~ (interface)](#applicativecomposition12-interface) - [~~ApplicativeComposition21~~ (interface)](#applicativecomposition21-interface) - [~~ApplicativeComposition22C~~ (interface)](#applicativecomposition22c-interface) - [~~ApplicativeComposition22~~ (interface)](#applicativecomposition22-interface) - [~~ApplicativeComposition2C1~~ (interface)](#applicativecomposition2c1-interface) - [~~ApplicativeCompositionHKT1~~ (interface)](#applicativecompositionhkt1-interface) - [~~ApplicativeCompositionHKT2C~~ (interface)](#applicativecompositionhkt2c-interface) - [~~ApplicativeCompositionHKT2~~ (interface)](#applicativecompositionhkt2-interface) - [~~ApplicativeComposition~~ (interface)](#applicativecomposition-interface) - [~~getApplicativeComposition~~](#getapplicativecomposition) --- # model ## Applicative (interface) **Signature** ```ts export interface Applicative extends Apply, Pointed {} ``` Added in v2.0.0 ## Applicative1 (interface) **Signature** ```ts export interface Applicative1 extends Apply1, Pointed1 {} ``` Added in v2.0.0 ## Applicative2 (interface) **Signature** ```ts export interface Applicative2 extends Apply2, Pointed2 {} ``` Added in v2.0.0 ## Applicative2C (interface) **Signature** ```ts export interface Applicative2C extends Apply2C, Pointed2C {} ``` Added in v2.0.0 ## Applicative3 (interface) **Signature** ```ts export interface Applicative3 extends Apply3, Pointed3 {} ``` Added in v2.0.0 ## Applicative3C (interface) **Signature** ```ts export interface Applicative3C extends Apply3C, Pointed3C {} ``` Added in v2.2.0 ## Applicative4 (interface) **Signature** ```ts export interface Applicative4 extends Apply4, Pointed4 {} ``` Added in v2.0.0 # utils ## getApplicativeMonoid Lift a monoid into 'F', the inner values are concatenated using the provided `Monoid`. **Signature** ```ts export declare function getApplicativeMonoid( F: Applicative4 ): (M: Monoid
) => Monoid> export declare function getApplicativeMonoid( F: Applicative3 ): (M: Monoid) => Monoid> export declare function getApplicativeMonoid( F: Applicative3C ): (M: Monoid) => Monoid> export declare function getApplicativeMonoid( F: Applicative2 ): (M: Monoid) => Monoid> export declare function getApplicativeMonoid( F: Applicative2C ): (M: Monoid) => Monoid> export declare function getApplicativeMonoid( F: Applicative1 ): (M: Monoid) => Monoid> export declare function getApplicativeMonoid(F: Applicative): (M: Monoid) => Monoid> ``` Added in v2.10.0 # zone of death ## ~~ApplicativeComposition11~~ (interface) **Signature** ```ts export interface ApplicativeComposition11 extends FunctorComposition11 { readonly of: (a: A) => Kind> readonly ap: (fgab: Kind B>>, fga: Kind>) => Kind> } ``` Added in v2.0.0 ## ~~ApplicativeComposition12C~~ (interface) **Signature** ```ts export interface ApplicativeComposition12C extends FunctorComposition12C { readonly of: (a: A) => Kind> readonly ap: (fgab: Kind B>>, fga: Kind>) => Kind> } ``` Added in v2.0.0 ## ~~ApplicativeComposition12~~ (interface) **Signature** ```ts export interface ApplicativeComposition12 extends FunctorComposition12 { readonly of: (a: A) => Kind> readonly ap: ( fgab: Kind B>>, fga: Kind> ) => Kind> } ``` Added in v2.0.0 ## ~~ApplicativeComposition21~~ (interface) **Signature** ```ts export interface ApplicativeComposition21 extends FunctorComposition21 { readonly of: (a: A) => Kind2> readonly ap: ( fgab: Kind2 B>>, fga: Kind2> ) => Kind2> } ``` Added in v2.0.0 ## ~~ApplicativeComposition22C~~ (interface) **Signature** ```ts export interface ApplicativeComposition22C extends FunctorComposition22C { readonly of: (a: A) => Kind2> readonly ap: ( fgab: Kind2 B>>, fga: Kind2> ) => Kind2> } ``` Added in v2.0.0 ## ~~ApplicativeComposition22~~ (interface) **Signature** ```ts export interface ApplicativeComposition22 extends FunctorComposition22 { readonly of: (a: A) => Kind2> readonly ap: ( fgab: Kind2 B>>, fga: Kind2> ) => Kind2> } ``` Added in v2.0.0 ## ~~ApplicativeComposition2C1~~ (interface) **Signature** ```ts export interface ApplicativeComposition2C1 extends FunctorComposition2C1 { readonly of: (a: A) => Kind2> readonly ap: (fgab: Kind2 B>>, fga: Kind2>) => Kind2> } ``` Added in v2.0.0 ## ~~ApplicativeCompositionHKT1~~ (interface) **Signature** ```ts export interface ApplicativeCompositionHKT1 extends FunctorCompositionHKT1 { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } ``` Added in v2.0.0 ## ~~ApplicativeCompositionHKT2C~~ (interface) **Signature** ```ts export interface ApplicativeCompositionHKT2C extends FunctorCompositionHKT2C { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } ``` Added in v2.0.0 ## ~~ApplicativeCompositionHKT2~~ (interface) **Signature** ```ts export interface ApplicativeCompositionHKT2 extends FunctorCompositionHKT2 { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } ``` Added in v2.0.0 ## ~~ApplicativeComposition~~ (interface) **Signature** ```ts export interface ApplicativeComposition extends FunctorComposition { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } ``` Added in v2.0.0 ## ~~getApplicativeComposition~~ Use [`ap`](./Apply.ts.html#ap) instead. **Signature** ```ts export declare function getApplicativeComposition( F: Applicative2, G: Applicative2C ): ApplicativeComposition22C export declare function getApplicativeComposition( F: Applicative2, G: Applicative2 ): ApplicativeComposition22 export declare function getApplicativeComposition( F: Applicative2, G: Applicative2C ): ApplicativeComposition22C export declare function getApplicativeComposition( F: Applicative2, G: Applicative1 ): ApplicativeComposition21 export declare function getApplicativeComposition( F: Applicative1, G: Applicative2 ): ApplicativeComposition12 export declare function getApplicativeComposition( F: Applicative1, G: Applicative2C ): ApplicativeComposition12C export declare function getApplicativeComposition( F: Applicative1, G: Applicative1 ): ApplicativeComposition11 export declare function getApplicativeComposition( F: Applicative, G: Applicative2 ): ApplicativeCompositionHKT2 export declare function getApplicativeComposition( F: Applicative, G: Applicative2C ): ApplicativeCompositionHKT2C export declare function getApplicativeComposition( F: Applicative, G: Applicative1 ): ApplicativeCompositionHKT1 export declare function getApplicativeComposition( F: Applicative, G: Applicative ): ApplicativeComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/Apply.ts.md ================================================ --- title: Apply.ts nav_order: 4 parent: Modules --- ## Apply overview The `Apply` class provides the `ap` which is used to apply a function to an argument under a type constructor. `Apply` can be used to lift functions of two or more arguments to work on values wrapped with the type constructor `f`. Instances must satisfy the following law in addition to the `Functor` laws: 1. Associative composition: `F.ap(F.ap(F.map(fbc, bc => ab => a => bc(ab(a))), fab), fa) <-> F.ap(fbc, F.ap(fab, fa))` Formally, `Apply` represents a strong lax semi-monoidal endofunctor. **Example** ```ts import * as O from 'fp-ts/Option' import { pipe } from 'fp-ts/function' const f = (a: string) => (b: number) => (c: boolean) => a + String(b) + String(c) const fa: O.Option = O.some('s') const fb: O.Option = O.some(1) const fc: O.Option = O.some(true) assert.deepStrictEqual( pipe( // lift a function O.some(f), // apply the first argument O.ap(fa), // apply the second argument O.ap(fb), // apply the third argument O.ap(fc) ), O.some('s1true') ) ``` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Apply (interface)](#apply-interface) - [Apply1 (interface)](#apply1-interface) - [Apply2 (interface)](#apply2-interface) - [Apply2C (interface)](#apply2c-interface) - [Apply3 (interface)](#apply3-interface) - [Apply3C (interface)](#apply3c-interface) - [Apply4 (interface)](#apply4-interface) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apS](#aps) - [apSecond](#apsecond) - [getApplySemigroup](#getapplysemigroup) - [sequenceS](#sequences) - [sequenceT](#sequencet) --- # model ## Apply (interface) **Signature** ```ts export interface Apply extends Functor { readonly ap: (fab: HKT B>, fa: HKT) => HKT } ``` Added in v2.0.0 ## Apply1 (interface) **Signature** ```ts export interface Apply1 extends Functor1 { readonly ap: (fab: Kind B>, fa: Kind) => Kind } ``` Added in v2.0.0 ## Apply2 (interface) **Signature** ```ts export interface Apply2 extends Functor2 { readonly ap: (fab: Kind2 B>, fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## Apply2C (interface) **Signature** ```ts export interface Apply2C extends Functor2C { readonly ap: (fab: Kind2 B>, fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## Apply3 (interface) **Signature** ```ts export interface Apply3 extends Functor3 { readonly ap: (fab: Kind3 B>, fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## Apply3C (interface) **Signature** ```ts export interface Apply3C extends Functor3C { readonly ap: (fab: Kind3 B>, fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## Apply4 (interface) **Signature** ```ts export interface Apply4 extends Functor4 { readonly ap: (fab: Kind4 B>, fa: Kind4) => Kind4 } ``` Added in v2.0.0 # utils ## ap `ap` composition. **Signature** ```ts export declare function ap( F: Apply4, G: Apply4 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply4, G: Apply3 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply4, G: Apply3C ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply4, G: Apply2 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply4, G: Apply2C ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply4, G: Apply1 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply3C, G: Apply4 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C, G: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C, G: Apply3C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C, G: Apply2 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C, G: Apply2C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C, G: Apply1 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3, G: Apply4 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3, G: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3, G: Apply3C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3, G: Apply2 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3, G: Apply2C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3, G: Apply1 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply2C, G: Apply4 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C, G: Apply3 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C, G: Apply3C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C, G: Apply2 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C, G: Apply2C ):
( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C, G: Apply1 ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2, G: Apply4 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2, G: Apply3 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2, G: Apply3C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2, G: Apply2 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2, G: Apply2C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2, G: Apply1 ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply1, G: Apply4 ): ( fa: Kind> ) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply1, G: Apply3 ): ( fa: Kind> ) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply1, G: Apply3C ): ( fa: Kind> ) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply1, G: Apply2 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply1, G: Apply2C ): (fa: Kind>) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply1, G: Apply1 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply, G: Apply4 ): ( fa: HKT> ) => (fab: HKT B>>) => HKT> export declare function ap( F: Apply, G: Apply3 ): ( fa: HKT> ) => (fab: HKT B>>) => HKT> export declare function ap( F: Apply, G: Apply3C ): (fa: HKT>) => (fab: HKT B>>) => HKT> export declare function ap( F: Apply, G: Apply2 ): (fa: HKT>) => (fab: HKT B>>) => HKT> export declare function ap( F: Apply, G: Apply2C ): (fa: HKT>) => (fab: HKT B>>) => HKT> export declare function ap( F: Apply, G: Apply1 ): (fa: HKT>) => (fab: HKT B>>) => HKT> export declare function ap( F: Apply, G: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> ``` Added in v2.10.0 ## apFirst **Signature** ```ts export declare function apFirst( A: Apply4 ): (second: Kind4) => (first: Kind4) => Kind4 export declare function apFirst( A: Apply3 ): (second: Kind3) => (first: Kind3) => Kind3 export declare function apFirst( A: Apply3C ): (second: Kind3) => (first: Kind3) => Kind3 export declare function apFirst( A: Apply2 ): (second: Kind2) => (first: Kind2) => Kind2 export declare function apFirst( A: Apply2C ): (second: Kind2) => (first: Kind2) => Kind2 export declare function apFirst( A: Apply1 ): (second: Kind) => (first: Kind) => Kind export declare function apFirst(A: Apply): (second: HKT) => (first: HKT) => HKT ``` Added in v2.10.0 ## apS **Signature** ```ts export declare function apS( F: Apply4 ): ( name: Exclude, fb: Kind4 ) => (fa: Kind4) => Kind4 export declare function apS( F: Apply3 ): ( name: Exclude, fb: Kind3 ) => (fa: Kind3) => Kind3 export declare function apS( F: Apply3C ): ( name: Exclude, fb: Kind3 ) => (fa: Kind3) => Kind3 export declare function apS( F: Apply2 ): ( name: Exclude, fb: Kind2 ) => (fa: Kind2) => Kind2 export declare function apS( F: Apply2C ): ( name: Exclude, fb: Kind2 ) => (fa: Kind2) => Kind2 export declare function apS( F: Apply1 ): ( name: Exclude, fb: Kind ) => (fa: Kind) => Kind export declare function apS( F: Apply ): ( name: Exclude, fb: HKT ) => (fa: HKT) => HKT ``` Added in v2.10.0 ## apSecond **Signature** ```ts export declare function apSecond( A: Apply4 ): (second: Kind4) => (first: Kind4) => Kind4 export declare function apSecond( A: Apply3 ): (second: Kind3) => (first: Kind3) => Kind3 export declare function apSecond( A: Apply3C ): (second: Kind3) => (first: Kind3) => Kind3 export declare function apSecond( A: Apply2 ): (second: Kind2) => (first: Kind2) => Kind2 export declare function apSecond( A: Apply2C ): (second: Kind2) => (first: Kind2) => Kind2 export declare function apSecond( A: Apply1 ): (second: Kind) => (first: Kind) => Kind export declare function apSecond(A: Apply): (second: HKT) => (first: HKT) => HKT ``` Added in v2.10.0 ## getApplySemigroup Lift a semigroup into 'F', the inner values are concatenated using the provided `Semigroup`. **Signature** ```ts export declare function getApplySemigroup( F: Apply4 ): (S: Semigroup) => Semigroup> export declare function getApplySemigroup( F: Apply3 ): (S: Semigroup) => Semigroup> export declare function getApplySemigroup( F: Apply3C ): (S: Semigroup) => Semigroup> export declare function getApplySemigroup( F: Apply2 ): (S: Semigroup) => Semigroup> export declare function getApplySemigroup( F: Apply2C ): (S: Semigroup) => Semigroup> export declare function getApplySemigroup(F: Apply1): (S: Semigroup) => Semigroup> export declare function getApplySemigroup(F: Apply): (S: Semigroup) => Semigroup> ``` Added in v2.10.0 ## sequenceS Like `Apply.sequenceT` but works with structs instead of tuples. **Signature** ```ts export declare function sequenceS( F: Apply4 ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind4] ? A : never }> export declare function sequenceS( F: Apply3 ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind3] ? A : never }> export declare function sequenceS( F: Apply3C ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind3] ? A : never }> export declare function sequenceS( F: Apply2 ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind2] ? A : never }> export declare function sequenceS( F: Apply2C ): >>( r: EnforceNonEmptyRecord ) => Kind2] ? A : never }> export declare function sequenceS( F: Apply1 ): >>( r: EnforceNonEmptyRecord ) => Kind] ? A : never }> export declare function sequenceS( F: Apply ): >>( r: EnforceNonEmptyRecord ) => HKT] ? A : never }> ``` **Example** ```ts import * as E from 'fp-ts/Either' import { sequenceS } from 'fp-ts/Apply' const ado = sequenceS(E.Apply) assert.deepStrictEqual( ado({ a: E.right(1), b: E.right(true), }), E.right({ a: 1, b: true }) ) assert.deepStrictEqual( ado({ a: E.right(1), b: E.left('error'), }), E.left('error') ) ``` Added in v2.0.0 ## sequenceT Tuple sequencing, i.e., take a tuple of monadic actions and does them from left-to-right, returning the resulting tuple. **Signature** ```ts export declare function sequenceT( F: Apply4 ): >>( ...t: T & { readonly 0: Kind4 } ) => Kind4] ? A : never }> export declare function sequenceT( F: Apply3 ): >>( ...t: T & { readonly 0: Kind3 } ) => Kind3] ? A : never }> export declare function sequenceT( F: Apply3C ): >>( ...t: T & { readonly 0: Kind3 } ) => Kind3] ? A : never }> export declare function sequenceT( F: Apply2 ): >>( ...t: T & { readonly 0: Kind2 } ) => Kind2] ? A : never }> export declare function sequenceT( F: Apply2C ): >>( ...t: T & { readonly 0: Kind2 } ) => Kind2] ? A : never }> export declare function sequenceT( F: Apply1 ): >>( ...t: T & { readonly 0: Kind } ) => Kind] ? A : never }> export declare function sequenceT( F: Apply ): >>( ...t: T & { readonly 0: HKT } ) => HKT] ? A : never }> ``` **Example** ```ts import { sequenceT } from 'fp-ts/Apply' import * as O from 'fp-ts/Option' const sequenceTOption = sequenceT(O.Apply) assert.deepStrictEqual(sequenceTOption(O.some(1)), O.some([1])) assert.deepStrictEqual(sequenceTOption(O.some(1), O.some('2')), O.some([1, '2'])) assert.deepStrictEqual(sequenceTOption(O.some(1), O.some('2'), O.none), O.none) ``` Added in v2.0.0 ================================================ FILE: docs/modules/Array.ts.md ================================================ --- title: Array.ts nav_order: 5 parent: Modules --- ## Array overview The Array module provides tools for working with Typescript's Array type in a functional way. In functional jargon, this module provides a monadic interface over Typescript's Array. Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [makeBy](#makeby) - [of](#of) - [replicate](#replicate) - [conversions](#conversions) - [fromEither](#fromeither) - [fromOption](#fromoption) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [guard](#guard) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [partition](#partition) - [partitionMap](#partitionmap) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [separate](#separate) - [wilt](#wilt) - [wither](#wither) - [folding](#folding) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [instances](#instances) - [Alt](#alt) - [Alternative](#alternative) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [ChainRecBreadthFirst](#chainrecbreadthfirst) - [ChainRecDepthFirst](#chainrecdepthfirst) - [Compactable](#compactable) - [Extend](#extend) - [Filterable](#filterable) - [FilterableWithIndex](#filterablewithindex) - [Foldable](#foldable) - [FoldableWithIndex](#foldablewithindex) - [FromEither](#fromeither) - [Functor](#functor) - [FunctorWithIndex](#functorwithindex) - [Monad](#monad) - [Pointed](#pointed) - [Traversable](#traversable) - [TraversableWithIndex](#traversablewithindex) - [Unfoldable](#unfoldable) - [Witherable](#witherable) - [Zero](#zero) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getMonoid](#getmonoid) - [getOrd](#getord) - [getSemigroup](#getsemigroup) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [legacy](#legacy) - [chain](#chain) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [mapWithIndex](#mapwithindex) - [pattern matching](#pattern-matching) - [foldLeft](#foldleft) - [foldRight](#foldright) - [match](#match) - [matchLeft](#matchleft) - [matchLeftW](#matchleftw) - [matchRight](#matchright) - [matchRightW](#matchrightw) - [matchW](#matchw) - [refinements](#refinements) - [isEmpty](#isempty) - [isNonEmpty](#isnonempty) - [sequencing](#sequencing) - [chainFirst](#chainfirst) - [chainRecBreadthFirst](#chainrecbreadthfirst) - [chainRecDepthFirst](#chainrecdepthfirst) - [chainWithIndex](#chainwithindex) - [flatMap](#flatmap) - [flatten](#flatten) - [traverseWithIndex](#traversewithindex) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [unsafe](#unsafe) - [unsafeDeleteAt](#unsafedeleteat) - [unsafeInsertAt](#unsafeinsertat) - [unsafeUpdateAt](#unsafeupdateat) - [utils](#utils) - [Spanned (interface)](#spanned-interface) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [append](#append) - [appendW](#appendw) - [chop](#chop) - [chunksOf](#chunksof) - [comprehension](#comprehension) - [concat](#concat) - [concatW](#concatw) - [copy](#copy) - [deleteAt](#deleteat) - [difference](#difference) - [dropLeft](#dropleft) - [dropLeftWhile](#dropleftwhile) - [dropRight](#dropright) - [duplicate](#duplicate) - [elem](#elem) - [every](#every) - [exists](#exists) - [extend](#extend) - [filterE](#filtere) - [findFirst](#findfirst) - [findFirstMap](#findfirstmap) - [findIndex](#findindex) - [findLast](#findlast) - [findLastIndex](#findlastindex) - [findLastMap](#findlastmap) - [head](#head) - [init](#init) - [insertAt](#insertat) - [intercalate](#intercalate) - [intersection](#intersection) - [intersperse](#intersperse) - [isOutOfBound](#isoutofbound) - [last](#last) - [lefts](#lefts) - [lookup](#lookup) - [modifyAt](#modifyat) - [prepend](#prepend) - [prependAll](#prependall) - [prependW](#prependw) - [reverse](#reverse) - [rights](#rights) - [rotate](#rotate) - [scanLeft](#scanleft) - [scanRight](#scanright) - [size](#size) - [some](#some) - [sort](#sort) - [sortBy](#sortby) - [spanLeft](#spanleft) - [splitAt](#splitat) - [tail](#tail) - [takeLeft](#takeleft) - [takeLeftWhile](#takeleftwhile) - [takeRight](#takeright) - [unfold](#unfold) - [union](#union) - [uniq](#uniq) - [unzip](#unzip) - [updateAt](#updateat) - [zero](#zero) - [zip](#zip) - [zipWith](#zipwith) - [zone of death](#zone-of-death) - [~~array~~](#array) - [~~cons~~](#cons) - [~~empty~~](#empty) - [~~prependToAll~~](#prependtoall) - [~~range~~](#range) - [~~snoc~~](#snoc) --- # constructors ## makeBy Return a `Array` of length `n` with element `i` initialized with `f(i)`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const makeBy:
(n: number, f: (i: number) => A) => A[] ``` **Example** ```ts import { makeBy } from 'fp-ts/Array' const double = (i: number): number => i * 2 assert.deepStrictEqual(makeBy(5, double), [0, 2, 4, 6, 8]) assert.deepStrictEqual(makeBy(-3, double), []) assert.deepStrictEqual(makeBy(4.32164, double), [0, 2, 4, 6]) ``` Added in v2.0.0 ## of Given an element of the base type, `of` builds an `Array` containing just that element of the base type (this is useful for building a `Monad`). **Signature** ```ts export declare const of: (a: A) => A[] ``` **Example** ```ts import { of } from 'fp-ts/Array' assert.deepStrictEqual(of('a'), ['a']) ``` Added in v2.0.0 ## replicate Create a `Array` containing a value repeated the specified number of times. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const replicate: (n: number, a: A) => A[] ``` **Example** ```ts import { replicate } from 'fp-ts/Array' assert.deepStrictEqual(replicate(3, 'a'), ['a', 'a', 'a']) assert.deepStrictEqual(replicate(-3, 'a'), []) assert.deepStrictEqual(replicate(2.985647, 'a'), ['a', 'a']) ``` Added in v2.0.0 # conversions ## fromEither Create an array from an `Either`. The resulting array will contain the content of the `Either` if it is `Right` and it will be empty if the `Either` is `Left`. **Signature** ```ts export declare const fromEither: (fa: Either) => A[] ``` **Example** ```ts import { fromEither } from 'fp-ts/Array' import { either } from 'fp-ts' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(either.right('r'), fromEither), ['r']) assert.deepStrictEqual(pipe(either.left('l'), fromEither), []) ``` Added in v2.11.0 ## fromOption Create an array from an `Option`. The resulting array will contain the content of the `Option` if it is `Some` and it will be empty if the `Option` is `None`. **Signature** ```ts export declare const fromOption: (fa: Option) => A[] ``` **Example** ```ts import { fromOption } from 'fp-ts/Array' import { option } from 'fp-ts' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(option.some('a'), fromOption), ['a']) assert.deepStrictEqual(pipe(option.none, fromOption), []) ``` Added in v2.11.0 # do notation ## Do **Signature** ```ts export declare const Do: {}[] ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: B[] ) => (fa: A[]) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[] ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => B[] ) => (ma: A[]) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[] ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: A[]) => { readonly [K in N]: A }[] ``` Added in v2.8.0 ## guard **Signature** ```ts export declare const guard: (b: boolean) => void[] ``` Added in v2.11.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: A[]) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[] ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. In case of `Array` concatenates the inputs into a single array. **Signature** ```ts export declare const alt: (that: LazyArg) => (fa: A[]) => A[] ``` **Example** ```ts import * as A from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], A.alt(() => [4, 5]) ), [1, 2, 3, 4, 5] ) ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (that: LazyArg) => (fa: A[]) => (B | A)[] ``` **Example** ```ts import * as A from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], A.altW(() => ['a', 'b']) ), [1, 2, 3, 'a', 'b'] ) ``` Added in v2.9.0 # filtering ## compact Compact an array of `Option`s discarding the `None` values and keeping the `Some` values. It returns a new array containing the values of the `Some` options. **Signature** ```ts export declare const compact: (fa: Option[]) => A[] ``` **Example** ```ts import { compact } from 'fp-ts/Array' import { option } from 'fp-ts' assert.deepStrictEqual(compact([option.some('a'), option.none, option.some('b')]), ['a', 'b']) ``` Added in v2.0.0 ## filter Given an iterating function that is a `Predicate` or a `Refinement`, `filter` creates a new `Array` containing the elements of the original `Array` for which the iterating function is `true`. **Signature** ```ts export declare const filter: { (refinement: Refinement): (as: A[]) => B[] (predicate: Predicate): (bs: B[]) => B[] (predicate: Predicate): (as: A[]) => A[] } ``` **Example** ```ts import { filter } from 'fp-ts/Array' import { isString } from 'fp-ts/string' assert.deepStrictEqual(filter(isString)(['a', 1, {}, 'b', 5]), ['a', 'b']) assert.deepStrictEqual(filter((x: number) => x > 0)([-3, 1, -2, 5]), [1, 5]) ``` Added in v2.0.0 ## filterMap Maps an array with an iterating function that returns an `Option` and it keeps only the `Some` values discarding the `None`s. **Signature** ```ts export declare const filterMap: (f: (a: A) => Option) => (fa: A[]) => B[] ``` **Example** ```ts import { filterMap } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' import { option } from 'fp-ts' const f = (s: string) => (s.length === 1 ? option.some(s.toUpperCase()) : option.none) assert.deepStrictEqual(pipe(['a', 'no', 'neither', 'b'], filterMap(f)), ['A', 'B']) ``` Added in v2.0.0 ## filterMapWithIndex Maps an array with an iterating function that takes the index and the value of each element and returns an `Option`. It keeps only the `Some` values discarding the `None`s. Same as [`filterMap`](#filterMap), but with an iterating function which takes also the index as input. **Signature** ```ts export declare const filterMapWithIndex: (f: (i: number, a: A) => Option) => (fa: A[]) => B[] ``` **Example** ```ts import { filterMapWithIndex } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' import { option } from 'fp-ts' const f = (i: number, s: string) => (i % 2 === 1 ? option.some(s.toUpperCase()) : option.none) assert.deepStrictEqual(pipe(['a', 'no', 'neither', 'b'], filterMapWithIndex(f)), ['NO', 'B']) ``` Added in v2.0.0 ## filterWithIndex Same as [`filter`](#filter), but passing also the index to the iterating function. **Signature** ```ts export declare const filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (as: A[]) => B[] (predicateWithIndex: PredicateWithIndex): (bs: B[]) => B[] (predicateWithIndex: PredicateWithIndex): (as: A[]) => A[] } ``` **Example** ```ts import { filterWithIndex } from 'fp-ts/Array' const f = (index: number, x: number) => x > 0 && index <= 2 assert.deepStrictEqual(filterWithIndex(f)([-3, 1, -2, 5]), [1]) ``` Added in v2.0.0 ## partition Given an iterating function that is a `Predicate` or a `Refinement`, `partition` creates two new `Array`s: `right` containing the elements of the original `Array` for which the iterating function is `true`, `left` containing the elements for which it is false. **Signature** ```ts export declare const partition: { (refinement: Refinement): (as: A[]) => Separated (predicate: Predicate): (bs: B[]) => Separated (predicate: Predicate): (as: A[]) => Separated } ``` **Example** ```ts import { partition } from 'fp-ts/Array' import { isString } from 'fp-ts/string' assert.deepStrictEqual(partition(isString)(['a', 1, {}, 'b', 5]), { left: [1, {}, 5], right: ['a', 'b'] }) assert.deepStrictEqual(partition((x: number) => x > 0)([-3, 1, -2, 5]), { left: [-3, -2], right: [1, 5] }) ``` Added in v2.0.0 ## partitionMap Given an iterating function that returns an `Either`, `partitionMap` applies the iterating function to each element and it creates two `Array`s: `right` containing the values of `Right` results, `left` containing the values of `Left` results. **Signature** ```ts export declare const partitionMap: (f: (a: A) => Either) => (fa: A[]) => Separated ``` **Example** ```ts import { partitionMap } from 'fp-ts/Array' import { Either, left, right } from 'fp-ts/Either' const upperIfString = (x: B): Either => (typeof x === 'string' ? right(x.toUpperCase()) : left(x)) assert.deepStrictEqual(partitionMap(upperIfString)([-2, 'hello', 6, 7, 'world']), { left: [-2, 6, 7], right: ['HELLO', 'WORLD'], }) ``` Added in v2.0.0 ## partitionMapWithIndex Same as [`partitionMap`](#partitionMap), but passing also the index to the iterating function. **Signature** ```ts export declare const partitionMapWithIndex: ( f: (i: number, a: A) => Either ) => (fa: A[]) => Separated ``` **Example** ```ts import { partitionMapWithIndex } from 'fp-ts/Array' import { Either, left, right } from 'fp-ts/Either' const upperIfStringBefore3 = (index: number, x: B): Either => index < 3 && typeof x === 'string' ? right(x.toUpperCase()) : left(x) assert.deepStrictEqual(partitionMapWithIndex(upperIfStringBefore3)([-2, 'hello', 6, 7, 'world']), { left: [-2, 6, 7, 'world'], right: ['HELLO'], }) ``` Added in v2.0.0 ## partitionWithIndex Same as [`partition`](#partition), but passing also the index to the iterating function. **Signature** ```ts export declare const partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): (as: A[]) => Separated (predicateWithIndex: PredicateWithIndex): (bs: B[]) => Separated (predicateWithIndex: PredicateWithIndex): (as: A[]) => Separated } ``` **Example** ```ts import { partitionWithIndex } from 'fp-ts/Array' assert.deepStrictEqual(partitionWithIndex((index, x: number) => index < 3 && x > 0)([-2, 5, 6, 7]), { left: [-2, 7], right: [5, 6], }) ``` Added in v2.0.0 ## separate Separate an array of `Either`s into `Left`s and `Right`s, creating two new arrays: one containing all the left values and one containing all the right values. **Signature** ```ts export declare const separate: (fa: Either[]) => Separated ``` **Example** ```ts import { separate } from 'fp-ts/Array' import { either } from 'fp-ts' assert.deepStrictEqual(separate([either.right('r1'), either.left('l1'), either.right('r2')]), { left: ['l1'], right: ['r1', 'r2'], }) ``` Added in v2.0.0 ## wilt **Signature** ```ts export declare const wilt: PipeableWilt1<'Array'> ``` Added in v2.6.5 ## wither **Signature** ```ts export declare const wither: PipeableWither1<'Array'> ``` Added in v2.6.5 # folding ## foldMap Map and fold an `Array`. Map the `Array` passing each value to the iterating function. Then fold the results using the provided `Monoid`. **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: A[]) => M ``` **Example** ```ts import { foldMap } from 'fp-ts/Array' const monoid = { concat: (a: string, b: string) => a + b, empty: '' } const f = (s: string) => s.toUpperCase() assert.deepStrictEqual(foldMap(monoid)(f)(['a', 'b', 'c']), 'ABC') ``` Added in v2.0.0 ## foldMapWithIndex Same as [`foldMap`](#foldMap) but passing also the index to the iterating function. **Signature** ```ts export declare const foldMapWithIndex: (M: Monoid) => (f: (i: number, a: A) => M) => (fa: A[]) => M ``` **Example** ```ts import { foldMapWithIndex } from 'fp-ts/Array' const monoid = { concat: (a: string, b: string) => a + b, empty: '' } const f = (index: number, s: string) => `${s.toUpperCase()}(${index})` assert.deepStrictEqual(foldMapWithIndex(monoid)(f)(['a', 'b', 'c']), 'A(0)B(1)C(2)') ``` Added in v2.0.0 ## reduce Reduces an `Array`. `reduce` executes the supplied iterating function on each element of the array, in order, passing in the element and the return value from the calculation on the preceding element. The first time that the iterating function is called there is no "return value of the previous calculation", the initial value is used in its place. **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: A[]) => B ``` **Example** ```ts import { reduce } from 'fp-ts/Array' assert.deepStrictEqual(reduce(5, (acc: number, cur: number) => acc * cur)([2, 3]), 5 * 2 * 3) ``` Added in v2.0.0 ## reduceRight Same as [`reduce`](#reduce) but applied from the end to the start. _Note_: the iterating function in this case takes the accumulator as the last argument. **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: A[]) => B ``` **Example** ```ts import { reduceRight } from 'fp-ts/Array' assert.deepStrictEqual(reduceRight('', (cur: string, acc: string) => acc + cur)(['a', 'b', 'c']), 'cba') ``` Added in v2.0.0 ## reduceRightWithIndex Same as [`reduceRight`](#reduceRight) but passing also the index to the iterating function. **Signature** ```ts export declare const reduceRightWithIndex: (b: B, f: (i: number, a: A, b: B) => B) => (fa: A[]) => B ``` **Example** ```ts import { reduceRightWithIndex } from 'fp-ts/Array' const f = (index: number, cur: unknown, acc: string) => acc + (typeof cur === 'string' ? cur.toUpperCase() + index : '') assert.deepStrictEqual(reduceRightWithIndex('', f)([2, 'a', 'b', null]), 'B2A1') ``` Added in v2.0.0 ## reduceWithIndex Same as [`reduce`](#reduce) but passing also the index to the iterating function. **Signature** ```ts export declare const reduceWithIndex: (b: B, f: (i: number, b: B, a: A) => B) => (fa: A[]) => B ``` **Example** ```ts import { reduceWithIndex } from 'fp-ts/Array' const f = (index: number, acc: string, cur: unknown) => acc + (typeof cur === 'string' ? cur.toUpperCase() + index : '') assert.deepStrictEqual(reduceWithIndex('', f)([2, 'a', 'b', null]), 'A1B2') ``` Added in v2.0.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'Array'> ``` Added in v2.7.0 ## Alternative **Signature** ```ts export declare const Alternative: Alternative1<'Array'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'Array'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'Array'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: Chain1<'Array'> ``` Added in v2.10.0 ## ChainRecBreadthFirst **Signature** ```ts export declare const ChainRecBreadthFirst: ChainRec1<'Array'> ``` Added in v2.11.0 ## ChainRecDepthFirst **Signature** ```ts export declare const ChainRecDepthFirst: ChainRec1<'Array'> ``` Added in v2.11.0 ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'Array'> ``` Added in v2.7.0 ## Extend **Signature** ```ts export declare const Extend: Extend1<'Array'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'Array'> ``` Added in v2.7.0 ## FilterableWithIndex **Signature** ```ts export declare const FilterableWithIndex: FilterableWithIndex1<'Array', number> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'Array'> ``` Added in v2.7.0 ## FoldableWithIndex **Signature** ```ts export declare const FoldableWithIndex: FoldableWithIndex1<'Array', number> ``` Added in v2.7.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither1<'Array'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'Array'> ``` Added in v2.7.0 ## FunctorWithIndex **Signature** ```ts export declare const FunctorWithIndex: FunctorWithIndex1<'Array', number> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'Array'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'Array'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'Array'> ``` Added in v2.7.0 ## TraversableWithIndex **Signature** ```ts export declare const TraversableWithIndex: TraversableWithIndex1<'Array', number> ``` Added in v2.7.0 ## Unfoldable **Signature** ```ts export declare const Unfoldable: Unfoldable1<'Array'> ``` Added in v2.7.0 ## Witherable **Signature** ```ts export declare const Witherable: Witherable1<'Array'> ``` Added in v2.7.0 ## Zero **Signature** ```ts export declare const Zero: Zero1<'Array'> ``` Added in v2.11.0 ## getDifferenceMagma Get a `Magma` for `Array` where the `concat` function is the differnce between the first and the second array, i.e. the result contains all the elements of the first array for which their is no equal element in the second array according to the `Eq` provided. **Signature** ```ts export declare const getDifferenceMagma: (E: Eq) => Magma ``` **Example** ```ts import { getDifferenceMagma } from 'fp-ts/Array' import { Eq } from 'fp-ts/number' const S = getDifferenceMagma(Eq) assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [1]) ``` Added in v2.11.0 ## getEq Derives an `Eq` over the `Array` of a given element type from the `Eq` of that type. The derived `Eq` defines two arrays as equal if all elements of both arrays are compared equal pairwise with the given `E`. In case of arrays of different lengths, the result is non equality. **Signature** ```ts export declare const getEq: (E: Eq) => Eq ``` **Example** ```ts import * as S from 'fp-ts/string' import { getEq } from 'fp-ts/Array' const E = getEq(S.Eq) assert.strictEqual(E.equals(['a', 'b'], ['a', 'b']), true) assert.strictEqual(E.equals(['a'], []), false) ``` Added in v2.0.0 ## getIntersectionSemigroup Get a `Semigroup` based on the intersection of the elements of `Array`s. Only elements present in the two arrays which are equal according to the provided `Eq` are included in the result. **Signature** ```ts export declare const getIntersectionSemigroup: (E: Eq) => Semigroup ``` **Example** ```ts import { getIntersectionSemigroup } from 'fp-ts/Array' import { Eq } from 'fp-ts/number' const S = getIntersectionSemigroup(Eq) assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [2]) ``` Added in v2.11.0 ## getMonoid Returns a `Monoid` for `Array` based on the concatenation of `Array`s. **Signature** ```ts export declare const getMonoid: () => Monoid ``` **Example** ```ts import { getMonoid } from 'fp-ts/Array' const M = getMonoid() assert.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4]) ``` Added in v2.0.0 ## getOrd Derives an `Ord` over the `Array` of a given element type from the `Ord` of that type. The ordering between two such arrays is equal to: the first non equal comparison of each arrays elements taken pairwise in increasing order, in case of equality over all the pairwise elements; the longest array is considered the greatest, if both arrays have the same length, the result is equality. **Signature** ```ts export declare const getOrd: (O: Ord) => Ord ``` **Example** ```ts import { getOrd } from 'fp-ts/Array' import * as S from 'fp-ts/string' const O = getOrd(S.Ord) assert.strictEqual(O.compare(['b'], ['a']), 1) assert.strictEqual(O.compare(['a'], ['a']), 0) assert.strictEqual(O.compare(['a'], ['b']), -1) ``` Added in v2.0.0 ## getSemigroup Get a `Semigroup` based on the concatenation of `Array`s. See also [`getMonoid`](#getMonoid). **Signature** ```ts export declare const getSemigroup: () => Semigroup ``` **Example** ```ts import { getSemigroup } from 'fp-ts/Array' const S = getSemigroup() assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [1, 2, 2, 3]) ``` Added in v2.10.0 ## getShow `getShow` makes a `Show` for an `Array` from a `Show` for an `A`. **Signature** ```ts export declare const getShow: (S: Show) => Show ``` **Example** ```ts import { getShow } from 'fp-ts/Array' const numShow = { show: (n: number) => (n >= 0 ? `${n}` : `(${-n})`) } assert.deepStrictEqual(getShow(numShow).show([-2, -1, 0, 1]), '[(2), (1), 0, 1]') ``` Added in v2.0.0 ## getUnionMonoid Get a `Monoid` based on the union of the elements of `Array`s. Elements which equal according to the provided `Eq` are included only once in the result. **Signature** ```ts export declare const getUnionMonoid: (E: Eq) => Monoid ``` **Example** ```ts import { getUnionMonoid } from 'fp-ts/Array' import { Eq } from 'fp-ts/number' const M = getUnionMonoid(Eq) assert.deepStrictEqual(M.concat([1, 2], [2, 3]), [1, 2, 3]) assert.deepStrictEqual(M.empty, []) ``` Added in v2.11.0 ## getUnionSemigroup Get a `Semigroup` based on the union of the elements of `Array`s. Elements which equal according to the provided `Eq` are included only once in the result. See also [`getUnionMonoid`](#getUnionMonoid). **Signature** ```ts export declare const getUnionSemigroup: (E: Eq) => Semigroup ``` **Example** ```ts import { getUnionSemigroup } from 'fp-ts/Array' import { Eq } from 'fp-ts/number' const S = getUnionSemigroup(Eq) assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [1, 2, 3]) ``` Added in v2.11.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => B[]) => (ma: A[]) => B[] ``` Added in v2.0.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: (f: (...a: A) => Either) => (...a: A) => B[] ``` Added in v2.11.0 ## fromOptionK **Signature** ```ts export declare const fromOptionK: (f: (...a: A) => Option) => (...a: A) => B[] ``` Added in v2.11.0 ## fromPredicate Create an array with one element, if the element satisfies the predicate, otherwise it returns an empty array. **Signature** ```ts export declare function fromPredicate(refinement: Refinement): (a: A) => Array export declare function fromPredicate(predicate: Predicate): (b: B) => Array export declare function fromPredicate(predicate: Predicate): (a: A) => Array ``` **Example** ```ts import { fromPredicate } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' import { isString } from 'fp-ts/string' assert.deepStrictEqual(pipe('a', fromPredicate(isString)), ['a']) assert.deepStrictEqual(pipe(7, fromPredicate(isString)), []) assert.deepStrictEqual( pipe( 7, fromPredicate((x) => x > 0) ), [7] ) assert.deepStrictEqual( pipe( -3, fromPredicate((x) => x > 0) ), [] ) ``` Added in v2.11.0 # mapping ## flap Given an input an `Array` of functions, `flap` returns an `Array` containing the results of applying each function to the given input. **Signature** ```ts export declare const flap: (a: A) => (fab: ((a: A) => B)[]) => B[] ``` **Example** ```ts import { flap } from 'fp-ts/Array' const funs = [(n: number) => `Double: ${n * 2}`, (n: number) => `Triple: ${n * 3}`, (n: number) => `Square: ${n * n}`] assert.deepStrictEqual(flap(4)(funs), ['Double: 8', 'Triple: 12', 'Square: 16']) ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: Array) => Array`. In practice it applies the base function to each element of the array and collects the results in a new array. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: A[]) => B[] ``` **Example** ```ts import { map } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' const f = (n: number) => n * 2 assert.deepStrictEqual(pipe([1, 2, 3], map(f)), [2, 4, 6]) ``` Added in v2.0.0 ## mapWithIndex Same as [`map`](#map), but the iterating function takes both the index and the value of the element. **Signature** ```ts export declare const mapWithIndex: (f: (i: number, a: A) => B) => (fa: A[]) => B[] ``` **Example** ```ts import { mapWithIndex } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' const f = (i: number, s: string) => `${s} - ${i}` assert.deepStrictEqual(pipe(['a', 'b', 'c'], mapWithIndex(f)), ['a - 0', 'b - 1', 'c - 2']) ``` Added in v2.0.0 # pattern matching ## foldLeft Alias of [`matchLeft`](#matchleft). **Signature** ```ts export declare const foldLeft: (onEmpty: LazyArg, onNonEmpty: (head: A, tail: A[]) => B) => (as: A[]) => B ``` Added in v2.0.0 ## foldRight Alias of [`matchRight`](#matchright). **Signature** ```ts export declare const foldRight: (onEmpty: LazyArg, onNonEmpty: (init: A[], last: A) => B) => (as: A[]) => B ``` Added in v2.0.0 ## match Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise it passes the array to `onNonEmpty` and returns the result. **Signature** ```ts export declare const match: (onEmpty: LazyArg, onNonEmpty: (as: NEA.NonEmptyArray) => B) => (as: A[]) => B ``` **Example** ```ts import { match } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' const matcher = match( () => 'No elements', (as) => `Found ${as.length} element(s)` ) assert.deepStrictEqual(pipe([1, 2, 3, 4], matcher), 'Found 4 element(s)') assert.deepStrictEqual(pipe([], matcher), 'No elements') ``` Added in v2.11.0 ## matchLeft Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise it passes the array to `onNonEmpty` broken into its first element and remaining elements. **Signature** ```ts export declare const matchLeft: (onEmpty: LazyArg, onNonEmpty: (head: A, tail: A[]) => B) => (as: A[]) => B ``` **Example** ```ts import { matchLeft } from 'fp-ts/Array' const len: (as: Array) => number = matchLeft( () => 0, (_, tail) => 1 + len(tail) ) assert.strictEqual(len([1, 2, 3]), 3) ``` Added in v2.10.0 ## matchLeftW Less strict version of [`matchLeft`](#matchleft). It will work when `onEmpty` and `onNonEmpty` have different return types. **Signature** ```ts export declare const matchLeftW: ( onEmpty: LazyArg, onNonEmpty: (head: A, tail: A[]) => C ) => (as: A[]) => B | C ``` **Example** ```ts import { matchLeftW } from 'fp-ts/Array' const f = matchLeftW( () => 0, (head: string, tail: string[]) => `Found "${head}" followed by ${tail.length} elements` ) assert.strictEqual(f(['a', 'b', 'c']), 'Found "a" followed by 2 elements') assert.strictEqual(f([]), 0) ``` Added in v2.11.0 ## matchRight Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise it passes the array to `onNonEmpty` broken into its initial elements and the last element. **Signature** ```ts export declare const matchRight: (onEmpty: LazyArg, onNonEmpty: (init: A[], last: A) => B) => (as: A[]) => B ``` **Example** ```ts import { matchRight } from 'fp-ts/Array' const len: (as: Array) => number = matchRight( () => 0, (head, _) => 1 + len(head) ) assert.strictEqual(len([1, 2, 3]), 3) ``` Added in v2.10.0 ## matchRightW Less strict version of [`matchRight`](#matchright). It will work when `onEmpty` and `onNonEmpty` have different return types. **Signature** ```ts export declare const matchRightW: ( onEmpty: LazyArg, onNonEmpty: (init: A[], last: A) => C ) => (as: A[]) => B | C ``` **Example** ```ts import { matchRightW } from 'fp-ts/Array' const f = matchRightW( () => 0, (head: string[], tail: string) => `Found ${head.length} elements folllowed by "${tail}"` ) assert.strictEqual(f(['a', 'b', 'c']), 'Found 2 elements folllowed by "c"') assert.strictEqual(f([]), 0) ``` Added in v2.11.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onEmpty: LazyArg, onNonEmpty: (as: NEA.NonEmptyArray) => C ) => (as: A[]) => B | C ``` **Example** ```ts import { matchW } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' const matcherW = matchW( () => 'No elements', (as) => as.length ) assert.deepStrictEqual(pipe([1, 2, 3, 4], matcherW), 4) assert.deepStrictEqual(pipe([], matcherW), 'No elements') ``` Added in v2.11.0 # refinements ## isEmpty Test whether an array is empty **Signature** ```ts export declare const isEmpty: (as: A[]) => as is [] ``` **Example** ```ts import { isEmpty } from 'fp-ts/Array' assert.strictEqual(isEmpty([]), true) assert.strictEqual(isEmpty(['a']), false) ``` Added in v2.0.0 ## isNonEmpty Test whether an array is non empty narrowing down the type to `NonEmptyArray` **Signature** ```ts export declare const isNonEmpty: (as: A[]) => as is NEA.NonEmptyArray ``` **Example** ```ts import { isNonEmpty } from 'fp-ts/Array' assert.strictEqual(isNonEmpty([]), false) assert.strictEqual(isNonEmpty(['a']), true) ``` Added in v2.0.0 # sequencing ## chainFirst Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const chainFirst: (f: (a: A) => B[]) => (first: A[]) => A[] ``` **Example** ```ts import * as A from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], A.chainFirst(() => ['a', 'b']) ), [1, 1, 2, 2, 3, 3] ) assert.deepStrictEqual( pipe( [1, 2, 3], A.chainFirst(() => []) ), [] ) ``` Added in v2.0.0 ## chainRecBreadthFirst **Signature** ```ts export declare const chainRecBreadthFirst: (f: (a: A) => Either[]) => (a: A) => B[] ``` Added in v2.11.0 ## chainRecDepthFirst **Signature** ```ts export declare const chainRecDepthFirst: (f: (a: A) => Either[]) => (a: A) => B[] ``` Added in v2.11.0 ## chainWithIndex Same as [`chain`](#chain), but passing also the index to the iterating function. **Signature** ```ts export declare const chainWithIndex: (f: (i: number, a: A) => B[]) => (as: A[]) => B[] ``` **Example** ```ts import { chainWithIndex, replicate } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' const f = (index: number, x: string) => replicate(2, `${x}${index}`) assert.deepStrictEqual(pipe(['a', 'b', 'c'], chainWithIndex(f)), ['a0', 'a0', 'b1', 'b1', 'c2', 'c2']) ``` Added in v2.7.0 ## flatMap Composes computations in sequence, using the return value of one computation to determine the next computation. In other words it takes a function `f` that produces an array from a single element of the base type `A` and returns a new function which applies `f` to each element of the input array (like [`map`](#map)) and, instead of returning an array of arrays, concatenates the results into a single array (like [`flatten`](#flatten)). **Signature** ```ts export declare const flatMap: { (f: (a: A, i: number) => B[]): (ma: A[]) => B[] (ma: A[], f: (a: A, i: number) => B[]): B[] } ``` **Example** ```ts import { flatMap, map, replicate } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' const f = (n: number) => replicate(n, `${n}`) assert.deepStrictEqual(pipe([1, 2, 3], map(f)), [['1'], ['2', '2'], ['3', '3', '3']]) assert.deepStrictEqual(pipe([1, 2, 3], flatMap(f)), ['1', '2', '2', '3', '3', '3']) ``` Added in v2.14.0 ## flatten Takes an array of arrays of `A` and flattens them into an array of `A` by concatenating the elements of each array in order. **Signature** ```ts export declare const flatten: (mma: A[][]) => A[] ``` **Example** ```ts import { flatten } from 'fp-ts/Array' assert.deepStrictEqual(flatten([['a'], ['b', 'c'], ['d', 'e', 'f']]), ['a', 'b', 'c', 'd', 'e', 'f']) ``` Added in v2.5.0 ## traverseWithIndex Same as [`traverse`](#traverse) but passing also the index to the iterating function. **Signature** ```ts export declare const traverseWithIndex: PipeableTraverseWithIndex1<'Array', number> ``` **Example** ```ts import { traverseWithIndex } from 'fp-ts/Array' import { Applicative, left, right } from 'fp-ts/Either' const f = (index: number, x: unknown) => typeof x === 'string' ? right(x.toUpperCase() + index) : left(new Error('not a string')) assert.deepStrictEqual(traverseWithIndex(Applicative)(f)(['a', 'b']), right(['A0', 'B1'])) assert.deepStrictEqual(traverseWithIndex(Applicative)(f)(['a', 5]), left(new Error('not a string'))) ``` Added in v2.6.3 # traversing ## sequence `sequence` takes an `Array` where elements are `HKT` (higher kinded type) and, using an applicative of that `HKT`, returns an `HKT` of `Array`. E.g. it can turn an `Array>` into an `Either>`. `sequence` requires an `Applicative` of the `HKT` you are targeting, e.g. to turn an `Array>` into an `Either>`, it needs an `Applicative` for `Either`, to to turn an `Array>` into an `Option>`, it needs an `Applicative` for `Option`. **Signature** ```ts export declare const sequence: Sequence1<'Array'> ``` **Example** ```ts import { sequence } from 'fp-ts/Array' import { Applicative, left, right } from 'fp-ts/Either' assert.deepStrictEqual(sequence(Applicative)([right('a'), right('b')]), right(['a', 'b'])) assert.deepStrictEqual( sequence(Applicative)([right('a'), left(new Error('not a string'))]), left(new Error('not a string')) ) ``` Added in v2.6.3 ## traverse Given an iterating function that returns a `HKT` (higher kinded type), `traverse` applies the iterating function to each element of the `Array` and then [`sequence`](#sequence)-s the results using the provided `Applicative`. E.g. suppose you have an `Array` and you want to format each element with a function that returns a result or an error as `f = (a: A) => Either`, using `traverse` you can apply `f` to all elements and directly obtain as a result an `Either>` i.e. an `Array` if all the results are `B`, or an `Error` if some of the results are `Error`s. **Signature** ```ts export declare const traverse: PipeableTraverse1<'Array'> ``` **Example** ```ts import { traverse } from 'fp-ts/Array' import { Applicative, left, right } from 'fp-ts/Either' const f = (x: unknown) => (typeof x === 'string' ? right(x.toUpperCase()) : left(new Error('not a string'))) assert.deepStrictEqual(traverse(Applicative)(f)(['a', 'b']), right(['A', 'B'])) assert.deepStrictEqual(traverse(Applicative)(f)(['a', 5]), left(new Error('not a string'))) ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Array' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # unsafe ## unsafeDeleteAt **Signature** ```ts export declare const unsafeDeleteAt: (i: number, as: A[]) => A[] ``` Added in v2.0.0 ## unsafeInsertAt **Signature** ```ts export declare const unsafeInsertAt: (i: number, a: A, as: A[]) => NEA.NonEmptyArray ``` Added in v2.0.0 ## unsafeUpdateAt **Signature** ```ts export declare const unsafeUpdateAt: (i: number, a: A, as: A[]) => A[] ``` Added in v2.0.0 # utils ## Spanned (interface) Type returned by [`spanLeft`](#spanLeft) composed of an `init` array and a `rest` array. **Signature** ```ts export interface Spanned { init: Array rest: Array } ``` Added in v2.10.0 ## ap **Signature** ```ts export declare const ap: (fa: A[]) => (fab: ((a: A) => B)[]) => B[] ``` **Example** ```ts import { ap, map, of } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' // a curried function with 3 input parameteres const f = (s1: string) => (n: number) => (s2: string) => s1 + n + s2 // let's use `ap` to iterate `f` over an array for each input parameter assert.deepStrictEqual(pipe(['a', 'b'], map(f), ap([1, 2]), ap(['😀', '😫', '😎'])), [ 'a1😀', 'a1😫', 'a1😎', 'a2😀', 'a2😫', 'a2😎', 'b1😀', 'b1😫', 'b1😎', 'b2😀', 'b2😫', 'b2😎', ]) // given Array implements the Applicative interface with the `of` method, // we can write exactly the same thing in a more symmetric way // using `of` on `f` and `ap` on each array in input assert.deepStrictEqual( pipe(of(f), ap(['a', 'b']), ap([1, 2]), ap(['😀', '😫', '😎'])), pipe(['a', 'b'], map(f), ap([1, 2]), ap(['😀', '😫', '😎'])) ) ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: B[]) => (first: A[]) => A[] ``` Added in v2.5.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: B[]) => (first: A[]) => B[] ``` Added in v2.5.0 ## append Append an element to the end of a `Array`, creating a new `NonEmptyArray`. **Signature** ```ts export declare const append: (end: A) => (init: A[]) => NEA.NonEmptyArray ``` **Example** ```ts import { append } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], append(4)), [1, 2, 3, 4]) ``` Added in v2.10.0 ## appendW Less strict version of [`append`](#append). **Signature** ```ts export declare const appendW: (end: B) => (init: A[]) => NEA.NonEmptyArray ``` **Example** ```ts import { appendW } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], appendW('d')), [1, 2, 3, 'd']) ``` Added in v2.11.0 ## chop A useful recursion pattern for processing an array to produce a new array, often used for "chopping" up the input array. Typically chop is called with some function that will consume an initial prefix of the array and produce a value and the rest of the array. **Signature** ```ts export declare const chop: (f: (as: NEA.NonEmptyArray) => [B, A[]]) => (as: A[]) => B[] ``` **Example** ```ts import { Eq } from 'fp-ts/Eq' import * as A from 'fp-ts/Array' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' const group = (S: Eq): ((as: Array) => Array>) => { return A.chop((as) => { const { init, rest } = pipe( as, A.spanLeft((a: A) => S.equals(a, as[0])) ) return [init, rest] }) } assert.deepStrictEqual(group(N.Eq)([1, 1, 2, 3, 3, 4]), [[1, 1], [2], [3, 3], [4]]) ``` Added in v2.0.0 ## chunksOf Splits an array into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of the array. Note that `chunksOf(n)([])` is `[]`, not `[[]]`. This is intentional, and is consistent with a recursive definition of `chunksOf`; it satisfies the property that ```ts chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys))) ``` whenever `n` evenly divides the length of `xs`. **Signature** ```ts export declare const chunksOf: (n: number) => (as: A[]) => NEA.NonEmptyArray[] ``` **Example** ```ts import { chunksOf } from 'fp-ts/Array' assert.deepStrictEqual(chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) ``` Added in v2.0.0 ## comprehension `Array` comprehension. ``` [ f(x, y, ...) | x ← xs, y ← ys, ..., g(x, y, ...) ] ``` **Signature** ```ts export declare function comprehension( input: [Array, Array, Array, Array], f: (a: A, b: B, c: C, d: D) => R, g?: (a: A, b: B, c: C, d: D) => boolean ): Array export declare function comprehension( input: [Array, Array, Array], f: (a: A, b: B, c: C) => R, g?: (a: A, b: B, c: C) => boolean ): Array export declare function comprehension( input: [Array, Array], f: (a: A, b: B) => R, g?: (a: A, b: B) => boolean ): Array export declare function comprehension(input: [Array], f: (a: A) => R, g?: (a: A) => boolean): Array ``` **Example** ```ts import { comprehension } from 'fp-ts/Array' import { tuple } from 'fp-ts/function' assert.deepStrictEqual( comprehension( [ [1, 2, 3], ['a', 'b'], ], tuple, (a, b) => (a + b.length) % 2 === 0 ), [ [1, 'a'], [1, 'b'], [3, 'a'], [3, 'b'], ] ) ``` Added in v2.0.0 ## concat **Signature** ```ts export declare const concat: (second: A[]) => (first: A[]) => A[] ``` Added in v2.11.0 ## concatW **Signature** ```ts export declare const concatW: (second: B[]) => (first: A[]) => (B | A)[] ``` Added in v2.11.0 ## copy This function takes an array and makes a new array containing the same elements. **Signature** ```ts export declare const copy: (as: A[]) => A[] ``` Added in v2.0.0 ## deleteAt Delete the element at the specified index, creating a new array, or returning `None` if the index is out of bounds. **Signature** ```ts export declare const deleteAt: (i: number) => (as: A[]) => Option ``` **Example** ```ts import { deleteAt } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(deleteAt(0)([1, 2, 3]), some([2, 3])) assert.deepStrictEqual(deleteAt(1)([]), none) ``` Added in v2.0.0 ## difference Creates an array of array values not included in the other given array using a `Eq` for equality comparisons. The order and references of result values are determined by the first array. **Signature** ```ts export declare function difference(E: Eq): { (xs: Array): (ys: Array) => Array (xs: Array, ys: Array): Array } ``` **Example** ```ts import { difference } from 'fp-ts/Array' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2], difference(N.Eq)([2, 3])), [1]) ``` Added in v2.0.0 ## dropLeft Creates a new `Array` which is a copy of the input dropping a max number of elements from the start. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const dropLeft: (n: number) => (as: A[]) => A[] ``` **Example** ```ts import { dropLeft } from 'fp-ts/Array' assert.deepStrictEqual(dropLeft(2)([1, 2, 3]), [3]) assert.deepStrictEqual(dropLeft(5)([1, 2, 3]), []) assert.deepStrictEqual(dropLeft(0)([1, 2, 3]), [1, 2, 3]) assert.deepStrictEqual(dropLeft(-2)([1, 2, 3]), [1, 2, 3]) ``` Added in v2.0.0 ## dropLeftWhile Creates a new `Array` which is a copy of the input dropping the longest initial subarray for which all element satisfy the specified predicate. **Signature** ```ts export declare function dropLeftWhile(refinement: Refinement): (as: Array) => Array export declare function dropLeftWhile(predicate: Predicate): (bs: Array) => Array export declare function dropLeftWhile(predicate: Predicate): (as: Array) => Array ``` **Example** ```ts import { dropLeftWhile } from 'fp-ts/Array' assert.deepStrictEqual(dropLeftWhile((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), [2, 4, 5]) ``` Added in v2.0.0 ## dropRight Creates a new `Array` which is a copy of the input dropping a max number of elements from the end. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const dropRight: (n: number) => (as: A[]) => A[] ``` **Example** ```ts import { dropRight } from 'fp-ts/Array' assert.deepStrictEqual(dropRight(2)([1, 2, 3]), [1]) assert.deepStrictEqual(dropRight(5)([1, 2, 3]), []) assert.deepStrictEqual(dropRight(0)([1, 2, 3]), [1, 2, 3]) assert.deepStrictEqual(dropRight(-2)([1, 2, 3]), [1, 2, 3]) ``` Added in v2.0.0 ## duplicate `duplicate` returns an array containing the whole input `Array`, then to the input `Array` dropping the first element, then to the input `Array` dropping the first two elements, etc. **Signature** ```ts export declare const duplicate: (wa: A[]) => A[][] ``` **Example** ```ts import { duplicate } from 'fp-ts/Array' assert.deepStrictEqual(duplicate(['a', 'b', 'c']), [['a', 'b', 'c'], ['b', 'c'], ['c']]) ``` Added in v2.0.0 ## elem Test if a value is a member of an `Array`. Takes a `Eq` as a single argument which returns the function to use to search for a value of type `A` in an `Array`. **Signature** ```ts export declare const elem: (E: Eq) => { (a: A): (as: A[]) => boolean; (a: A, as: A[]): boolean } ``` **Example** ```ts import { elem } from 'fp-ts/Array' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(2)), true) assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(0)), false) ``` Added in v2.0.0 ## every `every` tells if the provided predicate holds true for every element in the `Array`. **Signature** ```ts export declare const every: { (refinement: Refinement): Refinement (predicate: Predicate): Predicate } ``` **Example** ```ts import { every } from 'fp-ts/Array' assert.equal(every((x: number) => x >= 0)([1, 2, 3]), true) assert.equal(every((x: number) => x >= 0)([-1, 2, 3]), false) ``` Added in v2.9.0 ## exists Alias of [`some`](#some) **Signature** ```ts export declare const exists: (predicate: Predicate) => (as: A[]) => as is NEA.NonEmptyArray ``` Added in v2.11.0 ## extend Given an iterating function that takes `Array` as input, `extend` returns an array containing the results of the iterating function applied to the whole input `Array`, then to the input `Array` without the first element, then to the input `Array` without the first two elements, etc. **Signature** ```ts export declare const extend: (f: (as: A[]) => B) => (as: A[]) => B[] ``` **Example** ```ts import { extend } from 'fp-ts/Array' const f = (a: string[]) => a.join(',') assert.deepStrictEqual(extend(f)(['a', 'b', 'c']), ['a,b,c', 'b,c', 'c']) ``` Added in v2.0.0 ## filterE Filter values inside a context. **Signature** ```ts export declare const filterE: FilterE1<'Array'> ``` Added in v2.11.0 ## findFirst Find the first element which satisfies a predicate (or a refinement) function. It returns an `Option` containing the element or `None` if not found. **Signature** ```ts export declare function findFirst(refinement: Refinement): (as: Array) => Option export declare function findFirst(predicate: Predicate): (bs: Array) => Option export declare function findFirst(predicate: Predicate): (as: Array) => Option ``` **Example** ```ts import { findFirst } from 'fp-ts/Array' import { some } from 'fp-ts/Option' type X = { readonly a: number readonly b: number } assert.deepStrictEqual( findFirst((x: X) => x.a === 1)([ { a: 1, b: 1 }, { a: 1, b: 2 }, ]), some({ a: 1, b: 1 }) ) ``` Added in v2.0.0 ## findFirstMap Given a selector function which takes an element and returns an option, this function applies the selector to each element of the array and returns the first `Some` result. Otherwise it returns `None`. **Signature** ```ts export declare const findFirstMap: (f: (a: A) => Option) => (as: A[]) => Option ``` **Example** ```ts import { findFirstMap } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' interface Person { readonly name: string readonly age: number } const persons: Array = [ { name: 'John', age: 16 }, { name: 'Mary', age: 45 }, { name: 'Joey', age: 28 }, ] const nameOfPersonAbove18 = (p: Person) => (p.age <= 18 ? none : some(p.name)) const nameOfPersonAbove70 = (p: Person) => (p.age <= 70 ? none : some(p.name)) assert.deepStrictEqual(findFirstMap(nameOfPersonAbove18)(persons), some('Mary')) assert.deepStrictEqual(findFirstMap(nameOfPersonAbove70)(persons), none) ``` Added in v2.0.0 ## findIndex `findIndex` returns an `Option` containing the first index for which a predicate holds. It returns `None` if no element satisfies the predicate. Similar to [`findFirst`](#findFirst) but returning the index instead of the element. **Signature** ```ts export declare const findIndex: (predicate: Predicate) => (as: A[]) => Option ``` **Example** ```ts import { findIndex } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(findIndex((n: number) => n === 2)([1, 2, 3]), some(1)) assert.deepStrictEqual(findIndex((n: number) => n === 2)([]), none) ``` Added in v2.0.0 ## findLast Find the last element which satisfies a predicate function. It returns an `Option` containing the element or `None` if not found. **Signature** ```ts export declare function findLast(refinement: Refinement): (as: Array) => Option export declare function findLast(predicate: Predicate): (bs: Array) => Option export declare function findLast(predicate: Predicate): (as: Array) => Option ``` **Example** ```ts import { findLast } from 'fp-ts/Array' import { some } from 'fp-ts/Option' type X = { readonly a: number readonly b: number } assert.deepStrictEqual( findLast((x: X) => x.a === 1)([ { a: 1, b: 1 }, { a: 1, b: 2 }, ]), some({ a: 1, b: 2 }) ) ``` Added in v2.0.0 ## findLastIndex Returns the index of the last element of the list which matches the predicate. It returns an `Option` containing the index or `None` if not found. **Signature** ```ts export declare const findLastIndex: (predicate: Predicate) => (as: A[]) => Option ``` **Example** ```ts import { findLastIndex } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' interface X { readonly a: number readonly b: number } const xs: Array = [ { a: 1, b: 0 }, { a: 1, b: 1 }, ] assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 1)(xs), some(1)) assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 4)(xs), none) ``` Added in v2.0.0 ## findLastMap Given a selector function which takes an element and returns an option, this function applies the selector to each element of the array starting from the end and returns the last `Some` result. Otherwise it returns `None`. **Signature** ```ts export declare const findLastMap: (f: (a: A) => Option) => (as: A[]) => Option ``` **Example** ```ts import { findLastMap } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' interface Person { readonly name: string readonly age: number } const persons: Array = [ { name: 'John', age: 16 }, { name: 'Mary', age: 45 }, { name: 'Joey', age: 28 }, ] const nameOfPersonAbove18 = (p: Person) => (p.age <= 18 ? none : some(p.name)) const nameOfPersonAbove70 = (p: Person) => (p.age <= 70 ? none : some(p.name)) assert.deepStrictEqual(findLastMap(nameOfPersonAbove18)(persons), some('Joey')) assert.deepStrictEqual(findLastMap(nameOfPersonAbove70)(persons), none) ``` Added in v2.0.0 ## head Get the first element in an array, or `None` if the array is empty **Signature** ```ts export declare const head: (as: A[]) => Option ``` **Example** ```ts import { head } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(head([1, 2, 3]), some(1)) assert.deepStrictEqual(head([]), none) ``` Added in v2.0.0 ## init Get all but the last element of an array, creating a new array, or `None` if the array is empty **Signature** ```ts export declare const init: (as: A[]) => Option ``` **Example** ```ts import { init } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(init([1, 2, 3]), some([1, 2])) assert.deepStrictEqual(init([]), none) ``` Added in v2.0.0 ## insertAt Insert an element at the specified index, creating a new array, or returning `None` if the index is out of bounds. **Signature** ```ts export declare const insertAt: (i: number, a: A) => (as: A[]) => Option> ``` **Example** ```ts import { insertAt } from 'fp-ts/Array' import { some } from 'fp-ts/Option' assert.deepStrictEqual(insertAt(2, 5)([1, 2, 3, 4]), some([1, 2, 5, 3, 4])) ``` Added in v2.0.0 ## intercalate Places an element in between members of an `Array`, then folds the results using the provided `Monoid`. **Signature** ```ts export declare const intercalate: (M: Monoid) => (middle: A) => (as: A[]) => A ``` **Example** ```ts import * as S from 'fp-ts/string' import { intercalate } from 'fp-ts/Array' assert.deepStrictEqual(intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c') ``` Added in v2.12.0 ## intersection Creates an array of unique values that are included in all given arrays using a `Eq` for equality comparisons. The order and references of result values are determined by the first array. **Signature** ```ts export declare function intersection(E: Eq): { (xs: Array): (ys: Array) => Array (xs: Array, ys: Array): Array } ``` **Example** ```ts import { intersection } from 'fp-ts/Array' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2], intersection(N.Eq)([2, 3])), [2]) ``` Added in v2.0.0 ## intersperse Creates a new `Array` placing an element in between members of the input `Array`. **Signature** ```ts export declare const intersperse: (middle: A) => (as: A[]) => A[] ``` **Example** ```ts import { intersperse } from 'fp-ts/Array' assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.9.0 ## isOutOfBound Test whether an array contains a particular index **Signature** ```ts export declare const isOutOfBound: (i: number, as: A[]) => boolean ``` **Example** ```ts import { isOutOfBound } from 'fp-ts/Array' assert.strictEqual(isOutOfBound(1, ['a', 'b', 'c']), false) assert.strictEqual(isOutOfBound(-1, ['a', 'b', 'c']), true) assert.strictEqual(isOutOfBound(3, ['a', 'b', 'c']), true) ``` Added in v2.0.0 ## last Get the last element in an array, or `None` if the array is empty **Signature** ```ts export declare const last: (as: A[]) => Option ``` **Example** ```ts import { last } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(last([1, 2, 3]), some(3)) assert.deepStrictEqual(last([]), none) ``` Added in v2.0.0 ## lefts Takes an `Array` of `Either` and produces a new `Array` containing the values of all the `Left` elements in the same order. **Signature** ```ts export declare const lefts: (as: Either[]) => E[] ``` **Example** ```ts import { lefts } from 'fp-ts/Array' import { left, right } from 'fp-ts/Either' assert.deepStrictEqual(lefts([right(1), left('foo'), right(2)]), ['foo']) ``` Added in v2.0.0 ## lookup This function provides a safe way to read a value at a particular index from an array. It returns a `none` if the index is out of bounds, and a `some` of the element if the index is valid. **Signature** ```ts export declare const lookup: { (i: number): (as: A[]) => Option; (i: number, as: A[]): Option } ``` **Example** ```ts import { lookup } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], lookup(1)), some(2)) assert.deepStrictEqual(pipe([1, 2, 3], lookup(3)), none) ``` Added in v2.0.0 ## modifyAt Apply a function to the element at the specified index, creating a new array, or returning `None` if the index is out of bounds. **Signature** ```ts export declare const modifyAt: (i: number, f: (a: A) => A) => (as: A[]) => Option ``` **Example** ```ts import { modifyAt } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' const double = (x: number): number => x * 2 assert.deepStrictEqual(modifyAt(1, double)([1, 2, 3]), some([1, 4, 3])) assert.deepStrictEqual(modifyAt(1, double)([]), none) ``` Added in v2.0.0 ## prepend Prepend an element to the front of a `Array`, creating a new `NonEmptyArray`. **Signature** ```ts export declare const prepend: (head: A) => (tail: A[]) => NEA.NonEmptyArray ``` **Example** ```ts import { prepend } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([2, 3, 4], prepend(1)), [1, 2, 3, 4]) ``` Added in v2.10.0 ## prependAll Creates a new `Array`, prepending an element to every member of the input `Array`. **Signature** ```ts export declare const prependAll: (middle: A) => (as: A[]) => A[] ``` **Example** ```ts import { prependAll } from 'fp-ts/Array' assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.10.0 ## prependW Less strict version of [`prepend`](#prepend). **Signature** ```ts export declare const prependW: (head: B) => (tail: A[]) => NEA.NonEmptyArray ``` **Example** ```ts import { prependW } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([2, 3, 4], prependW('a')), ['a', 2, 3, 4]) ``` Added in v2.11.0 ## reverse Reverse an array, creating a new array **Signature** ```ts export declare const reverse: (as: A[]) => A[] ``` **Example** ```ts import { reverse } from 'fp-ts/Array' assert.deepStrictEqual(reverse([1, 2, 3]), [3, 2, 1]) ``` Added in v2.0.0 ## rights Takes an `Array` of `Either` and produces a new `Array` containing the values of all the `Right` elements in the same order. **Signature** ```ts export declare const rights: (as: Either[]) => A[] ``` **Example** ```ts import { rights } from 'fp-ts/Array' import { right, left } from 'fp-ts/Either' assert.deepStrictEqual(rights([right(1), left('foo'), right(2)]), [1, 2]) ``` Added in v2.0.0 ## rotate Creates a new `Array` rotating the input `Array` by `n` steps. **Signature** ```ts export declare const rotate: (n: number) => (as: A[]) => A[] ``` **Example** ```ts import { rotate } from 'fp-ts/Array' assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) ``` Added in v2.0.0 ## scanLeft Same as `reduce` but it carries over the intermediate steps **Signature** ```ts export declare const scanLeft: (b: B, f: (b: B, a: A) => B) => (as: A[]) => NEA.NonEmptyArray ``` **Example** ```ts import { scanLeft } from 'fp-ts/Array' assert.deepStrictEqual(scanLeft(10, (b, a: number) => b - a)([1, 2, 3]), [10, 9, 7, 4]) ``` Added in v2.0.0 ## scanRight Fold an array from the right, keeping all intermediate results instead of only the final result **Signature** ```ts export declare const scanRight: (b: B, f: (a: A, b: B) => B) => (as: A[]) => NEA.NonEmptyArray ``` **Example** ```ts import { scanRight } from 'fp-ts/Array' assert.deepStrictEqual(scanRight(10, (a: number, b) => b - a)([1, 2, 3]), [4, 5, 7, 10]) ``` Added in v2.0.0 ## size Calculate the number of elements in a `Array`. **Signature** ```ts export declare const size: (as: A[]) => number ``` **Example** ```ts import { size } from 'fp-ts/Array' assert.strictEqual(size(['a', 'b', 'c']), 3) ``` Added in v2.10.0 ## some `some` tells if the provided predicate holds true at least for one element in the `Array`. **Signature** ```ts export declare const some: (predicate: Predicate) => (as: A[]) => as is NEA.NonEmptyArray ``` **Example** ```ts import { some } from 'fp-ts/Array' assert.equal(some((x: number) => x >= 0)([1, 2, 3]), true) assert.equal(some((x: number) => x >= 10)([1, 2, 3]), false) ``` Added in v2.9.0 ## sort Sort the elements of an array in increasing order, creating a new array **Signature** ```ts export declare const sort: (O: Ord) => (as: A[]) => A[] ``` **Example** ```ts import { sort } from 'fp-ts/Array' import * as N from 'fp-ts/number' assert.deepStrictEqual(sort(N.Ord)([3, 2, 1]), [1, 2, 3]) ``` Added in v2.0.0 ## sortBy Sort the elements of an array in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, etc... **Signature** ```ts export declare const sortBy: (ords: Ord[]) => (as: A[]) => A[] ``` **Example** ```ts import { sortBy } from 'fp-ts/Array' import { contramap } from 'fp-ts/Ord' import * as S from 'fp-ts/string' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' interface Person { readonly name: string readonly age: number } const byName = pipe( S.Ord, contramap((p: Person) => p.name) ) const byAge = pipe( N.Ord, contramap((p: Person) => p.age) ) const sortByNameByAge = sortBy([byName, byAge]) const persons = [ { name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 }, ] assert.deepStrictEqual(sortByNameByAge(persons), [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, ]) ``` Added in v2.0.0 ## spanLeft Split an array into two parts: 1. the longest initial subarray for which all elements satisfy the specified predicate 2. the remaining elements **Signature** ```ts export declare function spanLeft(refinement: Refinement): (as: Array) => Spanned export declare function spanLeft(predicate: Predicate): (bs: Array) => Spanned export declare function spanLeft(predicate: Predicate): (as: Array) => Spanned ``` **Example** ```ts import { spanLeft } from 'fp-ts/Array' const isOdd = (n: number) => n % 2 === 1 assert.deepStrictEqual(spanLeft(isOdd)([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] }) assert.deepStrictEqual(spanLeft(isOdd)([0, 2, 4, 5]), { init: [], rest: [0, 2, 4, 5] }) assert.deepStrictEqual(spanLeft(isOdd)([1, 3, 5]), { init: [1, 3, 5], rest: [] }) ``` Added in v2.0.0 ## splitAt Splits an `Array` into two pieces, the first piece has max `n` elements. **Signature** ```ts export declare const splitAt: (n: number) => (as: A[]) => [A[], A[]] ``` **Example** ```ts import { splitAt } from 'fp-ts/Array' assert.deepStrictEqual(splitAt(2)([1, 2, 3, 4, 5]), [ [1, 2], [3, 4, 5], ]) ``` Added in v2.0.0 ## tail Get all but the first element of an array, creating a new array, or `None` if the array is empty **Signature** ```ts export declare const tail: (as: A[]) => Option ``` **Example** ```ts import { tail } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(tail([1, 2, 3]), some([2, 3])) assert.deepStrictEqual(tail([]), none) ``` Added in v2.0.0 ## takeLeft Keep only a max number of elements from the start of an `Array`, creating a new `Array`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const takeLeft: (n: number) => (as: A[]) => A[] ``` **Example** ```ts import { takeLeft } from 'fp-ts/Array' assert.deepStrictEqual(takeLeft(2)([1, 2, 3, 4, 5]), [1, 2]) assert.deepStrictEqual(takeLeft(7)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) assert.deepStrictEqual(takeLeft(0)([1, 2, 3, 4, 5]), []) assert.deepStrictEqual(takeLeft(-1)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) ``` Added in v2.0.0 ## takeLeftWhile Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new array **Signature** ```ts export declare function takeLeftWhile(refinement: Refinement): (as: Array) => Array export declare function takeLeftWhile(predicate: Predicate): (bs: Array) => Array export declare function takeLeftWhile(predicate: Predicate): (as: Array) => Array ``` **Example** ```ts import { takeLeftWhile } from 'fp-ts/Array' assert.deepStrictEqual(takeLeftWhile((n: number) => n % 2 === 0)([2, 4, 3, 6]), [2, 4]) ``` Added in v2.0.0 ## takeRight Keep only a max number of elements from the end of an `Array`, creating a new `Array`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const takeRight: (n: number) => (as: A[]) => A[] ``` **Example** ```ts import { takeRight } from 'fp-ts/Array' assert.deepStrictEqual(takeRight(2)([1, 2, 3, 4, 5]), [4, 5]) assert.deepStrictEqual(takeRight(7)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) assert.deepStrictEqual(takeRight(0)([1, 2, 3, 4, 5]), []) assert.deepStrictEqual(takeRight(-1)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) ``` Added in v2.0.0 ## unfold `unfold` takes a function `f` which returns an `Option` of a tuple containing an outcome value and an input for the following iteration. `unfold` applies `f` to the initial value `b` and then recursively to the second element of the tuple contained in the returned `option` of the previous calculation until `f` returns `Option.none`. **Signature** ```ts export declare const unfold: (b: B, f: (b: B) => Option) => A[] ``` **Example** ```ts import { unfold } from 'fp-ts/Array' import { option } from 'fp-ts' const f = (n: number) => { if (n <= 0) return option.none const returnValue = n * 2 const inputForNextRound = n - 1 return option.some([returnValue, inputForNextRound] as const) } assert.deepStrictEqual(unfold(5, f), [10, 8, 6, 4, 2]) ``` Added in v2.6.6 ## union Creates an array of unique values, in order, from all given arrays using a `Eq` for equality comparisons **Signature** ```ts export declare function union(E: Eq): { (xs: Array): (ys: Array) => Array (xs: Array, ys: Array): Array } ``` **Example** ```ts import { union } from 'fp-ts/Array' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2], union(N.Eq)([2, 3])), [1, 2, 3]) ``` Added in v2.0.0 ## uniq Creates a new `Array` removing duplicate elements, keeping the first occurrence of an element, based on a `Eq`. **Signature** ```ts export declare const uniq: (E: Eq) => (as: A[]) => A[] ``` **Example** ```ts import { uniq } from 'fp-ts/Array' import * as N from 'fp-ts/number' assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) ``` Added in v2.0.0 ## unzip The function is reverse of `zip`. Takes an array of pairs and return two corresponding arrays **Signature** ```ts export declare const unzip: (as: [A, B][]) => [A[], B[]] ``` **Example** ```ts import { unzip } from 'fp-ts/Array' assert.deepStrictEqual( unzip([ [1, 'a'], [2, 'b'], [3, 'c'], ]), [ [1, 2, 3], ['a', 'b', 'c'], ] ) ``` Added in v2.0.0 ## updateAt Change the element at the specified index, creating a new array, or returning `None` if the index is out of bounds. **Signature** ```ts export declare const updateAt: (i: number, a: A) => (as: A[]) => Option ``` **Example** ```ts import { updateAt } from 'fp-ts/Array' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(updateAt(1, 1)([1, 2, 3]), some([1, 1, 3])) assert.deepStrictEqual(updateAt(1, 1)([]), none) ``` Added in v2.0.0 ## zero Makes an empty `Array`, useful for building a [`Monoid`](#Monoid) **Signature** ```ts export declare const zero: () => A[] ``` Added in v2.7.0 ## zip Takes two arrays and returns an array of corresponding pairs. If one input array is short, excess elements of the longer array are discarded **Signature** ```ts export declare function zip(bs: Array): (as: Array) => Array<[A, B]> export declare function zip(as: Array, bs: Array): Array<[A, B]> ``` **Example** ```ts import { zip } from 'fp-ts/Array' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], zip(['a', 'b', 'c', 'd'])), [ [1, 'a'], [2, 'b'], [3, 'c'], ]) ``` Added in v2.0.0 ## zipWith Apply a function to pairs of elements at the same index in two arrays, collecting the results in a new array. If one input array is short, excess elements of the longer array are discarded. **Signature** ```ts export declare const zipWith: (fa: A[], fb: B[], f: (a: A, b: B) => C) => C[] ``` **Example** ```ts import { zipWith } from 'fp-ts/Array' assert.deepStrictEqual( zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3'] ) ``` Added in v2.0.0 # zone of death ## ~~array~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `A.Functor` instead of `A.array` (where `A` is from `import A from 'fp-ts/Array'`) **Signature** ```ts export declare const array: FunctorWithIndex1<'Array', number> & Monad1<'Array'> & Unfoldable1<'Array'> & Alternative1<'Array'> & Extend1<'Array'> & FilterableWithIndex1<'Array', number> & FoldableWithIndex1<'Array', number> & TraversableWithIndex1<'Array', number> & Witherable1<'Array'> ``` Added in v2.0.0 ## ~~cons~~ Use `prepend` instead. **Signature** ```ts export declare const cons: typeof NEA.cons ``` Added in v2.0.0 ## ~~empty~~ Use a new `[]` instead. **Signature** ```ts export declare const empty: never[] ``` Added in v2.0.0 ## ~~prependToAll~~ Use `prependAll` instead **Signature** ```ts export declare const prependToAll: (middle: A) => (as: A[]) => A[] ``` Added in v2.9.0 ## ~~range~~ Use `NonEmptyArray` module instead. **Signature** ```ts export declare const range: (start: number, end: number) => NEA.NonEmptyArray ``` Added in v2.0.0 ## ~~snoc~~ Use `append` instead. **Signature** ```ts export declare const snoc: (init: A[], end: A) => NEA.NonEmptyArray ``` Added in v2.0.0 ================================================ FILE: docs/modules/Bifunctor.ts.md ================================================ --- title: Bifunctor.ts nav_order: 6 parent: Modules --- ## Bifunctor overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Bifunctor (interface)](#bifunctor-interface) - [Bifunctor2 (interface)](#bifunctor2-interface) - [Bifunctor2C (interface)](#bifunctor2c-interface) - [Bifunctor3 (interface)](#bifunctor3-interface) - [Bifunctor3C (interface)](#bifunctor3c-interface) - [Bifunctor4 (interface)](#bifunctor4-interface) --- # model ## Bifunctor (interface) **Signature** ```ts export interface Bifunctor { readonly URI: F readonly bimap: (fea: HKT2, f: (e: E) => G, g: (a: A) => B) => HKT2 readonly mapLeft: (fea: HKT2, f: (e: E) => G) => HKT2 } ``` Added in v2.0.0 ## Bifunctor2 (interface) **Signature** ```ts export interface Bifunctor2 { readonly URI: F readonly bimap: (fea: Kind2, f: (e: E) => G, g: (a: A) => B) => Kind2 readonly mapLeft: (fea: Kind2, f: (e: E) => G) => Kind2 } ``` Added in v2.0.0 ## Bifunctor2C (interface) **Signature** ```ts export interface Bifunctor2C { readonly URI: F readonly _E: E readonly bimap: (fea: Kind2, f: (e: E) => G, g: (a: A) => B) => Kind2 readonly mapLeft: (fea: Kind2, f: (e: E) => M) => Kind2 } ``` Added in v2.0.0 ## Bifunctor3 (interface) **Signature** ```ts export interface Bifunctor3 { readonly URI: F readonly bimap: (fea: Kind3, f: (e: E) => G, g: (a: A) => B) => Kind3 readonly mapLeft: (fea: Kind3, f: (e: E) => G) => Kind3 } ``` Added in v2.0.0 ## Bifunctor3C (interface) **Signature** ```ts export interface Bifunctor3C { readonly URI: F readonly _E: E readonly bimap: (fea: Kind3, f: (e: E) => G, g: (a: A) => B) => Kind3 readonly mapLeft: (fea: Kind3, f: (e: E) => G) => Kind3 } ``` Added in v2.2.0 ## Bifunctor4 (interface) **Signature** ```ts export interface Bifunctor4 { readonly URI: F readonly bimap: (fea: Kind4, f: (e: E) => G, g: (a: A) => B) => Kind4 readonly mapLeft: (fea: Kind4, f: (e: E) => G) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/BooleanAlgebra.ts.md ================================================ --- title: BooleanAlgebra.ts nav_order: 8 parent: Modules --- ## BooleanAlgebra overview Boolean algebras are Heyting algebras with the additional constraint that the law of the excluded middle is true (equivalently, double-negation is true). Instances should satisfy the following laws in addition to the `HeytingAlgebra` laws: - Excluded middle: `a ∨ ¬a <-> 1` Boolean algebras generalize classical logic: one is equivalent to "true" and zero is equivalent to "false". Added in v2.0.0 ---

Table of contents

- [instances](#instances) - [booleanAlgebraVoid](#booleanalgebravoid) - [model](#model) - [BooleanAlgebra (interface)](#booleanalgebra-interface) - [utils](#utils) - [reverse](#reverse) - [zone of death](#zone-of-death) - [~~booleanAlgebraBoolean~~](#booleanalgebraboolean) - [~~getDualBooleanAlgebra~~](#getdualbooleanalgebra) - [~~getFunctionBooleanAlgebra~~](#getfunctionbooleanalgebra) --- # instances ## booleanAlgebraVoid **Signature** ```ts export declare const booleanAlgebraVoid: BooleanAlgebra ``` Added in v2.0.0 # model ## BooleanAlgebra (interface) **Signature** ```ts export interface BooleanAlgebra
extends HeytingAlgebra {} ``` Added in v2.0.0 # utils ## reverse Every boolean algebras has a dual algebra, which involves reversing one/zero as well as join/meet. **Signature** ```ts export declare const reverse: (B: BooleanAlgebra) => BooleanAlgebra ``` Added in v2.10.0 # zone of death ## ~~booleanAlgebraBoolean~~ Use [`BooleanAlgebra`](./boolean.ts.html#booleanalgebra) instead. **Signature** ```ts export declare const booleanAlgebraBoolean: BooleanAlgebra ``` Added in v2.0.0 ## ~~getDualBooleanAlgebra~~ Use [`reverse`](#reverse) instead. **Signature** ```ts export declare const getDualBooleanAlgebra: (B: BooleanAlgebra) => BooleanAlgebra ``` Added in v2.0.0 ## ~~getFunctionBooleanAlgebra~~ Use [`getBooleanAlgebra`](./function.ts.html#getbooleanalgebra) instead. **Signature** ```ts export declare const getFunctionBooleanAlgebra: ( B: BooleanAlgebra ) => () => BooleanAlgebra<(a: A) => B> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Bounded.ts.md ================================================ --- title: Bounded.ts nav_order: 9 parent: Modules --- ## Bounded overview The `Bounded` type class represents totally ordered types that have an upper and lower boundary. Instances should satisfy the following law in addition to the `Ord` laws: - Bounded: `bottom <= a <= top` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Bounded (interface)](#bounded-interface) - [utils](#utils) - [clamp](#clamp) - [reverse](#reverse) - [zone of death](#zone-of-death) - [~~boundedNumber~~](#boundednumber) --- # model ## Bounded (interface) **Signature** ```ts export interface Bounded
extends Ord { readonly top: A readonly bottom: A } ``` Added in v2.0.0 # utils ## clamp Clamp a value between bottom and top values. **Signature** ```ts export declare const clamp: (B: Bounded) => (a: A) => A ``` Added in v2.12.0 ## reverse Reverses the Ord of a bound and swaps top and bottom values. **Signature** ```ts export declare const reverse: (B: Bounded) => Bounded ``` Added in v2.12.0 # zone of death ## ~~boundedNumber~~ Use [`Bounded`](./number.ts.html#bounded) instead. **Signature** ```ts export declare const boundedNumber: Bounded ``` Added in v2.0.0 ================================================ FILE: docs/modules/BoundedDistributiveLattice.ts.md ================================================ --- title: BoundedDistributiveLattice.ts nav_order: 10 parent: Modules --- ## BoundedDistributiveLattice overview A `BoundedDistributiveLattice` is a lattice that is both bounded and distributive Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [getMinMaxBoundedDistributiveLattice](#getminmaxboundeddistributivelattice) - [model](#model) - [BoundedDistributiveLattice (interface)](#boundeddistributivelattice-interface) --- # constructors ## getMinMaxBoundedDistributiveLattice **Signature** ```ts export declare function getMinMaxBoundedDistributiveLattice
( O: Ord ): (min: A, max: A) => BoundedDistributiveLattice ``` Added in v2.0.0 # model ## BoundedDistributiveLattice (interface) **Signature** ```ts export interface BoundedDistributiveLattice extends BoundedLattice, DistributiveLattice {} ``` Added in v2.0.0 ================================================ FILE: docs/modules/BoundedJoinSemilattice.ts.md ================================================ --- title: BoundedJoinSemilattice.ts nav_order: 11 parent: Modules --- ## BoundedJoinSemilattice overview A `BoundedJoinSemilattice` must satisfy the following laws in addition to `JoinSemilattice` laws: - `a ∨ 0 <-> a` Added in v2.0.0 ---

Table of contents

- [model](#model) - [BoundedJoinSemilattice (interface)](#boundedjoinsemilattice-interface) --- # model ## BoundedJoinSemilattice (interface) **Signature** ```ts export interface BoundedJoinSemilattice
extends JoinSemilattice { readonly zero: A } ``` Added in v2.0.0 ================================================ FILE: docs/modules/BoundedLattice.ts.md ================================================ --- title: BoundedLattice.ts nav_order: 12 parent: Modules --- ## BoundedLattice overview A `BoundedLattice` must satisfy the following in addition to `BoundedMeetSemilattice` and `BoundedJoinSemilattice` laws: - Absorption law for meet: `a ∧ (a ∨ b) <-> a` - Absorption law for join: `a ∨ (a ∧ b) <-> a` Added in v2.0.0 ---

Table of contents

- [model](#model) - [BoundedLattice (interface)](#boundedlattice-interface) --- # model ## BoundedLattice (interface) **Signature** ```ts export interface BoundedLattice
extends BoundedJoinSemilattice, BoundedMeetSemilattice {} ``` Added in v2.0.0 ================================================ FILE: docs/modules/BoundedMeetSemilattice.ts.md ================================================ --- title: BoundedMeetSemilattice.ts nav_order: 13 parent: Modules --- ## BoundedMeetSemilattice overview A `BoundedMeetSemilattice` must satisfy the following laws in addition to `MeetSemilattice` laws: - `a ∧ 1 <-> a` Added in v2.0.0 ---

Table of contents

- [model](#model) - [BoundedMeetSemilattice (interface)](#boundedmeetsemilattice-interface) --- # model ## BoundedMeetSemilattice (interface) **Signature** ```ts export interface BoundedMeetSemilattice
extends MeetSemilattice { readonly one: A } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Category.ts.md ================================================ --- title: Category.ts nav_order: 14 parent: Modules --- ## Category overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Category (interface)](#category-interface) - [Category2 (interface)](#category2-interface) - [Category3 (interface)](#category3-interface) - [Category4 (interface)](#category4-interface) --- # model ## Category (interface) **Signature** ```ts export interface Category extends Semigroupoid { readonly id:
() => HKT2 } ``` Added in v2.0.0 ## Category2 (interface) **Signature** ```ts export interface Category2 extends Semigroupoid2 { readonly id: () => Kind2 } ``` Added in v2.0.0 ## Category3 (interface) **Signature** ```ts export interface Category3 extends Semigroupoid3 { readonly id: () => Kind3 } ``` Added in v2.0.0 ## Category4 (interface) **Signature** ```ts export interface Category4 extends Semigroupoid4 { readonly id: () => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Chain.ts.md ================================================ --- title: Chain.ts nav_order: 15 parent: Modules --- ## Chain overview The `Chain` type class extends the `Apply` type class with a `chain` operation which composes computations in sequence, using the return value of one computation to determine the next computation. Instances must satisfy the following law in addition to the `Apply` laws: 1. Associativity: `F.chain(F.chain(fa, afb), bfc) <-> F.chain(fa, a => F.chain(afb(a), bfc))` Note. `Apply`'s `ap` can be derived: `(fab, fa) => F.chain(fab, f => F.map(fa, f))` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Chain (interface)](#chain-interface) - [Chain1 (interface)](#chain1-interface) - [Chain2 (interface)](#chain2-interface) - [Chain2C (interface)](#chain2c-interface) - [Chain3 (interface)](#chain3-interface) - [Chain3C (interface)](#chain3c-interface) - [Chain4 (interface)](#chain4-interface) - [utils](#utils) - [bind](#bind) - [chainFirst](#chainfirst) --- # model ## Chain (interface) **Signature** ```ts export interface Chain extends Apply { readonly chain: (fa: HKT, f: (a: A) => HKT) => HKT } ``` Added in v2.0.0 ## Chain1 (interface) **Signature** ```ts export interface Chain1 extends Apply1 { readonly chain: (fa: Kind, f: (a: A) => Kind) => Kind } ``` Added in v2.0.0 ## Chain2 (interface) **Signature** ```ts export interface Chain2 extends Apply2 { readonly chain: (fa: Kind2, f: (a: A) => Kind2) => Kind2 } ``` Added in v2.0.0 ## Chain2C (interface) **Signature** ```ts export interface Chain2C extends Apply2C { readonly chain: (fa: Kind2, f: (a: A) => Kind2) => Kind2 } ``` Added in v2.0.0 ## Chain3 (interface) **Signature** ```ts export interface Chain3 extends Apply3 { readonly chain: (fa: Kind3, f: (a: A) => Kind3) => Kind3 } ``` Added in v2.0.0 ## Chain3C (interface) **Signature** ```ts export interface Chain3C extends Apply3C { readonly chain: (fa: Kind3, f: (a: A) => Kind3) => Kind3 } ``` Added in v2.2.0 ## Chain4 (interface) **Signature** ```ts export interface Chain4 extends Apply4 { readonly chain: (fa: Kind4, f: (a: A) => Kind4) => Kind4 } ``` Added in v2.0.0 # utils ## bind **Signature** ```ts export declare function bind( M: Chain4 ): ( name: Exclude, f: (a: A) => Kind4 ) => (ma: Kind4) => Kind4 export declare function bind( M: Chain3 ): ( name: Exclude, f: (a: A) => Kind3 ) => (ma: Kind3) => Kind3 export declare function bind( M: Chain3C ): ( name: Exclude, f: (a: A) => Kind3 ) => (ma: Kind3) => Kind3 export declare function bind( M: Chain2 ): ( name: Exclude, f: (a: A) => Kind2 ) => (ma: Kind2) => Kind2 export declare function bind( M: Chain2C ): ( name: Exclude, f: (a: A) => Kind2 ) => (ma: Kind2) => Kind2 export declare function bind( M: Chain1 ): ( name: Exclude, f: (a: A) => Kind ) => (ma: Kind) => Kind export declare function bind( M: Chain ): ( name: Exclude, f: (a: A) => HKT ) => (ma: HKT) => HKT ``` Added in v2.10.0 ## chainFirst **Signature** ```ts export declare function chainFirst( M: Chain4 ): (f: (a: A) => Kind4) => (first: Kind4) => Kind4 export declare function chainFirst( M: Chain3 ): (f: (a: A) => Kind3) => (first: Kind3) => Kind3 export declare function chainFirst( M: Chain3C ): (f: (a: A) => Kind3) => (first: Kind3) => Kind3 export declare function chainFirst( M: Chain2 ): (f: (a: A) => Kind2) => (first: Kind2) => Kind2 export declare function chainFirst( M: Chain2C ): (f: (a: A) => Kind2) => (first: Kind2) => Kind2 export declare function chainFirst( M: Chain1 ): (f: (a: A) => Kind) => (first: Kind) => Kind export declare function chainFirst(M: Chain): (f: (a: A) => HKT) => (first: HKT) => HKT ``` Added in v2.10.0 ================================================ FILE: docs/modules/ChainRec.ts.md ================================================ --- title: ChainRec.ts nav_order: 16 parent: Modules --- ## ChainRec overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [ChainRec (interface)](#chainrec-interface) - [ChainRec1 (interface)](#chainrec1-interface) - [ChainRec2 (interface)](#chainrec2-interface) - [ChainRec2C (interface)](#chainrec2c-interface) - [ChainRec3 (interface)](#chainrec3-interface) - [ChainRec3C (interface)](#chainrec3c-interface) - [ChainRec4 (interface)](#chainrec4-interface) - [utils](#utils) - [tailRec](#tailrec) --- # model ## ChainRec (interface) **Signature** ```ts export interface ChainRec extends Chain { readonly chainRec: (a: A, f: (a: A) => HKT>) => HKT } ``` Added in v2.0.0 ## ChainRec1 (interface) **Signature** ```ts export interface ChainRec1 extends Chain1 { readonly chainRec: (a: A, f: (a: A) => Kind>) => Kind } ``` Added in v2.0.0 ## ChainRec2 (interface) **Signature** ```ts export interface ChainRec2 extends Chain2 { readonly chainRec: (a: A, f: (a: A) => Kind2>) => Kind2 } ``` Added in v2.0.0 ## ChainRec2C (interface) **Signature** ```ts export interface ChainRec2C extends Chain2C { readonly chainRec: (a: A, f: (a: A) => Kind2>) => Kind2 } ``` Added in v2.0.0 ## ChainRec3 (interface) **Signature** ```ts export interface ChainRec3 extends Chain3 { readonly chainRec: (a: A, f: (a: A) => Kind3>) => Kind3 } ``` Added in v2.0.0 ## ChainRec3C (interface) **Signature** ```ts export interface ChainRec3C extends Chain3C { readonly chainRec: (a: A, f: (a: A) => Kind3>) => Kind3 } ``` Added in v2.10.0 ## ChainRec4 (interface) **Signature** ```ts export interface ChainRec4 extends Chain4 { readonly chainRec: (a: A, f: (a: A) => Kind4>) => Kind4 } ``` Added in v2.10.0 # utils ## tailRec **Signature** ```ts export declare const tailRec: (startWith: A, f: (a: A) => Either) => B ``` Added in v2.0.0 ================================================ FILE: docs/modules/Choice.ts.md ================================================ --- title: Choice.ts nav_order: 17 parent: Modules --- ## Choice overview The `Choice` class extends `Profunctor` with combinators for working with sum types. `left` and `right` lift values in a `Profunctor` to act on the `Left` and `Right` components of a sum, respectively. Looking at `Choice` through the intuition of inputs and outputs yields the following type signature: ```purescript left :: forall input output a. p input output -> p (Either input a) (Either output a) right :: forall input output a. p input output -> p (Either a input) (Either a output) ``` If we specialize the profunctor `p` to the `function` arrow, we get the following type signatures: ```purescript left :: forall input output a. (input -> output) -> (Either input a) -> (Either output a) right :: forall input output a. (input -> output) -> (Either a input) -> (Either a output) ``` When the `profunctor` is `Function` application, `left` allows you to map a function over the left side of an `Either`, and `right` maps it over the right side (same as `map` would do). Adapted from https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Choice.purs Added in v2.0.0 ---

Table of contents

- [model](#model) - [Choice (interface)](#choice-interface) - [Choice2 (interface)](#choice2-interface) - [Choice3 (interface)](#choice3-interface) - [Choice4 (interface)](#choice4-interface) - [utils](#utils) - [fanIn](#fanin) - [split](#split) - [~~fanin~~](#fanin) - [zone of death](#zone-of-death) - [~~splitChoice~~](#splitchoice) --- # model ## Choice (interface) **Signature** ```ts export interface Choice extends Profunctor { readonly left: (pab: HKT2) => HKT2, Either> readonly right: (pbc: HKT2) => HKT2, Either> } ``` Added in v2.0.0 ## Choice2 (interface) **Signature** ```ts export interface Choice2 extends Profunctor2 { readonly left: (pab: Kind2) => Kind2, Either> readonly right: (pbc: Kind2) => Kind2, Either> } ``` Added in v2.0.0 ## Choice3 (interface) **Signature** ```ts export interface Choice3 extends Profunctor3 { readonly left: (pab: Kind3) => Kind3, Either> readonly right: (pbc: Kind3) => Kind3, Either> } ``` Added in v2.0.0 ## Choice4 (interface) **Signature** ```ts export interface Choice4 extends Profunctor4 { readonly left: (pab: Kind4) => Kind4, Either> readonly right: (pbc: Kind4) => Kind4, Either> } ``` Added in v2.0.0 # utils ## fanIn Compose a value which eliminates a sum from two values, each eliminating one side of the sum. This combinator is useful when assembling values from smaller components, because it provides a way to support two different types of input. Specializing `fanIn` to function application would look like this: ```purescript fanIn :: forall a b c d. (a -> c) -> (b -> c) -> Either a b -> c ``` We take two functions, `f` and `g`, which both return the same type `c` and we transform them into a single function which takes an `Either` value with the parameter type of `f` on the left side and the parameter type of `g` on the right side. The function then runs either `f` or `g`, depending on whether the `Either` value is a `Left` or a `Right`. This allows us to bundle two different computations which both have the same result type into one function which will run the appropriate computation based on the parameter supplied in the `Either` value. **Signature** ```ts export declare function fanIn

( P: Choice4

, C: Category4

): (pac: Kind4, pbc: Kind4) => Kind4, C> export declare function fanIn

( P: Choice3

, C: Category3

): (pac: Kind3, pbc: Kind3) => Kind3, C> export declare function fanIn

( P: Choice2

, C: Category2

): (pac: Kind2, pbc: Kind2) => Kind2, C> export declare function fanIn

( P: Choice

, C: Category

): (pac: HKT2, pbc: HKT2) => HKT2, C> ``` Added in v2.10.0 ## split Compose a value acting on a sum from two values, each acting on one of the components of the sum. Specializing `split` to function application would look like this: ```purescript split :: forall a b c d. (a -> b) -> (c -> d) -> (Either a c) -> (Either b d) ``` We take two functions, `f` and `g`, and we transform them into a single function which takes an `Either`and maps `f` over the left side and `g` over the right side. Just like `bimap` would do for the `Bifunctor` instance of `Either`. **Signature** ```ts export declare function split

( P: Choice4

, C: Category4

): ( pab: Kind4, pcd: Kind4 ) => Kind4, Either> export declare function split

( P: Choice3

, C: Category3

): (pab: Kind3, pcd: Kind3) => Kind3, Either> export declare function split

( P: Choice2

, C: Category2

): (pab: Kind2, pcd: Kind2) => Kind2, Either> export declare function split

( P: Choice

, C: Category

): (pab: HKT2, pcd: HKT2) => HKT2, Either> ``` Added in v2.10.0 ## ~~fanin~~ Use [`fanIn`](#fanIn) instead. **Signature** ```ts export declare function fanin( F: Category3 & Choice3 ): (pac: Kind3, pbc: Kind3) => Kind3, C> export declare function fanin( F: Category2 & Choice2 ): (pac: Kind2, pbc: Kind2) => Kind2, C> export declare function fanin( F: Category & Choice ): (pac: HKT2, pbc: HKT2) => HKT2, C> ``` Added in v2.0.0 # zone of death ## ~~splitChoice~~ Use [`split`](#split) instead. **Signature** ```ts export declare function splitChoice( F: Category3 & Choice3 ): (pab: Kind3, pcd: Kind3) => Kind3, Either> export declare function splitChoice( F: Category2 & Choice2 ): (pab: Kind2, pcd: Kind2) => Kind2, Either> export declare function splitChoice( F: Category & Choice ): (pab: HKT2, pcd: HKT2) => HKT2, Either> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Comonad.ts.md ================================================ --- title: Comonad.ts nav_order: 18 parent: Modules --- ## Comonad overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Comonad (interface)](#comonad-interface) - [Comonad1 (interface)](#comonad1-interface) - [Comonad2 (interface)](#comonad2-interface) - [Comonad2C (interface)](#comonad2c-interface) - [Comonad3 (interface)](#comonad3-interface) - [Comonad3C (interface)](#comonad3c-interface) - [Comonad4 (interface)](#comonad4-interface) --- # model ## Comonad (interface) **Signature** ```ts export interface Comonad extends Extend { readonly extract:
(wa: HKT) => A } ``` Added in v2.0.0 ## Comonad1 (interface) **Signature** ```ts export interface Comonad1 extends Extend1 { readonly extract: (wa: Kind) => A } ``` Added in v2.0.0 ## Comonad2 (interface) **Signature** ```ts export interface Comonad2 extends Extend2 { readonly extract: (wa: Kind2) => A } ``` Added in v2.0.0 ## Comonad2C (interface) **Signature** ```ts export interface Comonad2C extends Extend2C { readonly extract: (wa: Kind2) => A } ``` Added in v2.0.0 ## Comonad3 (interface) **Signature** ```ts export interface Comonad3 extends Extend3 { readonly extract: (wa: Kind3) => A } ``` Added in v2.0.0 ## Comonad3C (interface) **Signature** ```ts export interface Comonad3C extends Extend3C { readonly extract: (wa: Kind3) => A } ``` Added in v2.10.0 ## Comonad4 (interface) **Signature** ```ts export interface Comonad4 extends Extend4 { readonly extract: (wa: Kind4) => A } ``` Added in v2.10.0 ================================================ FILE: docs/modules/Compactable.ts.md ================================================ --- title: Compactable.ts nav_order: 19 parent: Modules --- ## Compactable overview `Compactable` represents data structures which can be _compacted_/_filtered_. This is a generalization of `catOptions` as a new function `compact`. `compact` has relations with `Functor`, `Applicative`, `Monad`, `Alternative`, and `Traversable` in that we can use these classes to provide the ability to operate on a data type by eliminating intermediate `None`s. This is useful for representing the filtering out of values, or failure. Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Compactable.purs Added in v2.0.0 ---

Table of contents

- [model](#model) - [Compactable (interface)](#compactable-interface) - [Compactable1 (interface)](#compactable1-interface) - [Compactable2 (interface)](#compactable2-interface) - [Compactable2C (interface)](#compactable2c-interface) - [Compactable3 (interface)](#compactable3-interface) - [Compactable3C (interface)](#compactable3c-interface) - [Compactable4 (interface)](#compactable4-interface) - [utils](#utils) - [compact](#compact) - [separate](#separate) - [~~Separated~~ (interface)](#separated-interface) - [zone of death](#zone-of-death) - [~~CompactableComposition11~~ (interface)](#compactablecomposition11-interface) - [~~CompactableComposition12C~~ (interface)](#compactablecomposition12c-interface) - [~~CompactableComposition12~~ (interface)](#compactablecomposition12-interface) - [~~CompactableComposition21~~ (interface)](#compactablecomposition21-interface) - [~~CompactableComposition22C~~ (interface)](#compactablecomposition22c-interface) - [~~CompactableComposition22~~ (interface)](#compactablecomposition22-interface) - [~~CompactableComposition23C~~ (interface)](#compactablecomposition23c-interface) - [~~CompactableComposition23~~ (interface)](#compactablecomposition23-interface) - [~~CompactableComposition2C1~~ (interface)](#compactablecomposition2c1-interface) - [~~CompactableComposition~~ (interface)](#compactablecomposition-interface) - [~~getCompactableComposition~~](#getcompactablecomposition) --- # model ## Compactable (interface) **Signature** ```ts export interface Compactable { readonly URI: F /** * Compacts a data structure unwrapping inner Option */ readonly compact:
(fa: HKT>) => HKT /** * Separates a data structure moving inner Left to the left side and inner Right to the right side of Separated */ readonly separate: (fa: HKT>) => S.Separated, HKT> } ``` Added in v2.0.0 ## Compactable1 (interface) **Signature** ```ts export interface Compactable1 { readonly URI: F readonly compact: (fa: Kind>) => Kind readonly separate: (fa: Kind>) => S.Separated, Kind> } ``` Added in v2.0.0 ## Compactable2 (interface) **Signature** ```ts export interface Compactable2 { readonly URI: F readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => S.Separated, Kind2> } ``` Added in v2.0.0 ## Compactable2C (interface) **Signature** ```ts export interface Compactable2C { readonly URI: F readonly _E: E readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => S.Separated, Kind2> } ``` Added in v2.0.0 ## Compactable3 (interface) **Signature** ```ts export interface Compactable3 { readonly URI: F readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => S.Separated, Kind3> } ``` Added in v2.0.0 ## Compactable3C (interface) **Signature** ```ts export interface Compactable3C { readonly URI: F readonly _E: E readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => S.Separated, Kind3> } ``` Added in v2.2.0 ## Compactable4 (interface) **Signature** ```ts export interface Compactable4 { readonly URI: F readonly compact: (fa: Kind4>) => Kind4 readonly separate: ( fa: Kind4> ) => S.Separated, Kind4> } ``` Added in v2.0.0 # utils ## compact `compact` composition. **Signature** ```ts export declare function compact( F: Functor2, G: Compactable2C ): (fa: Kind2>>) => Kind2> export declare function compact( F: Functor1, G: Compactable2C ): (fa: Kind>>) => Kind> export declare function compact( F: Functor1, G: Compactable1 ): (fa: Kind>>) => Kind> export declare function compact( F: Functor, G: Compactable ): (fa: HKT>>) => HKT> ``` Added in v2.10.0 ## separate `separate` composition. **Signature** ```ts export declare function separate( F: Functor2, C: Compactable2C, G: Functor2 ): ( fge: Kind2>> ) => S.Separated>, Kind2>> export declare function separate( F: Functor1, C: Compactable2C, G: Functor2 ): (fge: Kind>>) => S.Separated>, Kind>> export declare function separate( F: Functor1, C: Compactable1, G: Functor1 ): (fge: Kind>>) => S.Separated>, Kind>> export declare function separate( F: Functor, C: Compactable, G: Functor ): (fge: HKT>>) => S.Separated>, HKT>> ``` Added in v2.10.0 ## ~~Separated~~ (interface) Use [`Separated`](./Separated.ts.html#separated) instead. **Signature** ```ts export interface Separated { readonly left: A readonly right: B } ``` Added in v2.0.0 # zone of death ## ~~CompactableComposition11~~ (interface) **Signature** ```ts export interface CompactableComposition11 extends FunctorComposition11 { readonly compact: (fga: Kind>>) => Kind> readonly separate: (fge: Kind>>) => Separated>, Kind>> } ``` Added in v2.0.0 ## ~~CompactableComposition12C~~ (interface) **Signature** ```ts export interface CompactableComposition12C extends FunctorComposition12C { readonly compact: (fga: Kind>>) => Kind> readonly separate: ( fge: Kind>> ) => Separated>, Kind>> } ``` Added in v2.0.0 ## ~~CompactableComposition12~~ (interface) **Signature** ```ts export interface CompactableComposition12 extends FunctorComposition12 { readonly compact: (fga: Kind>>) => Kind> readonly separate: ( fge: Kind>> ) => Separated>, Kind>> } ``` Added in v2.0.0 ## ~~CompactableComposition21~~ (interface) **Signature** ```ts export interface CompactableComposition21 extends FunctorComposition21 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } ``` Added in v2.0.0 ## ~~CompactableComposition22C~~ (interface) **Signature** ```ts export interface CompactableComposition22C extends FunctorComposition22C { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } ``` Added in v2.0.0 ## ~~CompactableComposition22~~ (interface) **Signature** ```ts export interface CompactableComposition22 extends FunctorComposition22 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } ``` Added in v2.0.0 ## ~~CompactableComposition23C~~ (interface) **Signature** ```ts export interface CompactableComposition23C extends FunctorComposition23C { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } ``` Added in v2.2.0 ## ~~CompactableComposition23~~ (interface) **Signature** ```ts export interface CompactableComposition23 extends FunctorComposition23 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } ``` Added in v2.2.0 ## ~~CompactableComposition2C1~~ (interface) **Signature** ```ts export interface CompactableComposition2C1 extends FunctorComposition2C1 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } ``` Added in v2.0.0 ## ~~CompactableComposition~~ (interface) **Signature** ```ts export interface CompactableComposition extends FunctorComposition { readonly compact: (fga: HKT>>) => HKT> readonly separate: (fge: HKT>>) => Separated>, HKT>> } ``` Added in v2.0.0 ## ~~getCompactableComposition~~ Use [`compact`](#compact) and [`separate`](#separate) instead. **Signature** ```ts export declare function getCompactableComposition( F: Functor2, G: Compactable3C & Functor3C ): CompactableComposition23C export declare function getCompactableComposition( F: Functor2, G: Compactable2C & Functor2C ): CompactableComposition22C export declare function getCompactableComposition( F: Functor2, G: Compactable2 & Functor2 ): CompactableComposition22 export declare function getCompactableComposition( F: Functor2C, G: Compactable1 & Functor1 ): CompactableComposition2C1 export declare function getCompactableComposition( F: Functor2, G: Compactable1 & Functor1 ): CompactableComposition21 export declare function getCompactableComposition( F: Functor1, G: Compactable2C & Functor2C ): CompactableComposition12 export declare function getCompactableComposition( F: Functor1, G: Compactable2 & Functor2 ): CompactableComposition12 export declare function getCompactableComposition( F: Functor1, G: Compactable1 & Functor1 ): CompactableComposition11 export declare function getCompactableComposition( F: Functor, G: Compactable & Functor ): CompactableComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/Console.ts.md ================================================ --- title: Console.ts nav_order: 20 parent: Modules --- ## Console overview Added in v2.0.0 ---

Table of contents

- [utils](#utils) - [error](#error) - [info](#info) - [log](#log) - [warn](#warn) --- # utils ## error **Signature** ```ts export declare const error:
(a: A) => IO ``` Added in v2.0.0 ## info **Signature** ```ts export declare const info: (a: A) => IO ``` Added in v2.0.0 ## log **Signature** ```ts export declare const log: (a: A) => IO ``` Added in v2.0.0 ## warn **Signature** ```ts export declare const warn: (a: A) => IO ``` Added in v2.0.0 ================================================ FILE: docs/modules/Const.ts.md ================================================ --- title: Const.ts nav_order: 21 parent: Modules --- ## Const overview The `Const` type constructor, which wraps its first type argument and ignores its second. That is, `Const` is isomorphic to `E` for any `A`. `Const` has some useful instances. For example, the `Applicative` instance allows us to collect results using a `Monoid` while ignoring return values. Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [make](#make) - [error handling](#error-handling) - [mapLeft](#mapleft) - [instances](#instances) - [Bifunctor](#bifunctor) - [Contravariant](#contravariant) - [Functor](#functor) - [getApplicative](#getapplicative) - [getApply](#getapply) - [getBooleanAlgebra](#getbooleanalgebra) - [getBounded](#getbounded) - [getEq](#geteq) - [getHeytingAlgebra](#getheytingalgebra) - [getMonoid](#getmonoid) - [getOrd](#getord) - [getRing](#getring) - [getSemigroup](#getsemigroup) - [getSemiring](#getsemiring) - [getShow](#getshow) - [mapping](#mapping) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [model](#model) - [Const (type alias)](#const-type-alias) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [contramap](#contramap) - [zone of death](#zone-of-death) - [~~const\_~~](#const_) --- # constructors ## make **Signature** ```ts export declare const make: (e: E) => Const ``` Added in v2.0.0 # error handling ## mapLeft Map a function over the first type argument of a bifunctor. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) =>
(fa: Const) => Const ``` Added in v2.6.2 # instances ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'Const'> ``` Added in v2.7.0 ## Contravariant **Signature** ```ts export declare const Contravariant: Contravariant2<'Const'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Const'> ``` Added in v2.7.0 ## getApplicative **Signature** ```ts export declare function getApplicative(M: Monoid): Applicative2C ``` Added in v2.0.0 ## getApply **Signature** ```ts export declare function getApply(S: Semigroup): Apply2C ``` Added in v2.0.0 ## getBooleanAlgebra **Signature** ```ts export declare const getBooleanAlgebra: (H: BooleanAlgebra) => BooleanAlgebra> ``` Added in v2.6.0 ## getBounded **Signature** ```ts export declare const getBounded: (B: Bounded) => Bounded> ``` Added in v2.6.0 ## getEq **Signature** ```ts export declare const getEq: (E: Eq) => Eq> ``` Added in v2.0.0 ## getHeytingAlgebra **Signature** ```ts export declare const getHeytingAlgebra: (H: HeytingAlgebra) => HeytingAlgebra> ``` Added in v2.6.0 ## getMonoid **Signature** ```ts export declare const getMonoid: (M: Monoid) => Monoid> ``` Added in v2.6.0 ## getOrd **Signature** ```ts export declare const getOrd: (O: Ord) => Ord> ``` Added in v2.6.0 ## getRing **Signature** ```ts export declare const getRing: (S: Ring) => Ring> ``` Added in v2.6.0 ## getSemigroup **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.6.0 ## getSemiring **Signature** ```ts export declare const getSemiring: (S: Semiring) => Semiring> ``` Added in v2.6.0 ## getShow **Signature** ```ts export declare function getShow(S: Show): Show> ``` Added in v2.0.0 # mapping ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Const) => Const ``` Added in v2.6.2 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Const B>) => Const ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Const) => Const ``` Added in v2.0.0 # model ## Const (type alias) **Signature** ```ts export type Const = E & { readonly _A: A } ``` Added in v2.0.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Const' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## contramap **Signature** ```ts export declare const contramap: (f: (b: B) => A) => (fa: Const) => Const ``` Added in v2.0.0 # zone of death ## ~~const\_~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `C.Functor` instead of `C.const_` (where `C` is from `import C from 'fp-ts/Const'`) **Signature** ```ts export declare const const_: Functor2<'Const'> & Contravariant2<'Const'> & Bifunctor2<'Const'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Contravariant.ts.md ================================================ --- title: Contravariant.ts nav_order: 22 parent: Modules --- ## Contravariant overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Contravariant (interface)](#contravariant-interface) - [Contravariant1 (interface)](#contravariant1-interface) - [Contravariant2 (interface)](#contravariant2-interface) - [Contravariant2C (interface)](#contravariant2c-interface) - [Contravariant3 (interface)](#contravariant3-interface) - [Contravariant3C (interface)](#contravariant3c-interface) - [Contravariant4 (interface)](#contravariant4-interface) --- # model ## Contravariant (interface) **Signature** ```ts export interface Contravariant { readonly URI: F readonly contramap: (fa: HKT, f: (b: B) => A) => HKT } ``` Added in v2.0.0 ## Contravariant1 (interface) **Signature** ```ts export interface Contravariant1 { readonly URI: F readonly contramap: (fa: Kind, f: (b: B) => A) => Kind } ``` Added in v2.0.0 ## Contravariant2 (interface) **Signature** ```ts export interface Contravariant2 { readonly URI: F readonly contramap: (fa: Kind2, f: (b: B) => A) => Kind2 } ``` Added in v2.0.0 ## Contravariant2C (interface) **Signature** ```ts export interface Contravariant2C { readonly URI: F readonly _E: E readonly contramap: (fa: Kind2, f: (b: B) => A) => Kind2 } ``` Added in v2.0.0 ## Contravariant3 (interface) **Signature** ```ts export interface Contravariant3 { readonly URI: F readonly contramap: (fa: Kind3, f: (b: B) => A) => Kind3 } ``` Added in v2.0.0 ## Contravariant3C (interface) **Signature** ```ts export interface Contravariant3C { readonly URI: F readonly _E: E readonly contramap: (fa: Kind3, f: (b: B) => A) => Kind3 } ``` Added in v2.2.0 ## Contravariant4 (interface) **Signature** ```ts export interface Contravariant4 { readonly URI: F readonly contramap: (fa: Kind4, f: (b: B) => A) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Date.ts.md ================================================ --- title: Date.ts nav_order: 23 parent: Modules --- ## Date overview Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [create](#create) - [instances](#instances) - [Eq](#eq) - [Ord](#ord) - [eqDate](#eqdate) - [eqMonth](#eqmonth) - [eqYear](#eqyear) - [utils](#utils) - [now](#now) --- # constructors ## create Returns the current `Date` **Signature** ```ts export declare const create: IO ``` Added in v2.0.0 # instances ## Eq **Signature** ```ts export declare const Eq: E.Eq ``` Added in v2.10.0 ## Ord **Signature** ```ts export declare const Ord: O.Ord ``` **Example** ```ts import { Ord } from 'fp-ts/Date' assert.deepStrictEqual(Ord.compare(new Date(1, 1, 2020), new Date(1, 1, 2021)), -1) ``` Added in v2.10.0 ## eqDate **Signature** ```ts export declare const eqDate: E.Eq ``` Added in v2.6.0 ## eqMonth **Signature** ```ts export declare const eqMonth: E.Eq ``` Added in v2.6.0 ## eqYear **Signature** ```ts export declare const eqYear: E.Eq ``` Added in v2.6.0 # utils ## now Returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC **Signature** ```ts export declare const now: IO ``` Added in v2.0.0 ================================================ FILE: docs/modules/DistributiveLattice.ts.md ================================================ --- title: DistributiveLattice.ts nav_order: 24 parent: Modules --- ## DistributiveLattice overview A `DistributiveLattice` must satisfy the following laws in addition to `Lattice` laws: - Distributivity for meet: `a ∨ (b ∧ c) <-> (a ∨ b) ∧ (a ∨ c)` - Distributivity for join: `a ∧ (b ∨ c) <-> (a ∧ b) ∨ (a ∧ c)` Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [getMinMaxDistributiveLattice](#getminmaxdistributivelattice) - [model](#model) - [DistributiveLattice (interface)](#distributivelattice-interface) --- # constructors ## getMinMaxDistributiveLattice **Signature** ```ts export declare function getMinMaxDistributiveLattice
(O: Ord): DistributiveLattice ``` Added in v2.0.0 # model ## DistributiveLattice (interface) **Signature** ```ts export interface DistributiveLattice extends Lattice {} ``` Added in v2.0.0 ================================================ FILE: docs/modules/Either.ts.md ================================================ --- title: Either.ts nav_order: 25 parent: Modules --- ## Either overview ```ts type Either = Left | Right ``` Represents a value of one of two possible types (a disjoint union). An instance of `Either` is either an instance of `Left` or `Right`. A common use of `Either` is as an alternative to `Option` for dealing with possible missing values. In this usage, `None` is replaced with a `Left` which can contain useful information. `Right` takes the place of `Some`. Convention dictates that `Left` is used for failure and `Right` is used for success. **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' const double = (n: number): number => n * 2 export const imperative = (as: ReadonlyArray): string => { const head = (as: ReadonlyArray): number => { if (as.length === 0) { throw new Error('empty array') } return as[0] } const inverse = (n: number): number => { if (n === 0) { throw new Error('cannot divide by zero') } return 1 / n } try { return `Result is ${inverse(double(head(as)))}` } catch (err: any) { return `Error is ${err.message}` } } export const functional = (as: ReadonlyArray): string => { const head = (as: ReadonlyArray): E.Either => as.length === 0 ? E.left('empty array') : E.right(as[0]) const inverse = (n: number): E.Either => (n === 0 ? E.left('cannot divide by zero') : E.right(1 / n)) return pipe( as, head, E.map(double), E.flatMap(inverse), E.match( (err) => `Error is ${err}`, // onLeft handler (head) => `Result is ${head}` // onRight handler ) ) } assert.deepStrictEqual(imperative([1, 2, 3]), functional([1, 2, 3])) assert.deepStrictEqual(imperative([]), functional([])) assert.deepStrictEqual(imperative([0]), functional([0])) ``` Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [constructors](#constructors) - [left](#left) - [of](#of) - [right](#right) - [conversions](#conversions) - [fromNullable](#fromnullable) - [fromOption](#fromoption) - [toUnion](#tounion) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getAltValidation](#getaltvalidation) - [getApplicativeValidation](#getapplicativevalidation) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [mapLeft](#mapleft) - [orElse](#orelse) - [orElseW](#orelsew) - [filtering](#filtering) - [filterOrElse](#filterorelse) - [filterOrElseW](#filterorelsew) - [getCompactable](#getcompactable) - [getFilterable](#getfilterable) - [getWitherable](#getwitherable) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Alt](#alt) - [Applicative](#applicative) - [Apply](#apply) - [Bifunctor](#bifunctor) - [Chain](#chain) - [ChainRec](#chainrec) - [Extend](#extend) - [Foldable](#foldable) - [FromEither](#fromeither) - [Functor](#functor) - [Monad](#monad) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [Traversable](#traversable) - [getEq](#geteq) - [getSemigroup](#getsemigroup) - [getShow](#getshow) - [interop](#interop) - [tryCatch](#trycatch) - [tryCatchK](#trycatchk) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstW](#chainfirstw) - [chainNullableK](#chainnullablek) - [chainOptionK](#chainoptionk) - [chainOptionKW](#chainoptionkw) - [chainW](#chainw) - [fromNullableK](#fromnullablek) - [fromOptionK](#fromoptionk) - [lifting](#lifting) - [fromPredicate](#frompredicate) - [liftNullable](#liftnullable) - [liftOption](#liftoption) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [model](#model) - [Either (type alias)](#either-type-alias) - [Left (interface)](#left-interface) - [Right (interface)](#right-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchW](#matchw) - [refinements](#refinements) - [isLeft](#isleft) - [isRight](#isright) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapNullable](#flatmapnullable) - [flatMapOption](#flatmapoption) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequence](#sequence) - [sequenceArray](#sequencearray) - [traverse](#traverse) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [duplicate](#duplicate) - [elem](#elem) - [exists](#exists) - [extend](#extend) - [swap](#swap) - [throwError](#throwerror) - [toError](#toerror) - [zone of death](#zone-of-death) - [~~JsonArray~~ (interface)](#jsonarray-interface) - [~~JsonRecord~~ (interface)](#jsonrecord-interface) - [~~Json~~ (type alias)](#json-type-alias) - [~~either~~](#either) - [~~getApplyMonoid~~](#getapplymonoid) - [~~getApplySemigroup~~](#getapplysemigroup) - [~~getValidationMonoid~~](#getvalidationmonoid) - [~~getValidationSemigroup~~](#getvalidationsemigroup) - [~~getValidation~~](#getvalidation) - [~~parseJSON~~](#parsejson) - [~~stringifyJSON~~](#stringifyjson) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: Either, f: (a: A) => Either): Either (f: (a: A) => Either): (self: Either) => Either } ``` Added in v2.15.0 # constructors ## left Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this structure. **Signature** ```ts export declare const left: (e: E) => Either ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => Either ``` Added in v2.7.0 ## right Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias of this structure. **Signature** ```ts export declare const right: (a: A) => Either ``` Added in v2.0.0 # conversions ## fromNullable Takes a default and a nullable value, if the value is not nully, turn it into a `Right`, if the value is nully use the provided default as a `Left`. **Signature** ```ts export declare const fromNullable: (e: E) =>
(a: A) => Either> ``` **Example** ```ts import { fromNullable, left, right } from 'fp-ts/Either' const parse = fromNullable('nully') assert.deepStrictEqual(parse(1), right(1)) assert.deepStrictEqual(parse(null), left('nully')) ``` Added in v2.0.0 ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option) => Either ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as O from 'fp-ts/Option' assert.deepStrictEqual( pipe( O.some(1), E.fromOption(() => 'error') ), E.right(1) ) assert.deepStrictEqual( pipe( O.none, E.fromOption(() => 'error') ), E.left('error') ) ``` Added in v2.0.0 ## toUnion **Signature** ```ts export declare const toUnion: (fa: Either) => E | A ``` Added in v2.10.0 # do notation ## Do **Signature** ```ts export declare const Do: Either ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: Either ) => (fa: Either) => Either ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: Either ) => (fa: Either) => Either ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => Either ) => (ma: Either) => Either ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: Either) => Either ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => Either ) => (fa: Either) => Either ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: Either) => Either ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. In case of `Either` returns the left-most non-`Left` value (or the right-most `Left` value if both values are `Left`). | x | y | pipe(x, alt(() => y) | | -------- | -------- | -------------------- | | left(a) | left(b) | left(b) | | left(a) | right(2) | right(2) | | right(1) | left(b) | right(1) | | right(1) | right(2) | right(1) | **Signature** ```ts export declare const alt: (that: LazyArg>) => (fa: Either) => Either ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( E.left('a'), E.alt(() => E.left('b')) ), E.left('b') ) assert.deepStrictEqual( pipe( E.left('a'), E.alt(() => E.right(2)) ), E.right(2) ) assert.deepStrictEqual( pipe( E.right(1), E.alt(() => E.left('b')) ), E.right(1) ) assert.deepStrictEqual( pipe( E.right(1), E.alt(() => E.right(2)) ), E.right(1) ) ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the error and the return types will be merged. **Signature** ```ts export declare const altW: (that: LazyArg>) => (fa: Either) => Either ``` Added in v2.9.0 ## getAltValidation The default [`Alt`](#alt) instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. **Signature** ```ts export declare const getAltValidation: (SE: Semigroup) => Alt2C<'Either', E> ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as S from 'fp-ts/Semigroup' import * as string from 'fp-ts/string' const parseString = (u: unknown): E.Either => typeof u === 'string' ? E.right(u) : E.left('not a string') const parseNumber = (u: unknown): E.Either => typeof u === 'number' ? E.right(u) : E.left('not a number') const parse = (u: unknown): E.Either => pipe( parseString(u), E.alt(() => parseNumber(u)) ) assert.deepStrictEqual(parse(true), E.left('not a number')) // <= last error const Alt = E.getAltValidation(pipe(string.Semigroup, S.intercalate(', '))) const parseAll = (u: unknown): E.Either => Alt.alt(parseString(u), () => parseNumber(u)) assert.deepStrictEqual(parseAll(true), E.left('not a string, not a number')) // <= all errors ``` Added in v2.7.0 ## getApplicativeValidation The default [`Applicative`](#applicative) instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. **Signature** ```ts export declare const getApplicativeValidation: (SE: Semigroup) => Applicative2C<'Either', E> ``` **Example** ```ts import * as A from 'fp-ts/Apply' import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as S from 'fp-ts/Semigroup' import * as string from 'fp-ts/string' const parseString = (u: unknown): E.Either => typeof u === 'string' ? E.right(u) : E.left('not a string') const parseNumber = (u: unknown): E.Either => typeof u === 'number' ? E.right(u) : E.left('not a number') interface Person { readonly name: string readonly age: number } const parsePerson = (input: Record): E.Either => pipe(E.Do, E.apS('name', parseString(input.name)), E.apS('age', parseNumber(input.age))) assert.deepStrictEqual(parsePerson({}), E.left('not a string')) // <= first error const Applicative = E.getApplicativeValidation(pipe(string.Semigroup, S.intercalate(', '))) const apS = A.apS(Applicative) const parsePersonAll = (input: Record): E.Either => pipe(E.Do, apS('name', parseString(input.name)), apS('age', parseNumber(input.age))) assert.deepStrictEqual(parsePersonAll({}), E.left('not a string, not a number')) // <= all errors ``` Added in v2.7.0 ## getOrElse Returns the wrapped value if it's a `Right` or a default value if is a `Left`. **Signature** ```ts export declare const getOrElse: (onLeft: (e: E) => A) => (ma: Either) => A ``` **Example** ```ts import { getOrElse, left, right } from 'fp-ts/Either' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( right(1), getOrElse(() => 0) ), 1 ) assert.deepStrictEqual( pipe( left('error'), getOrElse(() => 0) ), 0 ) ``` Added in v2.0.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: (onLeft: (e: E) => B) => (ma: Either) => B | A ``` Added in v2.6.0 ## mapLeft Map a function over the first type argument of a bifunctor. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: Either) => Either ``` Added in v2.0.0 ## orElse Useful for recovering from errors. **Signature** ```ts export declare const orElse: (onLeft: (e: E1) => Either) => (ma: Either) => Either ``` Added in v2.0.0 ## orElseW Less strict version of [`orElse`](#orelse). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const orElseW: ( onLeft: (e: E1) => Either ) => (ma: Either) => Either ``` Added in v2.10.0 # filtering ## filterOrElse **Signature** ```ts export declare const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (self: Either) => Either (predicate: Predicate, onFalse: (a: A) => E): (self: Either) => Either (predicate: Predicate, onFalse: (a: A) => E): (self: Either) => Either } ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( E.right(1), E.filterOrElse( (n) => n > 0, () => 'error' ) ), E.right(1) ) assert.deepStrictEqual( pipe( E.right(-1), E.filterOrElse( (n) => n > 0, () => 'error' ) ), E.left('error') ) assert.deepStrictEqual( pipe( E.left('a'), E.filterOrElse( (n) => n > 0, () => 'error' ) ), E.left('a') ) ``` Added in v2.0.0 ## filterOrElseW Less strict version of [`filterOrElse`](#filterorelse). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: Either ) => Either (predicate: Predicate, onFalse: (a: A) => E2): (mb: Either) => Either (predicate: Predicate, onFalse: (a: A) => E2): (ma: Either) => Either } ``` Added in v2.9.0 ## getCompactable Builds a `Compactable` instance for `Either` given `Monoid` for the left side. **Signature** ```ts export declare const getCompactable: (M: Monoid) => Compactable2C<'Either', E> ``` Added in v2.10.0 ## getFilterable Builds a `Filterable` instance for `Either` given `Monoid` for the left side **Signature** ```ts export declare const getFilterable: (M: Monoid) => Filterable2C<'Either', E> ``` Added in v2.10.0 ## getWitherable Builds `Witherable` instance for `Either` given `Monoid` for the left side **Signature** ```ts export declare const getWitherable: (M: Monoid) => Witherable2C<'Either', E> ``` Added in v2.0.0 # folding ## foldMap Map each element of the structure to a monoid, and combine the results. **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Either) => M ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as E from 'fp-ts/Either' import * as S from 'fp-ts/string' const yell = (a: string) => `${a}!` assert.deepStrictEqual(pipe(E.right('a'), E.foldMap(S.Monoid)(yell)), 'a!') assert.deepStrictEqual(pipe(E.left('e'), E.foldMap(S.Monoid)(yell)), S.Monoid.empty) ``` Added in v2.0.0 ## reduce Left-associative fold of a structure. **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Either) => B ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as E from 'fp-ts/Either' const startWith = 'prefix' const concat = (a: string, b: string) => `${a}:${b}` assert.deepStrictEqual(pipe(E.right('a'), E.reduce(startWith, concat)), 'prefix:a') assert.deepStrictEqual(pipe(E.left('e'), E.reduce(startWith, concat)), 'prefix') ``` Added in v2.0.0 ## reduceRight Right-associative fold of a structure. **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Either) => B ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as E from 'fp-ts/Either' const startWith = 'postfix' const concat = (a: string, b: string) => `${a}:${b}` assert.deepStrictEqual(pipe(E.right('a'), E.reduceRight(startWith, concat)), 'a:postfix') assert.deepStrictEqual(pipe(E.left('e'), E.reduceRight(startWith, concat)), 'postfix') ``` Added in v2.0.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt2<'Either'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative2<'Either'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply2<'Either'> ``` Added in v2.10.0 ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'Either'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'Either'> ``` Added in v2.10.0 ## ChainRec **Signature** ```ts export declare const ChainRec: ChainRec2<'Either'> ``` Added in v2.7.0 ## Extend **Signature** ```ts export declare const Extend: Extend2<'Either'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable2<'Either'> ``` Added in v2.7.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither2<'Either'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Either'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'Either'> ``` Added in v2.7.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow2<'Either'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'Either'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable2<'Either'> ``` Added in v2.7.0 ## getEq **Signature** ```ts export declare const getEq: (EL: Eq, EA: Eq) => Eq> ``` Added in v2.0.0 ## getSemigroup Semigroup returning the left-most non-`Left` value. If both operands are `Right`s then the inner values are concatenated using the provided `Semigroup` **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` **Example** ```ts import { getSemigroup, left, right } from 'fp-ts/Either' import { SemigroupSum } from 'fp-ts/number' const S = getSemigroup(SemigroupSum) assert.deepStrictEqual(S.concat(left('a'), left('b')), left('a')) assert.deepStrictEqual(S.concat(left('a'), right(2)), right(2)) assert.deepStrictEqual(S.concat(right(1), left('b')), right(1)) assert.deepStrictEqual(S.concat(right(1), right(2)), right(3)) ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare const getShow: (SE: Show, SA: Show) => Show> ``` Added in v2.0.0 # interop ## tryCatch Constructs a new `Either` from a function that might throw. See also [`tryCatchK`](#trycatchk). **Signature** ```ts export declare const tryCatch: (f: LazyArg, onThrow: (e: unknown) => E) => Either ``` **Example** ```ts import * as E from 'fp-ts/Either' const unsafeHead = (as: ReadonlyArray): A => { if (as.length > 0) { return as[0] } else { throw new Error('empty array') } } const head = (as: ReadonlyArray): E.Either => E.tryCatch( () => unsafeHead(as), (e) => (e instanceof Error ? e : new Error('unknown error')) ) assert.deepStrictEqual(head([]), E.left(new Error('empty array'))) assert.deepStrictEqual(head([1, 2, 3]), E.right(1)) ``` Added in v2.0.0 ## tryCatchK Converts a function that may throw to one returning a `Either`. **Signature** ```ts export declare const tryCatchK: ( f: (...a: A) => B, onThrow: (error: unknown) => E ) => (...a: A) => Either ``` Added in v2.10.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => Either) => (ma: Either) => Either ``` Added in v2.0.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => Either) => (ma: Either) => Either ``` Added in v2.0.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => Either ) => (ma: Either) => Either ``` Added in v2.8.0 ## chainNullableK Use `flatMapNullable`. **Signature** ```ts export declare const chainNullableK: ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: Either) => Either> ``` Added in v2.9.0 ## chainOptionK Use `flatMapOption`. **Signature** ```ts export declare const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: Either) => Either ``` Added in v2.11.0 ## chainOptionKW Use `flatMapOption`. **Signature** ```ts export declare const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: Either) => Either ``` Added in v2.13.2 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: (f: (a: A) => Either) => (ma: Either) => Either ``` Added in v2.6.0 ## fromNullableK Use `liftNullable`. **Signature** ```ts export declare const fromNullableK: ( e: E ) => (f: (...a: A) => B | null | undefined) => (...a: A) => Either> ``` Added in v2.9.0 ## fromOptionK Use `liftOption`. **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => Either ``` Added in v2.10.0 # lifting ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Either (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Either (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Either } ``` **Example** ```ts import { fromPredicate, left, right } from 'fp-ts/Either' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( 1, fromPredicate( (n) => n > 0, () => 'error' ) ), right(1) ) assert.deepStrictEqual( pipe( -1, fromPredicate( (n) => n > 0, () => 'error' ) ), left('error') ) ``` Added in v2.0.0 ## liftNullable **Signature** ```ts export declare const liftNullable: ( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => Either> ``` Added in v2.15.0 ## liftOption **Signature** ```ts export declare const liftOption: ( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => Either ``` Added in v2.15.0 # mapping ## as Maps the `Right` value of this `Either` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: Either) => Either (self: Either, a: A): Either } ``` Added in v2.16.0 ## asUnit Maps the `Right` value of this `Either` to the void constant value. **Signature** ```ts export declare const asUnit: (self: Either) => Either ``` Added in v2.16.0 ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Either) => Either ``` Added in v2.0.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Either B>) => Either ``` Added in v2.10.0 ## map **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Either) => Either ``` Added in v2.0.0 # model ## Either (type alias) **Signature** ```ts export type Either = Left | Right ``` Added in v2.0.0 ## Left (interface) **Signature** ```ts export interface Left { readonly _tag: 'Left' readonly left: E } ``` Added in v2.0.0 ## Right (interface) **Signature** ```ts export interface Right { readonly _tag: 'Right' readonly right: A } ``` Added in v2.0.0 # pattern matching ## fold Alias of [`match`](#match). **Signature** ```ts export declare const fold: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Either) => B ``` Added in v2.0.0 ## foldW Alias of [`matchW`](#matchw). **Signature** ```ts export declare const foldW: (onLeft: (e: E) => B, onRight: (a: A) => C) => (ma: Either) => B | C ``` Added in v2.10.0 ## match Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the first function, if the value is a `Right` the inner value is applied to the second function. **Signature** ```ts export declare const match: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Either) => B ``` **Example** ```ts import { match, left, right } from 'fp-ts/Either' import { pipe } from 'fp-ts/function' function onLeft(errors: Array): string { return `Errors: ${errors.join(', ')}` } function onRight(value: number): string { return `Ok: ${value}` } assert.strictEqual(pipe(right(1), match(onLeft, onRight)), 'Ok: 1') assert.strictEqual(pipe(left(['error 1', 'error 2']), match(onLeft, onRight)), 'Errors: error 1, error 2') ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: (onLeft: (e: E) => B, onRight: (a: A) => C) => (ma: Either) => B | C ``` Added in v2.10.0 # refinements ## isLeft Returns `true` if the either is an instance of `Left`, `false` otherwise. **Signature** ```ts export declare const isLeft: (ma: Either) => ma is Left ``` Added in v2.0.0 ## isRight Returns `true` if the either is an instance of `Right`, `false` otherwise. **Signature** ```ts export declare const isRight: (ma: Either) => ma is Right ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => Either): (ma: Either) => Either (ma: Either, f: (a: A) => Either): Either } ``` Added in v2.14.0 ## flatMapNullable **Signature** ```ts export declare const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: Either ) => Either> (self: Either, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): Either< E1 | E2, NonNullable > } ``` Added in v2.15.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): (self: Either) => Either (self: Either, f: (a: A) => Option, onNone: (a: A) => E2): Either } ``` Added in v2.15.0 ## flatten The `flatten` function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level. **Signature** ```ts export declare const flatten: (mma: Either>) => Either ``` **Example** ```ts import * as E from 'fp-ts/Either' assert.deepStrictEqual(E.flatten(E.right(E.right('a'))), E.right('a')) assert.deepStrictEqual(E.flatten(E.right(E.left('e'))), E.left('e')) assert.deepStrictEqual(E.flatten(E.left('e')), E.left('e')) ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const flattenW: (mma: Either>) => Either ``` Added in v2.11.0 # traversing ## sequence Evaluate each monadic action in the structure from left to right, and collect the results. **Signature** ```ts export declare const sequence: Sequence2<'Either'> ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as E from 'fp-ts/Either' import * as O from 'fp-ts/Option' assert.deepStrictEqual(pipe(E.right(O.some('a')), E.sequence(O.Applicative)), O.some(E.right('a'))) assert.deepStrictEqual(pipe(E.right(O.none), E.sequence(O.Applicative)), O.none) ``` Added in v2.6.3 ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (as: readonly Either[]) => Either ``` Added in v2.9.0 ## traverse Map each element of a structure to an action, evaluate these actions from left to right, and collect the results. **Signature** ```ts export declare const traverse: PipeableTraverse2<'Either'> ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as RA from 'fp-ts/ReadonlyArray' import * as E from 'fp-ts/Either' import * as O from 'fp-ts/Option' assert.deepStrictEqual(pipe(E.right(['a']), E.traverse(O.Applicative)(RA.head)), O.some(E.right('a'))) assert.deepStrictEqual(pipe(E.right([]), E.traverse(O.Applicative)(RA.head)), O.none) ``` Added in v2.6.3 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => Either ) => (as: readonly A[]) => Either ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => Either ) => (as: readonly A[]) => Either ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => Either ) => (as: readonly A[]) => Either ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => Either ) => (as: ReadonlyNonEmptyArray) => Either> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Either' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: Either ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: Either) => (fab: Either B>) => Either ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: Either) => (first: Either) => Either ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst) The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apFirstW: (second: Either) => (first: Either) => Either ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: Either) => (first: Either) => Either ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond) The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apSecondW: (second: Either) => (first: Either) => Either ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apW: (fa: Either) => (fab: Either B>) => Either ``` Added in v2.8.0 ## duplicate **Signature** ```ts export declare const duplicate: (ma: Either) => Either> ``` Added in v2.0.0 ## elem **Signature** ```ts export declare function elem(E: Eq): { (a: A): (ma: Either) => boolean (a: A, ma: Either): boolean } ``` Added in v2.0.0 ## exists Returns `false` if `Left` or returns the result of the application of the given predicate to the `Right` value. **Signature** ```ts export declare const exists: (predicate: Predicate) => (ma: Either) => boolean ``` **Example** ```ts import { exists, left, right } from 'fp-ts/Either' const gt2 = exists((n: number) => n > 2) assert.strictEqual(gt2(left('a')), false) assert.strictEqual(gt2(right(1)), false) assert.strictEqual(gt2(right(3)), true) ``` Added in v2.0.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: Either) => B) => (wa: Either) => Either ``` Added in v2.0.0 ## swap Returns a `Right` if is a `Left` (and vice versa). **Signature** ```ts export declare const swap: (ma: Either) => Either ``` Added in v2.0.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => Either ``` Added in v2.6.3 ## toError Default value for the `onError` argument of `tryCatch` **Signature** ```ts export declare function toError(e: unknown): Error ``` Added in v2.0.0 # zone of death ## ~~JsonArray~~ (interface) Use [`Json`](./Json.ts.html) module instead. **Signature** ```ts export interface JsonArray extends ReadonlyArray {} ``` Added in v2.6.7 ## ~~JsonRecord~~ (interface) Use [`Json`](./Json.ts.html) module instead. **Signature** ```ts export interface JsonRecord { readonly [key: string]: Json } ``` Added in v2.6.7 ## ~~Json~~ (type alias) Use [`Json`](./Json.ts.html) module instead. **Signature** ```ts export type Json = boolean | number | string | null | JsonArray | JsonRecord ``` Added in v2.6.7 ## ~~either~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `E.Functor` instead of `E.either` (where `E` is from `import E from 'fp-ts/Either'`) **Signature** ```ts export declare const either: Monad2<'Either'> & Foldable2<'Either'> & Traversable2<'Either'> & Bifunctor2<'Either'> & Alt2<'Either'> & Extend2<'Either'> & ChainRec2<'Either'> & MonadThrow2<'Either'> ``` Added in v2.0.0 ## ~~getApplyMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getApplyMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getApplySemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values are concatenated using the provided `Semigroup` **Signature** ```ts export declare const getApplySemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getValidationMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getValidationMonoid: (SE: Semigroup, MA: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getValidationSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getValidationSemigroup: (SE: Semigroup, SA: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getValidation~~ Use [`getApplicativeValidation`](#getapplicativevalidation) and [`getAltValidation`](#getaltvalidation) instead. **Signature** ```ts export declare function getValidation( SE: Semigroup ): Monad2C & Foldable2 & Traversable2 & Bifunctor2 & Alt2C & Extend2 & ChainRec2C & MonadThrow2C ``` Added in v2.0.0 ## ~~parseJSON~~ Use [`parse`](./Json.ts.html#parse) instead. **Signature** ```ts export declare function parseJSON(s: string, onError: (reason: unknown) => E): Either ``` Added in v2.0.0 ## ~~stringifyJSON~~ Use [`stringify`](./Json.ts.html#stringify) instead. **Signature** ```ts export declare const stringifyJSON: (u: unknown, onError: (reason: unknown) => E) => Either ``` Added in v2.0.0 ================================================ FILE: docs/modules/EitherT.ts.md ================================================ --- title: EitherT.ts nav_order: 26 parent: Modules --- ## EitherT overview The error monad transformer. It can be used to add error handling to other monads. The `of` function yields a successful computation, while `chain` sequences two subcomputations, failing on the first error. Added in v2.0.0 ---

Table of contents

- [error handling](#error-handling) - [altValidation](#altvalidation) - [orElseFirst](#orelsefirst) - [orLeft](#orleft) - [pattern matching](#pattern-matching) - [match](#match) - [utils](#utils) - [alt](#alt) - [ap](#ap) - [bimap](#bimap) - [chain](#chain) - [chainNullableK](#chainnullablek) - [fromNullable](#fromnullable) - [fromNullableK](#fromnullablek) - [getOrElse](#getorelse) - [left](#left) - [leftF](#leftf) - [map](#map) - [mapLeft](#mapleft) - [matchE](#matche) - [orElse](#orelse) - [right](#right) - [rightF](#rightf) - [swap](#swap) - [toUnion](#tounion) - [zone of death](#zone-of-death) - [~~EitherM1~~ (interface)](#eitherm1-interface) - [~~EitherM2~~ (interface)](#eitherm2-interface) - [~~EitherM~~ (interface)](#eitherm-interface) - [~~EitherT1~~ (type alias)](#eithert1-type-alias) - [~~EitherT2~~ (type alias)](#eithert2-type-alias) - [~~EitherT~~ (interface)](#eithert-interface) - [~~getEitherM~~](#geteitherm) --- # error handling ## altValidation **Signature** ```ts export declare function altValidation( M: Monad3, S: Semigroup ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export declare function altValidation( M: Monad3C, S: Semigroup ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export declare function altValidation( M: Monad2, S: Semigroup ): ( second: LazyArg>> ) => (first: Kind2>) => Kind2> export declare function altValidation( M: Monad2C, S: Semigroup ):
(second: LazyArg>>) => (first: Kind2>) => Kind2> export declare function altValidation( M: Monad1, S: Semigroup ): (second: LazyArg>>) => (first: Kind>) => Kind> export declare function altValidation( M: Monad, S: Semigroup ): (second: LazyArg>>) => (first: HKT>) => HKT> ``` Added in v2.10.0 ## orElseFirst **Signature** ```ts export declare function orElseFirst( M: Monad3 ): ( onLeft: (e: E) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function orElseFirst( M: Monad3C ): ( onLeft: (e: E) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function orElseFirst( M: Monad2 ): ( onLeft: (e: E) => Kind2> ) => (ma: Kind2>) => Kind2> export declare function orElseFirst( M: Monad2C ): ( onLeft: (e: E) => Kind2> ) => (ma: Kind2>) => Kind2> export declare function orElseFirst( M: Monad1 ): (onLeft: (e: E) => Kind>) => (ma: Kind>) => Kind> export declare function orElseFirst( M: Monad ): (onLeft: (e: E) => HKT>) => (ma: HKT>) => HKT> ``` Added in v2.11.0 ## orLeft **Signature** ```ts export declare function orLeft( M: Monad3 ): ( onLeft: (e: E1) => Kind3 ) => (fa: Kind3>) => Kind3> export declare function orLeft( M: Monad3C ): ( onLeft: (e: E1) => Kind3 ) => (fa: Kind3>) => Kind3> export declare function orLeft( M: Monad2 ): ( onLeft: (e: E1) => Kind2 ) => (fa: Kind2>) => Kind2> export declare function orLeft( M: Monad2C ): (onLeft: (e: E1) => Kind2) => (fa: Kind2>) => Kind2> export declare function orLeft( M: Monad1 ): (onLeft: (e: E1) => Kind) => (fa: Kind>) => Kind> export declare function orLeft( M: Monad ): (onLeft: (e: E1) => HKT) => (fa: HKT>) => HKT> ``` Added in v2.11.0 # pattern matching ## match **Signature** ```ts export declare function match( F: Functor3 ): ( onLeft: (e: E) => B, onRight: (a: A) => B ) => (ma: Kind3>) => Kind3 export declare function match( F: Functor3C ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind3>) => Kind3 export declare function match( F: Functor2 ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind2>) => Kind2 export declare function match( F: Functor2C ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind2>) => Kind2 export declare function match( F: Functor1 ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind>) => Kind export declare function match( F: Functor ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: HKT>) => HKT ``` Added in v2.11.0 # utils ## alt **Signature** ```ts export declare function alt( M: Monad3 ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export declare function alt( M: Monad3C ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export declare function alt( M: Monad2 ): ( second: LazyArg>> ) => (first: Kind2>) => Kind2> export declare function alt( M: Monad2C ): ( second: LazyArg>> ) => (first: Kind2>) => Kind2> export declare function alt( M: Monad1 ): (second: LazyArg>>) => (first: Kind>) => Kind> export declare function alt( M: Monad ): (second: LazyArg>>) => (first: HKT>) => HKT> ``` Added in v2.10.0 ## ap **Signature** ```ts export declare function ap( F: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply2 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply1 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> ``` Added in v2.10.0 ## bimap **Signature** ```ts export declare function bimap( F: Functor3 ): ( f: (e: E) => G, g: (a: A) => B ) => (self: Kind3>) => Kind3> export declare function bimap( F: Functor3C ): ( f: (e: E) => G, g: (a: A) => B ) => (self: Kind3>) => Kind3> export declare function bimap( F: Functor2 ): (f: (e: E) => G, g: (a: A) => B) => (self: Kind2>) => Kind2> export declare function bimap( F: Functor2C ): (f: (e: E) => G, g: (a: A) => B) => (self: Kind2>) => Kind2> export declare function bimap( F: Functor1 ): (f: (e: E) => G, g: (a: A) => B) => (self: Kind>) => Kind> export declare function bimap( F: Functor ): (f: (e: E) => G, g: (a: A) => B) => (self: HKT>) => HKT> ``` Added in v2.10.0 ## chain **Signature** ```ts export declare function chain( M: Monad3 ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function chain( M: Monad3C ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function chain( M: Monad2 ): ( f: (a: A) => Kind2> ) => (ma: Kind2>) => Kind2> export declare function chain( M: Monad2C ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export declare function chain( M: Monad1 ): (f: (a: A) => Kind>) => (ma: Kind>) => Kind> export declare function chain( M: Monad ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> ``` Added in v2.10.0 ## chainNullableK **Signature** ```ts export declare function chainNullableK( M: Monad3 ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export declare function chainNullableK( M: Monad3C ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export declare function chainNullableK( M: Monad2 ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind2>) => Kind2>> export declare function chainNullableK( M: Monad2C ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind2>) => Kind2>> export declare function chainNullableK( M: Monad1 ): ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: Kind>) => Kind>> export declare function chainNullableK( M: Monad ): ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: HKT>) => HKT>> ``` Added in v2.12.0 ## fromNullable **Signature** ```ts export declare function fromNullable( F: Pointed3 ): (e: E) => (a: A) => Kind3>> export declare function fromNullable( F: Pointed3C ): (e: E) => (a: A) => Kind3>> export declare function fromNullable( F: Pointed2 ): (e: E) => (a: A) => Kind2>> export declare function fromNullable( F: Pointed2C ): (e: E) => (a: A) => Kind2>> export declare function fromNullable( F: Pointed1 ): (e: E) => (a: A) => Kind>> export declare function fromNullable(F: Pointed): (e: E) => (a: A) => HKT>> ``` Added in v2.12.0 ## fromNullableK **Signature** ```ts export declare function fromNullableK( F: Pointed3 ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export declare function fromNullableK( F: Pointed3C ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export declare function fromNullableK( F: Pointed2 ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export declare function fromNullableK( F: Pointed2C ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export declare function fromNullableK( F: Pointed1 ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind>> export declare function fromNullableK( F: Pointed ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => HKT>> ``` Added in v2.12.0 ## getOrElse **Signature** ```ts export declare function getOrElse( M: Monad3 ): (onLeft: (e: E) => Kind3) => (ma: Kind3>) => Kind3 export declare function getOrElse( M: Monad3C ): (onLeft: (e: E) => Kind3) => (ma: Kind3>) => Kind3 export declare function getOrElse( M: Monad2 ): (onLeft: (e: E) => Kind2) => (ma: Kind2>) => Kind2 export declare function getOrElse( M: Monad2C ): (onLeft: (e: E) => Kind2) => (ma: Kind2>) => Kind2 export declare function getOrElse( M: Monad1 ): (onLeft: (e: E) => Kind) => (ma: Kind>) => Kind export declare function getOrElse( M: Monad ): (onLeft: (e: E) => HKT) => (ma: HKT>) => HKT ``` Added in v2.10.0 ## left **Signature** ```ts export declare function left( F: Pointed3 ): (e: E) => Kind3> export declare function left( F: Pointed3C ): (e: E) => Kind3> export declare function left(F: Pointed2): (e: E) => Kind2> export declare function left( F: Pointed2C ): (e: E) => Kind2> export declare function left(F: Pointed1): (e: E) => Kind> export declare function left(F: Pointed): (e: E) => HKT> ``` Added in v2.10.0 ## leftF **Signature** ```ts export declare function leftF( F: Functor3 ): (fe: Kind3) => Kind3> export declare function leftF( F: Functor3C ): (fe: Kind3) => Kind3> export declare function leftF( F: Functor2 ): (fe: Kind2) => Kind2> export declare function leftF( F: Functor2C ): (fe: Kind2) => Kind2> export declare function leftF(F: Functor1): (fe: Kind) => Kind> export declare function leftF(F: Functor): (fe: HKT) => HKT> ``` Added in v2.10.0 ## map **Signature** ```ts export declare function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export declare function map( F: Functor ): (f: (a: A) => B) => (fa: HKT>) => HKT> ``` Added in v2.10.0 ## mapLeft **Signature** ```ts export declare function mapLeft( F: Functor3 ): (f: (e: E) => G) => (self: Kind3>) => Kind3> export declare function mapLeft( F: Functor3C ): (f: (e: E) => G) => (self: Kind3>) => Kind3> export declare function mapLeft( F: Functor2 ): (f: (e: E) => G) => (self: Kind2>) => Kind2> export declare function mapLeft( F: Functor2C ): (f: (e: E) => G) => (self: Kind2>) => Kind2> export declare function mapLeft( F: Functor1 ): (f: (e: E) => G) => (self: Kind>) => Kind> export declare function mapLeft( F: Functor ): (f: (e: E) => G) => (self: HKT>) => HKT> ``` Added in v2.10.0 ## matchE **Signature** ```ts export declare function matchE( M: Chain3 ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export declare function matchE( M: Chain3C ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export declare function matchE( M: Chain2 ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export declare function matchE( M: Chain2C ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export declare function matchE( M: Chain1 ): (onLeft: (e: E) => Kind, onRight: (a: A) => Kind) => (ma: Kind>) => Kind export declare function matchE( M: Chain ): (onLeft: (e: E) => HKT, onRight: (a: A) => HKT) => (ma: HKT>) => HKT ``` Added in v2.10.0 ## orElse **Signature** ```ts export declare function orElse( M: Monad3 ): ( onLeft: (e: E1) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function orElse( M: Monad3C ): ( onLeft: (e: E1) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function orElse( M: Monad2 ): ( onLeft: (e: E1) => Kind2> ) => (ma: Kind2>) => Kind2> export declare function orElse( M: Monad2C ): ( onLeft: (e: E1) => Kind2> ) => (ma: Kind2>) => Kind2> export declare function orElse( M: Monad1 ): (onLeft: (e: E1) => Kind>) => (ma: Kind>) => Kind> export declare function orElse( M: Monad ): (onLeft: (e: E1) => HKT>) => (ma: HKT>) => HKT> ``` Added in v2.10.0 ## right **Signature** ```ts export declare function right( F: Pointed3 ): (a: A) => Kind3> export declare function right( F: Pointed3C ): (a: A) => Kind3> export declare function right(F: Pointed2): (a: A) => Kind2> export declare function right( F: Pointed2C ): (a: A) => Kind2> export declare function right(F: Pointed1): (a: A) => Kind> export declare function right(F: Pointed): (a: A) => HKT> ``` Added in v2.10.0 ## rightF **Signature** ```ts export declare function rightF( F: Functor3 ): (fa: Kind3) => Kind3> export declare function rightF( F: Functor3C ): (fa: Kind3) => Kind3> export declare function rightF( F: Functor2 ): (fa: Kind2) => Kind2> export declare function rightF( F: Functor2C ): (fa: Kind2) => Kind2> export declare function rightF(F: Functor1): (fa: Kind) => Kind> export declare function rightF(F: Functor): (fa: HKT) => HKT> ``` Added in v2.10.0 ## swap **Signature** ```ts export declare function swap( F: Functor3 ): (ma: Kind3>) => Kind3> export declare function swap( F: Functor3C ): (ma: Kind3>) => Kind3> export declare function swap( F: Functor2 ): (ma: Kind2>) => Kind2> export declare function swap( F: Functor2C ): (ma: Kind2>) => Kind2> export declare function swap(F: Functor1): (ma: Kind>) => Kind> export declare function swap(F: Functor): (ma: HKT>) => HKT> ``` Added in v2.10.0 ## toUnion **Signature** ```ts export declare function toUnion( F: Functor3 ): (fa: Kind3>) => Kind3 export declare function toUnion( F: Functor3C ): (fa: Kind3>) => Kind3 export declare function toUnion( F: Functor2 ): (fa: Kind2>) => Kind2 export declare function toUnion( F: Functor2C ): (fa: Kind2>) => Kind2 export declare function toUnion(F: Functor1): (fa: Kind>) => Kind export declare function toUnion(F: Functor): (fa: HKT>) => HKT ``` Added in v2.10.0 # zone of death ## ~~EitherM1~~ (interface) **Signature** ```ts export interface EitherM1 extends ApplicativeComposition12 { readonly chain: (ma: EitherT1, f: (a: A) => EitherT1) => EitherT1 readonly alt: (fa: EitherT1, that: LazyArg>) => EitherT1 readonly bimap: (ma: EitherT1, f: (e: E) => N, g: (a: A) => B) => EitherT1 readonly mapLeft: (ma: EitherT1, f: (e: E) => N) => EitherT1 readonly fold: ( ma: EitherT1, onLeft: (e: E) => Kind, onRight: (a: A) => Kind ) => Kind readonly getOrElse: (ma: EitherT1, onLeft: (e: E) => Kind) => Kind readonly orElse: (ma: EitherT1, onLeft: (e: E) => EitherT1) => EitherT1 readonly swap: (ma: EitherT1) => EitherT1 readonly rightM: (ma: Kind) => EitherT1 readonly leftM: (me: Kind) => EitherT1 readonly left: (e: E) => EitherT1 } ``` Added in v2.0.0 ## ~~EitherM2~~ (interface) **Signature** ```ts export interface EitherM2 extends ApplicativeComposition22 { readonly chain: (ma: EitherT2, f: (a: A) => EitherT2) => EitherT2 readonly alt: (fa: EitherT2, that: LazyArg>) => EitherT2 readonly bimap: (ma: EitherT2, f: (e: E) => N, g: (a: A) => B) => EitherT2 readonly mapLeft: (ma: EitherT2, f: (e: E) => N) => EitherT2 readonly fold: ( ma: EitherT2, onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2 ) => Kind2 readonly getOrElse: (ma: EitherT2, onLeft: (e: E) => Kind2) => Kind2 readonly orElse: ( ma: EitherT2, onLeft: (e: E) => EitherT2 ) => EitherT2 readonly swap: (ma: EitherT2) => EitherT2 readonly rightM: (ma: Kind2) => EitherT2 readonly leftM: (me: Kind2) => EitherT2 readonly left: (e: E) => EitherT2 } ``` Added in v2.0.0 ## ~~EitherM~~ (interface) **Signature** ```ts export interface EitherM extends ApplicativeCompositionHKT2 { readonly chain: (ma: EitherT, f: (a: A) => EitherT) => EitherT readonly alt: (fa: EitherT, that: LazyArg>) => EitherT readonly bimap: (ma: EitherT, f: (e: E) => N, g: (a: A) => B) => EitherT readonly mapLeft: (ma: EitherT, f: (e: E) => N) => EitherT readonly fold: (ma: EitherT, onLeft: (e: E) => HKT, onRight: (a: A) => HKT) => HKT readonly getOrElse: (ma: EitherT, onLeft: (e: E) => HKT) => HKT readonly orElse: (ma: EitherT, onLeft: (e: E) => EitherT) => EitherT readonly swap: (ma: EitherT) => EitherT readonly rightM: (ma: HKT) => EitherT readonly leftM: (me: HKT) => EitherT readonly left: (e: E) => EitherT } ``` Added in v2.0.0 ## ~~EitherT1~~ (type alias) **Signature** ```ts export type EitherT1 = Kind> ``` Added in v2.0.0 ## ~~EitherT2~~ (type alias) **Signature** ```ts export type EitherT2 = Kind2> ``` Added in v2.0.0 ## ~~EitherT~~ (interface) **Signature** ```ts export interface EitherT extends HKT> {} ``` Added in v2.0.0 ## ~~getEitherM~~ **Signature** ```ts export declare function getEitherM(M: Monad2): EitherM2 export declare function getEitherM(M: Monad1): EitherM1 export declare function getEitherM(M: Monad): EitherM ``` Added in v2.0.0 ================================================ FILE: docs/modules/Endomorphism.ts.md ================================================ --- title: Endomorphism.ts nav_order: 27 parent: Modules --- ## Endomorphism overview Added in v2.11.0 ---

Table of contents

- [instances](#instances) - [getMonoid](#getmonoid) - [getSemigroup](#getsemigroup) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [Endomorphism (interface)](#endomorphism-interface) --- # instances ## getMonoid Endomorphism form a `Monoid` where the `empty` value is the `identity` function. **Signature** ```ts export declare const getMonoid:
() => Monoid> ``` Added in v2.11.0 ## getSemigroup Endomorphism form a `Semigroup` where the `concat` operation is the usual function composition. **Signature** ```ts export declare const getSemigroup: () => Semigroup> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Endomorphism' ``` Added in v2.11.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.11.0 # utils ## Endomorphism (interface) **Signature** ```ts export interface Endomorphism { (a: A): A } ``` Added in v2.11.0 ================================================ FILE: docs/modules/Eq.ts.md ================================================ --- title: Eq.ts nav_order: 28 parent: Modules --- ## Eq overview The `Eq` type class represents types which support decidable equality. Instances must satisfy the following laws: 1. Reflexivity: `E.equals(a, a) === true` 2. Symmetry: `E.equals(a, b) === E.equals(b, a)` 3. Transitivity: if `E.equals(a, b) === true` and `E.equals(b, c) === true`, then `E.equals(a, c) === true` Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [fromEquals](#fromequals) - [instances](#instances) - [Contravariant](#contravariant) - [eqStrict](#eqstrict) - [getMonoid](#getmonoid) - [getSemigroup](#getsemigroup) - [model](#model) - [Eq (interface)](#eq-interface) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [contramap](#contramap) - [struct](#struct) - [tuple](#tuple) - [zone of death](#zone-of-death) - [~~eqBoolean~~](#eqboolean) - [~~eqDate~~](#eqdate) - [~~eqNumber~~](#eqnumber) - [~~eqString~~](#eqstring) - [~~eq~~](#eq) - [~~getStructEq~~](#getstructeq) - [~~getTupleEq~~](#gettupleeq) - [~~strictEqual~~](#strictequal) --- # constructors ## fromEquals **Signature** ```ts export declare const fromEquals:
(equals: (x: A, y: A) => boolean) => Eq ``` Added in v2.0.0 # instances ## Contravariant **Signature** ```ts export declare const Contravariant: Contravariant1<'Eq'> ``` Added in v2.7.0 ## eqStrict **Signature** ```ts export declare const eqStrict: Eq ``` Added in v2.5.0 ## getMonoid **Signature** ```ts export declare const getMonoid: () => Monoid> ``` Added in v2.6.0 ## getSemigroup **Signature** ```ts export declare const getSemigroup: () => Semigroup> ``` Added in v2.10.0 # model ## Eq (interface) **Signature** ```ts export interface Eq { readonly equals: (x: A, y: A) => boolean } ``` Added in v2.0.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Eq' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## contramap A typical use case for `contramap` would be like, given some `User` type, to construct an `Eq`. We can do so with a function from `User -> X` where `X` is some value that we know how to compare for equality (meaning we have an `Eq`) For example, given the following `User` type, we want to construct an `Eq` that just looks at the `key` field for each user (since it's known to be unique). If we have a way of comparing `UUID`s for equality (`eqUUID: Eq`) and we know how to go from `User -> UUID`, using `contramap` we can do this **Signature** ```ts export declare const contramap: (f: (b: B) => A) => (fa: Eq) => Eq ``` **Example** ```ts import { contramap, Eq } from 'fp-ts/Eq' import { pipe } from 'fp-ts/function' import * as S from 'fp-ts/string' type UUID = string interface User { readonly key: UUID readonly firstName: string readonly lastName: string } const eqUUID: Eq = S.Eq const eqUserByKey: Eq = pipe( eqUUID, contramap((user) => user.key) ) assert.deepStrictEqual( eqUserByKey.equals({ key: 'k1', firstName: 'a1', lastName: 'b1' }, { key: 'k2', firstName: 'a1', lastName: 'b1' }), false ) assert.deepStrictEqual( eqUserByKey.equals({ key: 'k1', firstName: 'a1', lastName: 'b1' }, { key: 'k1', firstName: 'a2', lastName: 'b1' }), true ) ``` Added in v2.0.0 ## struct **Signature** ```ts export declare const struct: (eqs: { [K in keyof A]: Eq }) => Eq<{ readonly [K in keyof A]: A[K] }> ``` Added in v2.10.0 ## tuple Given a tuple of `Eq`s returns a `Eq` for the tuple **Signature** ```ts export declare const tuple: (...eqs: { [K in keyof A]: Eq }) => Eq> ``` **Example** ```ts import { tuple } from 'fp-ts/Eq' import * as S from 'fp-ts/string' import * as N from 'fp-ts/number' import * as B from 'fp-ts/boolean' const E = tuple(S.Eq, N.Eq, B.Eq) assert.strictEqual(E.equals(['a', 1, true], ['a', 1, true]), true) assert.strictEqual(E.equals(['a', 1, true], ['b', 1, true]), false) assert.strictEqual(E.equals(['a', 1, true], ['a', 2, true]), false) assert.strictEqual(E.equals(['a', 1, true], ['a', 1, false]), false) ``` Added in v2.10.0 # zone of death ## ~~eqBoolean~~ Use [`Eq`](./boolean.ts.html#eq) instead. **Signature** ```ts export declare const eqBoolean: Eq ``` Added in v2.0.0 ## ~~eqDate~~ Use [`Eq`](./Date.ts.html#eq) instead. **Signature** ```ts export declare const eqDate: Eq ``` Added in v2.0.0 ## ~~eqNumber~~ Use [`Eq`](./number.ts.html#eq) instead. **Signature** ```ts export declare const eqNumber: Eq ``` Added in v2.0.0 ## ~~eqString~~ Use [`Eq`](./string.ts.html#eq) instead. **Signature** ```ts export declare const eqString: Eq ``` Added in v2.0.0 ## ~~eq~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Contravariant` instance, pass `E.Contravariant` instead of `E.eq` (where `E` is from `import E from 'fp-ts/Eq'`) **Signature** ```ts export declare const eq: Contravariant1<'Eq'> ``` Added in v2.0.0 ## ~~getStructEq~~ Use [`struct`](#struct) instead. **Signature** ```ts export declare const getStructEq: >>(eqs: { [K in keyof O]: Eq }) => Eq ``` Added in v2.0.0 ## ~~getTupleEq~~ Use [`tuple`](#tuple) instead. **Signature** ```ts export declare const getTupleEq: []>( ...eqs: T ) => Eq<{ [K in keyof T]: T[K] extends Eq ? A : never }> ``` Added in v2.0.0 ## ~~strictEqual~~ Use [`eqStrict`](#eqstrict) instead **Signature** ```ts export declare const strictEqual: (a: A, b: A) => boolean ``` Added in v2.0.0 ================================================ FILE: docs/modules/Extend.ts.md ================================================ --- title: Extend.ts nav_order: 29 parent: Modules --- ## Extend overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Extend (interface)](#extend-interface) - [Extend1 (interface)](#extend1-interface) - [Extend2 (interface)](#extend2-interface) - [Extend2C (interface)](#extend2c-interface) - [Extend3 (interface)](#extend3-interface) - [Extend3C (interface)](#extend3c-interface) - [Extend4 (interface)](#extend4-interface) --- # model ## Extend (interface) **Signature** ```ts export interface Extend extends Functor { readonly extend: (wa: HKT, f: (wa: HKT) => B) => HKT } ``` Added in v2.0.0 ## Extend1 (interface) **Signature** ```ts export interface Extend1 extends Functor1 { readonly extend: (wa: Kind, f: (wa: Kind) => B) => Kind } ``` Added in v2.0.0 ## Extend2 (interface) **Signature** ```ts export interface Extend2 extends Functor2 { readonly extend: (wa: Kind2, f: (wa: Kind2) => B) => Kind2 } ``` Added in v2.0.0 ## Extend2C (interface) **Signature** ```ts export interface Extend2C extends Functor2C { readonly extend: (wa: Kind2, f: (wa: Kind2) => B) => Kind2 } ``` Added in v2.0.0 ## Extend3 (interface) **Signature** ```ts export interface Extend3 extends Functor3 { readonly extend: (wa: Kind3, f: (wa: Kind3) => B) => Kind3 } ``` Added in v2.0.0 ## Extend3C (interface) **Signature** ```ts export interface Extend3C extends Functor3C { readonly extend: (wa: Kind3, f: (wa: Kind3) => B) => Kind3 } ``` Added in v2.2.0 ## Extend4 (interface) **Signature** ```ts export interface Extend4 extends Functor4 { readonly extend: (wa: Kind4, f: (wa: Kind4) => B) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Field.ts.md ================================================ --- title: Field.ts nav_order: 30 parent: Modules --- ## Field overview Adapted from https://github.com/purescript/purescript-prelude/blob/master/src/Data/Field.purs Added in v2.0.0 ---

Table of contents

- [model](#model) - [Field (interface)](#field-interface) - [utils](#utils) - [gcd](#gcd) - [lcm](#lcm) - [zone of death](#zone-of-death) - [~~fieldNumber~~](#fieldnumber) --- # model ## Field (interface) **Signature** ```ts export interface Field
extends Ring { readonly degree: (a: A) => number readonly div: (x: A, y: A) => A readonly mod: (x: A, y: A) => A } ``` Added in v2.0.0 # utils ## gcd The _greatest common divisor_ of two values **Signature** ```ts export declare function gcd(E: Eq, field: Field): (x: A, y: A) => A ``` Added in v2.0.0 ## lcm The _least common multiple_ of two values **Signature** ```ts export declare function lcm(E: Eq, F: Field): (x: A, y: A) => A ``` Added in v2.0.0 # zone of death ## ~~fieldNumber~~ Use [`Field`](./number.ts.html#field) instead. **Signature** ```ts export declare const fieldNumber: Field ``` Added in v2.0.0 ================================================ FILE: docs/modules/Filterable.ts.md ================================================ --- title: Filterable.ts nav_order: 31 parent: Modules --- ## Filterable overview `Filterable` represents data structures which can be _partitioned_/_filtered_. Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Filterable.purs Added in v2.0.0 ---

Table of contents

- [model](#model) - [Filterable (interface)](#filterable-interface) - [Filterable1 (interface)](#filterable1-interface) - [Filterable2 (interface)](#filterable2-interface) - [Filterable2C (interface)](#filterable2c-interface) - [Filterable3 (interface)](#filterable3-interface) - [Filterable3C (interface)](#filterable3c-interface) - [Filterable4 (interface)](#filterable4-interface) - [utils](#utils) - [Filter (interface)](#filter-interface) - [Filter1 (interface)](#filter1-interface) - [Filter2 (interface)](#filter2-interface) - [Filter2C (interface)](#filter2c-interface) - [Filter3 (interface)](#filter3-interface) - [Filter3C (interface)](#filter3c-interface) - [Filter4 (interface)](#filter4-interface) - [Partition (interface)](#partition-interface) - [Partition1 (interface)](#partition1-interface) - [Partition2 (interface)](#partition2-interface) - [Partition2C (interface)](#partition2c-interface) - [Partition3 (interface)](#partition3-interface) - [Partition3C (interface)](#partition3c-interface) - [Partition4 (interface)](#partition4-interface) - [filter](#filter) - [filterMap](#filtermap) - [partition](#partition) - [partitionMap](#partitionmap) - [zone of death](#zone-of-death) - [~~FilterableComposition11~~ (interface)](#filterablecomposition11-interface) - [~~FilterableComposition12C~~ (interface)](#filterablecomposition12c-interface) - [~~FilterableComposition12~~ (interface)](#filterablecomposition12-interface) - [~~FilterableComposition21~~ (interface)](#filterablecomposition21-interface) - [~~FilterableComposition22C~~ (interface)](#filterablecomposition22c-interface) - [~~FilterableComposition22~~ (interface)](#filterablecomposition22-interface) - [~~FilterableComposition23C~~ (interface)](#filterablecomposition23c-interface) - [~~FilterableComposition2C1~~ (interface)](#filterablecomposition2c1-interface) - [~~FilterableComposition~~ (interface)](#filterablecomposition-interface) - [~~getFilterableComposition~~](#getfilterablecomposition) --- # model ## Filterable (interface) **Signature** ```ts export interface Filterable extends Functor, Compactable { /** * Partition a data structure based on an either predicate. */ readonly partitionMap: (fa: HKT, f: (a: A) => Either) => Separated, HKT> /** * Partition a data structure based on a boolean predicate. */ readonly partition: Partition /** * Map over a data structure and filter based on an option predicate. */ readonly filterMap: (fa: HKT, f: (a: A) => Option) => HKT /** * Filter a data structure based on a boolean predicate. */ readonly filter: Filter } ``` Added in v2.0.0 ## Filterable1 (interface) **Signature** ```ts export interface Filterable1 extends Functor1, Compactable1 { readonly partitionMap: (fa: Kind, f: (a: A) => Either) => Separated, Kind> readonly partition: Partition1 readonly filterMap: (fa: Kind, f: (a: A) => Option) => Kind readonly filter: Filter1 } ``` Added in v2.0.0 ## Filterable2 (interface) **Signature** ```ts export interface Filterable2 extends Functor2, Compactable2 { readonly partitionMap: ( fa: Kind2, f: (a: A) => Either ) => Separated, Kind2> readonly partition: Partition2 readonly filterMap: (fa: Kind2, f: (a: A) => Option) => Kind2 readonly filter: Filter2 } ``` Added in v2.0.0 ## Filterable2C (interface) **Signature** ```ts export interface Filterable2C extends Functor2C, Compactable2C { readonly partitionMap: ( fa: Kind2, f: (a: A) => Either ) => Separated, Kind2> readonly partition: Partition2C readonly filterMap: (fa: Kind2, f: (a: A) => Option) => Kind2 readonly filter: Filter2C } ``` Added in v2.0.0 ## Filterable3 (interface) **Signature** ```ts export interface Filterable3 extends Functor3, Compactable3 { readonly partitionMap: ( fa: Kind3, f: (a: A) => Either ) => Separated, Kind3> readonly partition: Partition3 readonly filterMap: (fa: Kind3, f: (a: A) => Option) => Kind3 readonly filter: Filter3 } ``` Added in v2.0.0 ## Filterable3C (interface) **Signature** ```ts export interface Filterable3C extends Functor3C, Compactable3C { readonly partitionMap: ( fa: Kind3, f: (a: A) => Either ) => Separated, Kind3> readonly partition: Partition3C readonly filterMap: (fa: Kind3, f: (a: A) => Option) => Kind3 readonly filter: Filter3C } ``` Added in v2.2.0 ## Filterable4 (interface) **Signature** ```ts export interface Filterable4 extends Functor4, Compactable4 { readonly partitionMap: ( fa: Kind4, f: (a: A) => Either ) => Separated, Kind4> readonly partition: Partition4 readonly filterMap: (fa: Kind4, f: (a: A) => Option) => Kind4 readonly filter: Filter4 } ``` Added in v2.0.0 # utils ## Filter (interface) **Signature** ```ts export interface Filter { (fa: HKT, refinement: Refinement): HKT
(fa: HKT, predicate: Predicate): HKT } ``` Added in v2.0.0 ## Filter1 (interface) **Signature** ```ts export interface Filter1 { (fa: Kind, refinement: Refinement): Kind (fa: Kind, predicate: Predicate): Kind } ``` Added in v2.0.0 ## Filter2 (interface) **Signature** ```ts export interface Filter2 { (fa: Kind2, refinement: Refinement): Kind2 (fa: Kind2, predicate: Predicate): Kind2 } ``` Added in v2.0.0 ## Filter2C (interface) **Signature** ```ts export interface Filter2C { (fa: Kind2, refinement: Refinement): Kind2 (fa: Kind2, predicate: Predicate): Kind2 } ``` Added in v2.0.0 ## Filter3 (interface) **Signature** ```ts export interface Filter3 { (fa: Kind3, refinement: Refinement): Kind3 (fa: Kind3, predicate: Predicate): Kind3 } ``` Added in v2.0.0 ## Filter3C (interface) **Signature** ```ts export interface Filter3C { (fa: Kind3, refinement: Refinement): Kind3 (fa: Kind3, predicate: Predicate): Kind3 } ``` Added in v2.2.0 ## Filter4 (interface) **Signature** ```ts export interface Filter4 { (fa: Kind4, refinement: Refinement): Kind4 (fa: Kind4, predicate: Predicate): Kind4 } ``` Added in v2.0.0 ## Partition (interface) **Signature** ```ts export interface Partition { (fa: HKT, refinement: Refinement): Separated, HKT> (fa: HKT, predicate: Predicate): Separated, HKT> } ``` Added in v2.0.0 ## Partition1 (interface) **Signature** ```ts export interface Partition1 { (fa: Kind, refinement: Refinement): Separated, Kind> (fa: Kind, predicate: Predicate): Separated, Kind> } ``` Added in v2.0.0 ## Partition2 (interface) **Signature** ```ts export interface Partition2 { (fa: Kind2, refinement: Refinement): Separated, Kind2> (fa: Kind2, predicate: Predicate): Separated, Kind2> } ``` Added in v2.0.0 ## Partition2C (interface) **Signature** ```ts export interface Partition2C { (fa: Kind2, refinement: Refinement): Separated, Kind2> (fa: Kind2, predicate: Predicate): Separated, Kind2> } ``` Added in v2.0.0 ## Partition3 (interface) **Signature** ```ts export interface Partition3 { (fa: Kind3, refinement: Refinement): Separated< Kind3, Kind3 > (fa: Kind3, predicate: Predicate): Separated, Kind3> } ``` Added in v2.0.0 ## Partition3C (interface) **Signature** ```ts export interface Partition3C { (fa: Kind3, refinement: Refinement): Separated< Kind3, Kind3 > (fa: Kind3, predicate: Predicate): Separated, Kind3> } ``` Added in v2.2.0 ## Partition4 (interface) **Signature** ```ts export interface Partition4 { (fa: Kind4, refinement: Refinement): Separated< Kind4, Kind4 > (fa: Kind4, predicate: Predicate): Separated, Kind4> } ``` Added in v2.0.0 ## filter `filter` composition. **Signature** ```ts export declare function filter( F: Functor2, G: Filterable2C ): { (refinement: Refinement): (fga: Kind2>) => Kind2> (predicate: Predicate): (fgb: Kind2>) => Kind2> (predicate: Predicate): (fga: Kind2>) => Kind2> } export declare function filter( F: Functor1, G: Filterable2C ): { (refinement: Refinement): (fga: Kind>) => Kind> (predicate: Predicate): (fgb: Kind>) => Kind> (predicate: Predicate): (fga: Kind>) => Kind> } export declare function filter( F: Functor1, G: Filterable1 ): { (refinement: Refinement): (fga: Kind>) => Kind> (predicate: Predicate): (fgb: Kind>) => Kind> (predicate: Predicate): (fga: Kind>) => Kind> } export declare function filter( F: Functor, G: Filterable ): { (refinement: Refinement): (fga: HKT>) => HKT> (predicate: Predicate): (fgb: HKT>) => HKT> (predicate: Predicate): (fga: HKT>) => HKT> } ``` Added in v2.10.0 ## filterMap `filterMap` composition. **Signature** ```ts export declare function filterMap( F: Functor2, G: Filterable2C ): (f: (a: A) => Option) => (fga: Kind2>) => Kind2> export declare function filterMap( F: Functor1, G: Filterable2C ): (f: (a: A) => Option) => (fga: Kind>) => Kind> export declare function filterMap( F: Functor1, G: Filterable1 ): (f: (a: A) => Option) => (fga: Kind>) => Kind> export declare function filterMap( F: Functor, G: Filterable ): (f: (a: A) => Option) => (fga: HKT>) => HKT> ``` Added in v2.10.0 ## partition `partition` composition. **Signature** ```ts export declare function partition( F: Functor2, G: Filterable2C ): { (refinement: Refinement): ( fga: Kind2> ) => Separated>, Kind2>> (predicate: Predicate): ( fgb: Kind2> ) => Separated>, Kind2>> (predicate: Predicate): ( fga: Kind2> ) => Separated>, Kind2>> } export declare function partition( F: Functor1, G: Filterable2C ): { (refinement: Refinement): ( fga: Kind> ) => Separated>, Kind>> (predicate: Predicate): ( fgb: Kind> ) => Separated>, Kind>> (predicate: Predicate): ( fga: Kind> ) => Separated>, Kind>> } export declare function partition( F: Functor1, G: Filterable1 ): { (refinement: Refinement): ( fga: Kind> ) => Separated>, Kind>> (predicate: Predicate): ( fgb: Kind> ) => Separated>, Kind>> (predicate: Predicate): (fga: Kind>) => Separated>, Kind>> } export declare function partition( F: Functor, G: Filterable ): { (refinement: Refinement): ( fga: HKT> ) => Separated>, HKT>> (predicate: Predicate): (fgb: HKT>) => Separated>, HKT>> (predicate: Predicate): (fga: HKT>) => Separated>, HKT>> } ``` Added in v2.10.0 ## partitionMap `partitionMap` composition. **Signature** ```ts export declare function partitionMap( F: Functor2, G: Filterable2C ): ( f: (a: A) => Either ) => (fa: Kind2>) => Separated>, Kind2>> export declare function partitionMap( F: Functor1, G: Filterable2C ): ( f: (a: A) => Either ) => (fa: Kind>) => Separated>, Kind>> export declare function partitionMap( F: Functor1, G: Filterable1 ): ( f: (a: A) => Either ) => (fa: Kind>) => Separated>, Kind>> export declare function partitionMap( F: Functor, G: Filterable ): (f: (a: A) => Either) => (fa: HKT>) => Separated>, HKT>> ``` Added in v2.10.0 # zone of death ## ~~FilterableComposition11~~ (interface) **Signature** ```ts export interface FilterableComposition11 extends FunctorComposition11, CompactableComposition11 { readonly partitionMap: ( fa: Kind>, f: (a: A) => Either ) => Separated>, Kind>> readonly partition: ( fa: Kind>, predicate: Predicate ) => Separated>, Kind>> readonly filterMap: (fa: Kind>, f: (a: A) => Option) => Kind> readonly filter: (fa: Kind>, predicate: Predicate) => Kind> } ``` Added in v2.0.0 ## ~~FilterableComposition12C~~ (interface) **Signature** ```ts export interface FilterableComposition12C extends FunctorComposition12C, CompactableComposition12C { readonly partitionMap: ( fa: Kind>, f: (a: A) => Either ) => Separated>, Kind>> readonly partition: ( fa: Kind>, predicate: Predicate ) => Separated>, Kind>> readonly filterMap: (fa: Kind>, f: (a: A) => Option) => Kind> readonly filter: (fa: Kind>, predicate: Predicate) => Kind> } ``` Added in v2.0.0 ## ~~FilterableComposition12~~ (interface) **Signature** ```ts export interface FilterableComposition12 extends FunctorComposition12, CompactableComposition12 { readonly partitionMap: ( fa: Kind>, f: (a: A) => Either ) => Separated>, Kind>> readonly partition: ( fa: Kind>, predicate: Predicate ) => Separated>, Kind>> readonly filterMap: (fa: Kind>, f: (a: A) => Option) => Kind> readonly filter: (fa: Kind>, predicate: Predicate) => Kind> } ``` Added in v2.0.0 ## ~~FilterableComposition21~~ (interface) **Signature** ```ts export interface FilterableComposition21 extends FunctorComposition21, CompactableComposition21 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: (fa: Kind2>, f: (a: A) => Option) => Kind2> readonly filter: (fa: Kind2>, predicate: Predicate) => Kind2> } ``` Added in v2.0.0 ## ~~FilterableComposition22C~~ (interface) **Signature** ```ts export interface FilterableComposition22C extends FunctorComposition22, CompactableComposition22 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: ( fa: Kind2>, f: (a: A) => Option ) => Kind2> readonly filter: (fa: Kind2>, predicate: Predicate) => Kind2> } ``` Added in v2.0.0 ## ~~FilterableComposition22~~ (interface) **Signature** ```ts export interface FilterableComposition22 extends FunctorComposition22, CompactableComposition22 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: ( fa: Kind2>, f: (a: A) => Option ) => Kind2> readonly filter: ( fa: Kind2>, predicate: Predicate ) => Kind2> } ``` Added in v2.0.0 ## ~~FilterableComposition23C~~ (interface) **Signature** ```ts export interface FilterableComposition23C extends FunctorComposition23, CompactableComposition23 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: ( fa: Kind2>, f: (a: A) => Option ) => Kind2> readonly filter: ( fa: Kind2>, predicate: Predicate ) => Kind2> } ``` Added in v2.2.0 ## ~~FilterableComposition2C1~~ (interface) **Signature** ```ts export interface FilterableComposition2C1 extends FunctorComposition21, CompactableComposition21 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: (fa: Kind2>, f: (a: A) => Option) => Kind2> readonly filter: (fa: Kind2>, predicate: Predicate) => Kind2> } ``` Added in v2.0.0 ## ~~FilterableComposition~~ (interface) **Signature** ```ts export interface FilterableComposition extends FunctorComposition, CompactableComposition { readonly partitionMap: ( fa: HKT>, f: (a: A) => Either ) => Separated>, HKT>> readonly partition: ( fa: HKT>, predicate: Predicate ) => Separated>, HKT>> readonly filterMap: (fa: HKT>, f: (a: A) => Option) => HKT> readonly filter: (fa: HKT>, predicate: Predicate) => HKT> } ``` Added in v2.0.0 ## ~~getFilterableComposition~~ Use - [`filter`](#filter) - [`filterMap`](#filtermap) - [`partition`](#partition) - [`partitionMap`](#partitionmap) instead. **Signature** ```ts export declare function getFilterableComposition( F: Functor2, G: Filterable3C ): FilterableComposition23C export declare function getFilterableComposition( F: Functor2, G: Filterable2C ): FilterableComposition22C export declare function getFilterableComposition( F: Functor2, G: Filterable2 ): FilterableComposition22 export declare function getFilterableComposition( F: Functor2C, G: Filterable1 ): FilterableComposition2C1 export declare function getFilterableComposition( F: Functor2, G: Filterable1 ): FilterableComposition21 export declare function getFilterableComposition( F: Functor1, G: Filterable2C ): FilterableComposition12C export declare function getFilterableComposition( F: Functor1, G: Filterable2 ): FilterableComposition12 export declare function getFilterableComposition( F: Functor1, G: Filterable1 ): FilterableComposition11 export declare function getFilterableComposition(F: Functor, G: Filterable): FilterableComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/FilterableWithIndex.ts.md ================================================ --- title: FilterableWithIndex.ts nav_order: 32 parent: Modules --- ## FilterableWithIndex overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [FilterableWithIndex (interface)](#filterablewithindex-interface) - [FilterableWithIndex1 (interface)](#filterablewithindex1-interface) - [FilterableWithIndex2 (interface)](#filterablewithindex2-interface) - [FilterableWithIndex2C (interface)](#filterablewithindex2c-interface) - [FilterableWithIndex3 (interface)](#filterablewithindex3-interface) - [FilterableWithIndex3C (interface)](#filterablewithindex3c-interface) - [FilterableWithIndex4 (interface)](#filterablewithindex4-interface) - [utils](#utils) - [FilterWithIndex (interface)](#filterwithindex-interface) - [FilterWithIndex1 (interface)](#filterwithindex1-interface) - [FilterWithIndex2 (interface)](#filterwithindex2-interface) - [FilterWithIndex2C (interface)](#filterwithindex2c-interface) - [FilterWithIndex3 (interface)](#filterwithindex3-interface) - [FilterWithIndex3C (interface)](#filterwithindex3c-interface) - [FilterWithIndex4 (interface)](#filterwithindex4-interface) - [PartitionWithIndex (interface)](#partitionwithindex-interface) - [PartitionWithIndex1 (interface)](#partitionwithindex1-interface) - [PartitionWithIndex2 (interface)](#partitionwithindex2-interface) - [PartitionWithIndex2C (interface)](#partitionwithindex2c-interface) - [PartitionWithIndex3 (interface)](#partitionwithindex3-interface) - [PartitionWithIndex3C (interface)](#partitionwithindex3c-interface) - [PartitionWithIndex4 (interface)](#partitionwithindex4-interface) - [PredicateWithIndex (type alias)](#predicatewithindex-type-alias) - [RefinementWithIndex (type alias)](#refinementwithindex-type-alias) --- # model ## FilterableWithIndex (interface) **Signature** ```ts export interface FilterableWithIndex extends FunctorWithIndex, Filterable { readonly partitionMapWithIndex: ( fa: HKT, f: (i: I, a: A) => Either ) => Separated, HKT> readonly partitionWithIndex: PartitionWithIndex readonly filterMapWithIndex: (fa: HKT, f: (i: I, a: A) => Option) => HKT readonly filterWithIndex: FilterWithIndex } ``` Added in v2.0.0 ## FilterableWithIndex1 (interface) **Signature** ```ts export interface FilterableWithIndex1 extends FunctorWithIndex1, Filterable1 { readonly partitionMapWithIndex: ( fa: Kind, f: (i: I, a: A) => Either ) => Separated, Kind> readonly partitionWithIndex: PartitionWithIndex1 readonly filterMapWithIndex: (fa: Kind, f: (i: I, a: A) => Option) => Kind readonly filterWithIndex: FilterWithIndex1 } ``` Added in v2.0.0 ## FilterableWithIndex2 (interface) **Signature** ```ts export interface FilterableWithIndex2 extends FunctorWithIndex2, Filterable2 { readonly partitionMapWithIndex: ( fa: Kind2, f: (i: I, a: A) => Either ) => Separated, Kind2> readonly partitionWithIndex: PartitionWithIndex2 readonly filterMapWithIndex: (fa: Kind2, f: (i: I, a: A) => Option) => Kind2 readonly filterWithIndex: FilterWithIndex2 } ``` Added in v2.0.0 ## FilterableWithIndex2C (interface) **Signature** ```ts export interface FilterableWithIndex2C extends FunctorWithIndex2C, Filterable2C { readonly partitionMapWithIndex: ( fa: Kind2, f: (i: I, a: A) => Either ) => Separated, Kind2> readonly partitionWithIndex: PartitionWithIndex2C readonly filterMapWithIndex: (fa: Kind2, f: (i: I, a: A) => Option) => Kind2 readonly filterWithIndex: FilterWithIndex2C } ``` Added in v2.0.0 ## FilterableWithIndex3 (interface) **Signature** ```ts export interface FilterableWithIndex3 extends FunctorWithIndex3, Filterable3 { readonly partitionMapWithIndex: ( fa: Kind3, f: (i: I, a: A) => Either ) => Separated, Kind3> readonly partitionWithIndex: PartitionWithIndex3 readonly filterMapWithIndex: (fa: Kind3, f: (i: I, a: A) => Option) => Kind3 readonly filterWithIndex: FilterWithIndex3 } ``` Added in v2.0.0 ## FilterableWithIndex3C (interface) **Signature** ```ts export interface FilterableWithIndex3C extends FunctorWithIndex3C, Filterable3C { readonly partitionMapWithIndex: ( fa: Kind3, f: (i: I, a: A) => Either ) => Separated, Kind3> readonly partitionWithIndex: PartitionWithIndex3C readonly filterMapWithIndex: (fa: Kind3, f: (i: I, a: A) => Option) => Kind3 readonly filterWithIndex: FilterWithIndex3C } ``` Added in v2.2.0 ## FilterableWithIndex4 (interface) **Signature** ```ts export interface FilterableWithIndex4 extends FunctorWithIndex4, Filterable4 { readonly partitionMapWithIndex: ( fa: Kind4, f: (i: I, a: A) => Either ) => Separated, Kind4> readonly partitionWithIndex: PartitionWithIndex4 readonly filterMapWithIndex: ( fa: Kind4, f: (i: I, a: A) => Option ) => Kind4 readonly filterWithIndex: FilterWithIndex4 } ``` Added in v2.0.0 # utils ## FilterWithIndex (interface) **Signature** ```ts export interface FilterWithIndex { (fa: HKT, refinementWithIndex: RefinementWithIndex): HKT
(fa: HKT, predicateWithIndex: PredicateWithIndex): HKT } ``` Added in v2.0.0 ## FilterWithIndex1 (interface) **Signature** ```ts export interface FilterWithIndex1 { (fa: Kind, refinementWithIndex: RefinementWithIndex): Kind (fa: Kind, predicateWithIndex: PredicateWithIndex): Kind } ``` Added in v2.0.0 ## FilterWithIndex2 (interface) **Signature** ```ts export interface FilterWithIndex2 { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Kind2 (fa: Kind2, predicateWithIndex: PredicateWithIndex): Kind2 } ``` Added in v2.0.0 ## FilterWithIndex2C (interface) **Signature** ```ts export interface FilterWithIndex2C { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Kind2 (fa: Kind2, predicateWithIndex: PredicateWithIndex): Kind2 } ``` Added in v2.0.0 ## FilterWithIndex3 (interface) **Signature** ```ts export interface FilterWithIndex3 { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Kind3 (fa: Kind3, predicateWithIndex: PredicateWithIndex): Kind3 } ``` Added in v2.0.0 ## FilterWithIndex3C (interface) **Signature** ```ts export interface FilterWithIndex3C { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Kind3 (fa: Kind3, predicateWithIndex: PredicateWithIndex): Kind3 } ``` Added in v2.2.0 ## FilterWithIndex4 (interface) **Signature** ```ts export interface FilterWithIndex4 { (fa: Kind4, refinementWithIndex: RefinementWithIndex): Kind4< F, S, R, E, B > (fa: Kind4, predicateWithIndex: PredicateWithIndex): Kind4 } ``` Added in v2.0.0 ## PartitionWithIndex (interface) **Signature** ```ts export interface PartitionWithIndex { (fa: HKT, refinementWithIndex: RefinementWithIndex): Separated, HKT> (fa: HKT, predicateWithIndex: PredicateWithIndex): Separated, HKT> } ``` Added in v2.0.0 ## PartitionWithIndex1 (interface) **Signature** ```ts export interface PartitionWithIndex1 { (fa: Kind, refinementWithIndex: RefinementWithIndex): Separated, Kind> (fa: Kind, predicateWithIndex: PredicateWithIndex): Separated, Kind> } ``` Added in v2.0.0 ## PartitionWithIndex2 (interface) **Signature** ```ts export interface PartitionWithIndex2 { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Separated< Kind2, Kind2 > (fa: Kind2, predicateWithIndex: PredicateWithIndex): Separated, Kind2> } ``` Added in v2.0.0 ## PartitionWithIndex2C (interface) **Signature** ```ts export interface PartitionWithIndex2C { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Separated< Kind2, Kind2 > (fa: Kind2, predicateWithIndex: PredicateWithIndex): Separated, Kind2> } ``` Added in v2.0.0 ## PartitionWithIndex3 (interface) **Signature** ```ts export interface PartitionWithIndex3 { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Separated< Kind3, Kind3 > (fa: Kind3, predicateWithIndex: PredicateWithIndex): Separated< Kind3, Kind3 > } ``` Added in v2.0.0 ## PartitionWithIndex3C (interface) **Signature** ```ts export interface PartitionWithIndex3C { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Separated< Kind3, Kind3 > (fa: Kind3, predicateWithIndex: PredicateWithIndex): Separated< Kind3, Kind3 > } ``` Added in v2.2.0 ## PartitionWithIndex4 (interface) **Signature** ```ts export interface PartitionWithIndex4 { (fa: Kind4, refinementWithIndex: RefinementWithIndex): Separated< Kind4, Kind4 > (fa: Kind4, predicateWithIndex: PredicateWithIndex): Separated< Kind4, Kind4 > } ``` Added in v2.0.0 ## PredicateWithIndex (type alias) **Signature** ```ts export type PredicateWithIndex = (i: I, a: A) => boolean ``` Added in v2.0.0 ## RefinementWithIndex (type alias) **Signature** ```ts export type RefinementWithIndex = (i: I, a: A) => a is B ``` Added in v2.0.0 ================================================ FILE: docs/modules/Foldable.ts.md ================================================ --- title: Foldable.ts nav_order: 33 parent: Modules --- ## Foldable overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Foldable (interface)](#foldable-interface) - [Foldable1 (interface)](#foldable1-interface) - [Foldable2 (interface)](#foldable2-interface) - [Foldable2C (interface)](#foldable2c-interface) - [Foldable3 (interface)](#foldable3-interface) - [Foldable3C (interface)](#foldable3c-interface) - [Foldable4 (interface)](#foldable4-interface) - [utils](#utils) - [foldMap](#foldmap) - [intercalate](#intercalate) - [reduce](#reduce) - [reduceM](#reducem) - [reduceRight](#reduceright) - [toReadonlyArray](#toreadonlyarray) - [traverse\_](#traverse_) - [zone of death](#zone-of-death) - [~~FoldableComposition11~~ (interface)](#foldablecomposition11-interface) - [~~FoldableComposition12C~~ (interface)](#foldablecomposition12c-interface) - [~~FoldableComposition12~~ (interface)](#foldablecomposition12-interface) - [~~FoldableComposition21~~ (interface)](#foldablecomposition21-interface) - [~~FoldableComposition22C~~ (interface)](#foldablecomposition22c-interface) - [~~FoldableComposition22~~ (interface)](#foldablecomposition22-interface) - [~~FoldableComposition2C1~~ (interface)](#foldablecomposition2c1-interface) - [~~FoldableComposition~~ (interface)](#foldablecomposition-interface) - [~~foldM~~](#foldm) - [~~getFoldableComposition~~](#getfoldablecomposition) - [~~toArray~~](#toarray) --- # model ## Foldable (interface) **Signature** ```ts export interface Foldable { readonly URI: F readonly reduce: (fa: HKT, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) =>
(fa: HKT, f: (a: A) => M) => M readonly reduceRight: (fa: HKT, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## Foldable1 (interface) **Signature** ```ts export interface Foldable1 { readonly URI: F readonly reduce: (fa: Kind, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind, f: (a: A) => M) => M readonly reduceRight: (fa: Kind, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## Foldable2 (interface) **Signature** ```ts export interface Foldable2 { readonly URI: F readonly reduce: (fa: Kind2, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## Foldable2C (interface) **Signature** ```ts export interface Foldable2C { readonly URI: F readonly _E: E readonly reduce: (fa: Kind2, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## Foldable3 (interface) **Signature** ```ts export interface Foldable3 { readonly URI: F readonly reduce: (fa: Kind3, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind3, f: (a: A) => M) => M readonly reduceRight: (fa: Kind3, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## Foldable3C (interface) **Signature** ```ts export interface Foldable3C { readonly URI: F readonly _E: E readonly reduce: (fa: Kind3, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind3, f: (a: A) => M) => M readonly reduceRight: (fa: Kind3, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.2.0 ## Foldable4 (interface) **Signature** ```ts export interface Foldable4 { readonly URI: F readonly reduce: (fa: Kind4, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind4, f: (a: A) => M) => M readonly reduceRight: (fa: Kind4, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 # utils ## foldMap `foldMap` composition. **Signature** ```ts export declare function foldMap( F: Foldable1, G: Foldable1 ): (M: Monoid) => (f: (a: A) => M) => (fga: Kind>) => M export declare function foldMap( F: Foldable, G: Foldable ): (M: Monoid) => (f: (a: A) => M) => (fga: HKT>) => M ``` Added in v2.10.0 ## intercalate Fold a data structure, accumulating values in some `Monoid`, combining adjacent elements using the specified separator **Signature** ```ts export declare function intercalate( M: Monoid, F: Foldable3 ): (middle: M, fm: Kind3) => M export declare function intercalate( M: Monoid, F: Foldable2 ): (middle: M, fm: Kind2) => M export declare function intercalate( M: Monoid, F: Foldable2C ): (middle: M, fm: Kind2) => M export declare function intercalate(M: Monoid, F: Foldable1): (middle: M, fm: Kind) => M export declare function intercalate(M: Monoid, F: Foldable): (middle: M, fm: HKT) => M ``` **Example** ```ts import { intercalate } from 'fp-ts/Foldable' import * as S from 'fp-ts/string' import { make, Foldable } from 'fp-ts/Tree' const t = make('a', [make('b', []), make('c', []), make('d', [])]) assert.strictEqual(intercalate(S.Monoid, Foldable)('|', t), 'a|b|c|d') ``` Added in v2.0.0 ## reduce `reduce` composition. **Signature** ```ts export declare function reduce( F: Foldable1, G: Foldable1 ): (b: B, f: (b: B, a: A) => B) => (fga: Kind>) => B export declare function reduce( F: Foldable, G: Foldable ): (b: B, f: (b: B, a: A) => B) => (fga: HKT>) => B ``` Added in v2.10.0 ## reduceM Similar to 'reduce', but the result is encapsulated in a monad. Note: this function is not generally stack-safe, e.g., for monads which build up thunks a la `IO`. **Signature** ```ts export declare function reduceM( M: Monad3, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind3) => (fa: Kind) => Kind3 export declare function reduceM( M: Monad3C, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind3) => (fa: Kind) => Kind3 export declare function reduceM( M: Monad2, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind2) => (fa: Kind) => Kind2 export declare function reduceM( M: Monad2C, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind2) => (fa: Kind) => Kind2 export declare function reduceM( M: Monad1, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind) => (fa: Kind) => Kind export declare function reduceM( M: Monad, F: Foldable ): (b: B, f: (b: B, a: A) => HKT) => (fa: HKT) => HKT ``` **Example** ```ts import { reduceM } from 'fp-ts/Foldable' import { Monad, some } from 'fp-ts/Option' import { make, Foldable } from 'fp-ts/Tree' import { pipe } from 'fp-ts/function' const t = make(1, [make(2, []), make(3, []), make(4, [])]) assert.deepStrictEqual( pipe( t, reduceM(Monad, Foldable)(0, (b, a) => (a > 2 ? some(b + a) : some(b))) ), some(7) ) ``` Added in v2.8.0 ## reduceRight `reduceRight` composition. **Signature** ```ts export declare function reduceRight( F: Foldable1, G: Foldable1 ): (b: B, f: (a: A, b: B) => B) => (fga: Kind>) => B export declare function reduceRight( F: Foldable, G: Foldable ): (b: B, f: (a: A, b: B) => B) => (fga: HKT>) => B ``` Added in v2.10.0 ## toReadonlyArray Transforms a `Foldable` into a `toReadonlyArray`. **Signature** ```ts export declare function toReadonlyArray( F: Foldable4 ): (fa: Kind4) => ReadonlyArray export declare function toReadonlyArray( F: Foldable3 ): (fa: Kind3) => ReadonlyArray export declare function toReadonlyArray( F: Foldable3C ): (fa: Kind3) => ReadonlyArray export declare function toReadonlyArray( F: Foldable2 ): (fa: Kind2) => ReadonlyArray export declare function toReadonlyArray( F: Foldable2C ): (fa: Kind2) => ReadonlyArray export declare function toReadonlyArray(F: Foldable1): (fa: Kind) => ReadonlyArray export declare function toReadonlyArray(F: Foldable): (fa: HKT) => ReadonlyArray ``` **Example** ```ts import { toReadonlyArray } from 'fp-ts/Foldable' import { Foldable, make } from 'fp-ts/Tree' const t = make(1, [make(2, []), make(3, []), make(4, [])]) assert.deepStrictEqual(toReadonlyArray(Foldable)(t), [1, 2, 3, 4]) ``` Added in v2.10.0 ## traverse\_ Traverse a data structure, performing some effects encoded by an `Applicative` functor at each value, ignoring the final result. **Signature** ```ts export declare function traverse_( M: Applicative3, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind3) => Kind3 export declare function traverse_( M: Applicative2, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind2) => Kind2 export declare function traverse_( M: Applicative2C, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind2) => Kind2 export declare function traverse_( M: Applicative1, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind) => Kind export declare function traverse_( M: Applicative, F: Foldable ): (fa: HKT, f: (a: A) => HKT) => HKT ``` **Example** ```ts import { Foldable } from 'fp-ts/Array' import { traverse_ } from 'fp-ts/Foldable' import { Applicative } from 'fp-ts/IO' let log = '' const append = (s: string) => () => (log += s) traverse_(Applicative, Foldable)(['a', 'b', 'c'], append)() assert.strictEqual(log, 'abc') ``` Added in v2.0.0 # zone of death ## ~~FoldableComposition11~~ (interface) **Signature** ```ts export interface FoldableComposition11 { readonly reduce: (fga: Kind>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition12C~~ (interface) **Signature** ```ts export interface FoldableComposition12C { readonly reduce: (fga: Kind>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition12~~ (interface) **Signature** ```ts export interface FoldableComposition12 { readonly reduce: (fga: Kind>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition21~~ (interface) **Signature** ```ts export interface FoldableComposition21 { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition22C~~ (interface) **Signature** ```ts export interface FoldableComposition22C { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition22~~ (interface) **Signature** ```ts export interface FoldableComposition22 { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition2C1~~ (interface) **Signature** ```ts export interface FoldableComposition2C1 { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableComposition~~ (interface) **Signature** ```ts export interface FoldableComposition { readonly reduce: (fga: HKT>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: HKT>, f: (a: A) => M) => M readonly reduceRight: (fa: HKT>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~foldM~~ Use [`reduceM`](#reducem) instead **Signature** ```ts export declare function foldM( M: Monad3, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind3) => Kind3 export declare function foldM( M: Monad3C, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind3) => Kind3 export declare function foldM( M: Monad2, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind2) => Kind2 export declare function foldM( M: Monad2C, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind2) => Kind2 export declare function foldM( M: Monad1, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind) => Kind export declare function foldM( M: Monad, F: Foldable ): (fa: HKT, b: B, f: (b: B, a: A) => HKT) => HKT ``` Added in v2.0.0 ## ~~getFoldableComposition~~ Use - [reduce](#reduce) - [foldMap](#foldmap) - [reduceRight](#reduceright) instead. **Signature** ```ts export declare function getFoldableComposition( F: Foldable2, G: Foldable2C ): FoldableComposition22C export declare function getFoldableComposition( F: Foldable2, G: Foldable2 ): FoldableComposition22 export declare function getFoldableComposition( F: Foldable2C, G: Foldable1 ): FoldableComposition2C1 export declare function getFoldableComposition( F: Foldable2, G: Foldable1 ): FoldableComposition21 export declare function getFoldableComposition( F: Foldable1, G: Foldable2C ): FoldableComposition12C export declare function getFoldableComposition( F: Foldable1, G: Foldable2 ): FoldableComposition12 export declare function getFoldableComposition( F: Foldable1, G: Foldable1 ): FoldableComposition11 export declare function getFoldableComposition(F: Foldable, G: Foldable): FoldableComposition ``` Added in v2.0.0 ## ~~toArray~~ Use [`toReadonlyArray`](#toreadonlyarray) instead **Signature** ```ts export declare const toArray: typeof toReadonlyArray ``` Added in v2.8.0 ================================================ FILE: docs/modules/FoldableWithIndex.ts.md ================================================ --- title: FoldableWithIndex.ts nav_order: 34 parent: Modules --- ## FoldableWithIndex overview A `Foldable` with an additional index. A `FoldableWithIndex` instance must be compatible with its `Foldable` instance ```ts reduce(fa, b, f) = reduceWithIndex(fa, b, (_, b, a) => f(b, a)) foldMap(M)(fa, f) = foldMapWithIndex(M)(fa, (_, a) => f(a)) reduceRight(fa, b, f) = reduceRightWithIndex(fa, b, (_, a, b) => f(a, b)) ``` Added in v2.0.0 ---

Table of contents

- [model](#model) - [FoldableWithIndex (interface)](#foldablewithindex-interface) - [FoldableWithIndex1 (interface)](#foldablewithindex1-interface) - [FoldableWithIndex2 (interface)](#foldablewithindex2-interface) - [FoldableWithIndex2C (interface)](#foldablewithindex2c-interface) - [FoldableWithIndex3 (interface)](#foldablewithindex3-interface) - [FoldableWithIndex3C (interface)](#foldablewithindex3c-interface) - [FoldableWithIndex4 (interface)](#foldablewithindex4-interface) - [utils](#utils) - [foldMapWithIndex](#foldmapwithindex) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [zone of death](#zone-of-death) - [~~FoldableWithIndexComposition11~~ (interface)](#foldablewithindexcomposition11-interface) - [~~FoldableWithIndexComposition12C~~ (interface)](#foldablewithindexcomposition12c-interface) - [~~FoldableWithIndexComposition12~~ (interface)](#foldablewithindexcomposition12-interface) - [~~FoldableWithIndexComposition21~~ (interface)](#foldablewithindexcomposition21-interface) - [~~FoldableWithIndexComposition22C~~ (interface)](#foldablewithindexcomposition22c-interface) - [~~FoldableWithIndexComposition22~~ (interface)](#foldablewithindexcomposition22-interface) - [~~FoldableWithIndexComposition2C1~~ (interface)](#foldablewithindexcomposition2c1-interface) - [~~FoldableWithIndexComposition~~ (interface)](#foldablewithindexcomposition-interface) - [~~getFoldableWithIndexComposition~~](#getfoldablewithindexcomposition) --- # model ## FoldableWithIndex (interface) **Signature** ```ts export interface FoldableWithIndex extends Foldable { readonly reduceWithIndex: (fa: HKT, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) =>
(fa: HKT, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: HKT, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.0.0 ## FoldableWithIndex1 (interface) **Signature** ```ts export interface FoldableWithIndex1 extends Foldable1 { readonly reduceWithIndex: (fa: Kind, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.0.0 ## FoldableWithIndex2 (interface) **Signature** ```ts export interface FoldableWithIndex2 extends Foldable2 { readonly reduceWithIndex: (fa: Kind2, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind2, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind2, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.0.0 ## FoldableWithIndex2C (interface) **Signature** ```ts export interface FoldableWithIndex2C extends Foldable2C { readonly reduceWithIndex: (fa: Kind2, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind2, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind2, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.0.0 ## FoldableWithIndex3 (interface) **Signature** ```ts export interface FoldableWithIndex3 extends Foldable3 { readonly reduceWithIndex: (fa: Kind3, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind3, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind3, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.0.0 ## FoldableWithIndex3C (interface) **Signature** ```ts export interface FoldableWithIndex3C extends Foldable3C { readonly reduceWithIndex: (fa: Kind3, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind3, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind3, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.2.0 ## FoldableWithIndex4 (interface) **Signature** ```ts export interface FoldableWithIndex4 extends Foldable4 { readonly reduceWithIndex: (fa: Kind4, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind4, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind4, b: B, f: (i: I, a: A, b: B) => B) => B } ``` Added in v2.0.0 # utils ## foldMapWithIndex `foldMapWithIndex` composition. **Signature** ```ts export declare function foldMapWithIndex( F: FoldableWithIndex1, G: FoldableWithIndex1 ): (M: Monoid) => (f: (ij: readonly [I, J], a: A) => M) => (fga: Kind>) => M export declare function foldMapWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (M: Monoid) => (f: (ij: readonly [I, J], a: A) => M) => (fga: HKT>) => M ``` Added in v2.10.0 ## reduceRightWithIndex `reduceRightWithIndex` composition. **Signature** ```ts export declare function reduceRightWithIndex( F: FoldableWithIndex1, G: FoldableWithIndex1 ): (b: B, f: (ij: readonly [I, J], a: A, b: B) => B) => (fga: Kind>) => B export declare function reduceRightWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (b: B, f: (ij: readonly [I, J], a: A, b: B) => B) => (fga: HKT>) => B ``` Added in v2.10.0 ## reduceWithIndex `reduceWithIndex` composition. **Signature** ```ts export declare function reduceWithIndex( F: FoldableWithIndex1, G: FoldableWithIndex1 ): (b: B, f: (ij: readonly [I, J], b: B, a: A) => B) => (fga: Kind>) => B export declare function reduceWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (b: B, f: (ij: readonly [I, J], b: B, a: A) => B) => (fga: HKT>) => B ``` Added in v2.10.0 # zone of death ## ~~FoldableWithIndexComposition11~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition11 extends FoldableComposition11 { readonly reduceWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition12C~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition12C extends FoldableComposition12C { readonly reduceWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition12~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition12 extends FoldableComposition12 { readonly reduceWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition21~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition21 extends FoldableComposition21 { readonly reduceWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: ( M: Monoid ) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition22C~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition22C extends FoldableComposition22C { readonly reduceWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: ( M: Monoid ) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: ( fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B ) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition22~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition22 extends FoldableComposition22 { readonly reduceWithIndex: ( fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B ) => B readonly foldMapWithIndex: ( M: Monoid ) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: ( fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B ) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition2C1~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition2C1 extends FoldableComposition2C1 { readonly reduceWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~FoldableWithIndexComposition~~ (interface) **Signature** ```ts export interface FoldableWithIndexComposition extends FoldableComposition { readonly reduceWithIndex: (fga: HKT>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: HKT>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: HKT>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } ``` Added in v2.0.0 ## ~~getFoldableWithIndexComposition~~ Use - [reduceWithIndex](#reducewithindex) - [foldMapWithIndex](#foldmapwithindex) - [reduceRightWithIndex](#reducerightwithindex) instead. **Signature** ```ts export declare function getFoldableWithIndexComposition( F: FoldableWithIndex2, G: FoldableWithIndex2C ): FoldableWithIndexComposition22C export declare function getFoldableWithIndexComposition( F: FoldableWithIndex2, G: FoldableWithIndex2 ): FoldableWithIndexComposition22 export declare function getFoldableWithIndexComposition( F: FoldableWithIndex2C, G: FoldableWithIndex1 ): FoldableWithIndexComposition2C1 export declare function getFoldableWithIndexComposition( F: FoldableWithIndex2, G: FoldableWithIndex1 ): FoldableWithIndexComposition21 export declare function getFoldableWithIndexComposition( F: FoldableWithIndex1, G: FoldableWithIndex2 ): FoldableWithIndexComposition12 export declare function getFoldableWithIndexComposition( F: FoldableWithIndex1, G: FoldableWithIndex2 ): FoldableWithIndexComposition12 export declare function getFoldableWithIndexComposition( F: FoldableWithIndex1, G: FoldableWithIndex1 ): FoldableWithIndexComposition11 export declare function getFoldableWithIndexComposition( F: FoldableWithIndex, G: FoldableWithIndex ): FoldableWithIndexComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/FromEither.ts.md ================================================ --- title: FromEither.ts nav_order: 35 parent: Modules --- ## FromEither overview The `FromEither` type class represents those data types which support errors. Added in v2.10.0 ---

Table of contents

- [constructors](#constructors) - [fromOption](#fromoption) - [lifting](#lifting) - [fromPredicate](#frompredicate) - [model](#model) - [FromEither (interface)](#fromeither-interface) - [FromEither1 (interface)](#fromeither1-interface) - [FromEither2 (interface)](#fromeither2-interface) - [FromEither2C (interface)](#fromeither2c-interface) - [FromEither3 (interface)](#fromeither3-interface) - [FromEither3C (interface)](#fromeither3c-interface) - [FromEither4 (interface)](#fromeither4-interface) - [utils](#utils) - [chainEitherK](#chaineitherk) - [chainFirstEitherK](#chainfirsteitherk) - [chainOptionK](#chainoptionk) - [filterOrElse](#filterorelse) - [fromEitherK](#fromeitherk) - [fromOptionK](#fromoptionk) --- # constructors ## fromOption **Signature** ```ts export declare function fromOption( F: FromEither4 ): (onNone: LazyArg) => (fa: Option
) => Kind4 export declare function fromOption( F: FromEither3 ): (onNone: LazyArg) => (fa: Option) => Kind3 export declare function fromOption( F: FromEither3C ): (onNone: LazyArg) => (fa: Option) => Kind3 export declare function fromOption( F: FromEither2 ): (onNone: LazyArg) => (fa: Option) => Kind2 export declare function fromOption( F: FromEither2C ): (onNone: LazyArg) => (fa: Option) => Kind2 export declare function fromOption(F: FromEither): (onNone: LazyArg) => (ma: Option) => HKT2 ``` Added in v2.10.0 # lifting ## fromPredicate **Signature** ```ts export declare function fromPredicate( F: FromEither4 ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind4 } export declare function fromPredicate( F: FromEither3 ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } export declare function fromPredicate( F: FromEither3C ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } export declare function fromPredicate( F: FromEither2 ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } export declare function fromPredicate( F: FromEither2C ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } export declare function fromPredicate(F: FromEither): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => HKT2 } ``` Added in v2.10.0 # model ## FromEither (interface) **Signature** ```ts export interface FromEither { readonly URI: F readonly fromEither: (e: Either) => HKT2 } ``` Added in v2.10.0 ## FromEither1 (interface) **Signature** ```ts export interface FromEither1 { readonly URI: F readonly fromEither: (fa: Either) => Kind } ``` Added in v2.11.0 ## FromEither2 (interface) **Signature** ```ts export interface FromEither2 { readonly URI: F readonly fromEither: (fa: Either) => Kind2 } ``` Added in v2.10.0 ## FromEither2C (interface) **Signature** ```ts export interface FromEither2C { readonly URI: F readonly _E: E readonly fromEither: (fa: Either) => Kind2 } ``` Added in v2.10.0 ## FromEither3 (interface) **Signature** ```ts export interface FromEither3 { readonly URI: F readonly fromEither: (fa: Either) => Kind3 } ``` Added in v2.10.0 ## FromEither3C (interface) **Signature** ```ts export interface FromEither3C { readonly URI: F readonly _E: E readonly fromEither: (fa: Either) => Kind3 } ``` Added in v2.10.0 ## FromEither4 (interface) **Signature** ```ts export interface FromEither4 { readonly URI: F readonly fromEither: (fa: Either) => Kind4 } ``` Added in v2.10.0 # utils ## chainEitherK **Signature** ```ts export declare function chainEitherK( F: FromEither4, M: Chain4 ): (f: (a: A) => Either) => (ma: Kind4) => Kind4 export declare function chainEitherK( F: FromEither3, M: Chain3 ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export declare function chainEitherK( F: FromEither3C, M: Chain3C ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export declare function chainEitherK( F: FromEither2, M: Chain2 ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export declare function chainEitherK( F: FromEither2C, M: Chain2C ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export declare function chainEitherK( F: FromEither1, M: Chain1 ): (f: (a: A) => Either) => (ma: Kind) => Kind export declare function chainEitherK( F: FromEither, M: Chain ): (f: (a: A) => Either) => (ma: HKT2) => HKT2 ``` Added in v2.10.0 ## chainFirstEitherK **Signature** ```ts export declare function chainFirstEitherK( F: FromEither4, M: Chain4 ): (f: (a: A) => Either) => (ma: Kind4) => Kind4 export declare function chainFirstEitherK( F: FromEither3, M: Chain3 ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export declare function chainFirstEitherK( F: FromEither3C, M: Chain3C ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export declare function chainFirstEitherK( F: FromEither2, M: Chain2 ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export declare function chainFirstEitherK( F: FromEither2C, M: Chain2C ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export declare function chainFirstEitherK( F: FromEither1, M: Chain1 ): (f: (a: A) => Either) => (ma: Kind) => Kind export declare function chainFirstEitherK( F: FromEither, M: Chain ): (f: (a: A) => Either) => (ma: HKT2) => HKT2 ``` Added in v2.12.0 ## chainOptionK **Signature** ```ts export declare function chainOptionK( F: FromEither4, M: Chain4 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind4) => Kind4 export declare function chainOptionK( F: FromEither3, M: Chain3 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind3) => Kind3 export declare function chainOptionK( F: FromEither3C, M: Chain3C ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind3) => Kind3 export declare function chainOptionK( F: FromEither2, M: Chain2 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind2) => Kind2 export declare function chainOptionK( F: FromEither2C, M: Chain2C ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind2) => Kind2 export declare function chainOptionK( F: FromEither, M: Chain ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: HKT2) => HKT2 ``` Added in v2.10.0 ## filterOrElse **Signature** ```ts export declare function filterOrElse( F: FromEither4, M: Chain4 ): { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind4 ) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): ( mb: Kind4 ) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind4) => Kind4 } export declare function filterOrElse( F: FromEither3, M: Chain3 ): { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind3 ) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind3) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } export declare function filterOrElse( F: FromEither3C, M: Chain3C ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind3) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind3) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } export declare function filterOrElse( F: FromEither2, M: Chain2 ): { (refinement: Refinement, onFalse: (a: A) => E): (self: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (self: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (self: Kind2) => Kind2 } export declare function filterOrElse( F: FromEither2C, M: Chain2C ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } export declare function filterOrElse( F: FromEither, M: Chain ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: HKT2) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (mb: HKT2) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (ma: HKT2) => HKT2 } ``` Added in v2.10.0 ## fromEitherK **Signature** ```ts export declare function fromEitherK( F: FromEither4 ): , E, B>(f: (...a: A) => Either) => (...a: A) => Kind4 export declare function fromEitherK( F: FromEither3 ): , E, B>(f: (...a: A) => Either) => (...a: A) => Kind3 export declare function fromEitherK( F: FromEither3C ): , B>(f: (...a: A) => Either) => (...a: A) => Kind3 export declare function fromEitherK( F: FromEither2 ): , E, B>(f: (...a: A) => Either) => (...a: A) => Kind2 export declare function fromEitherK( F: FromEither2C ): , B>(f: (...a: A) => Either) => (...a: A) => Kind2 export declare function fromEitherK( F: FromEither1 ): , B>(f: (...a: A) => Either) => (...a: A) => Kind export declare function fromEitherK( F: FromEither ): , E, B>(f: (...a: A) => Either) => (...a: A) => HKT2 ``` Added in v2.10.0 ## fromOptionK **Signature** ```ts export declare function fromOptionK( F: FromEither4 ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind4 export declare function fromOptionK( F: FromEither3 ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind3 export declare function fromOptionK( F: FromEither3C ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind3 export declare function fromOptionK( F: FromEither2 ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind2 export declare function fromOptionK( F: FromEither2C ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind2 export declare function fromOptionK( F: FromEither ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => HKT2 ``` Added in v2.10.0 ================================================ FILE: docs/modules/FromIO.ts.md ================================================ --- title: FromIO.ts nav_order: 36 parent: Modules --- ## FromIO overview Lift a computation from the `IO` monad Added in v2.10.0 ---

Table of contents

- [model](#model) - [FromIO (interface)](#fromio-interface) - [FromIO1 (interface)](#fromio1-interface) - [FromIO2 (interface)](#fromio2-interface) - [FromIO2C (interface)](#fromio2c-interface) - [FromIO3 (interface)](#fromio3-interface) - [FromIO3C (interface)](#fromio3c-interface) - [FromIO4 (interface)](#fromio4-interface) - [utils](#utils) - [chainFirstIOK](#chainfirstiok) - [chainIOK](#chainiok) - [fromIOK](#fromiok) --- # model ## FromIO (interface) **Signature** ```ts export interface FromIO { readonly URI: F readonly fromIO:
(fa: IO) => HKT } ``` Added in v2.10.0 ## FromIO1 (interface) **Signature** ```ts export interface FromIO1 { readonly URI: F readonly fromIO: (fa: IO) => Kind } ``` Added in v2.10.0 ## FromIO2 (interface) **Signature** ```ts export interface FromIO2 { readonly URI: F readonly fromIO: (fa: IO) => Kind2 } ``` Added in v2.10.0 ## FromIO2C (interface) **Signature** ```ts export interface FromIO2C { readonly URI: F readonly _E: E readonly fromIO: (fa: IO) => Kind2 } ``` Added in v2.10.0 ## FromIO3 (interface) **Signature** ```ts export interface FromIO3 { readonly URI: F readonly fromIO: (fa: IO) => Kind3 } ``` Added in v2.10.0 ## FromIO3C (interface) **Signature** ```ts export interface FromIO3C { readonly URI: F readonly _E: E readonly fromIO: (fa: IO) => Kind3 } ``` Added in v2.10.0 ## FromIO4 (interface) **Signature** ```ts export interface FromIO4 { readonly URI: F readonly fromIO: (fa: IO) => Kind4 } ``` Added in v2.10.0 # utils ## chainFirstIOK **Signature** ```ts export declare function chainFirstIOK( F: FromIO4, M: Chain4 ): (f: (a: A) => IO) => (first: Kind4) => Kind4 export declare function chainFirstIOK( F: FromIO3, M: Chain3 ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export declare function chainFirstIOK( F: FromIO3C, M: Chain3C ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export declare function chainFirstIOK( F: FromIO2, M: Chain2 ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export declare function chainFirstIOK( F: FromIO2C, M: Chain2C ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export declare function chainFirstIOK( F: FromIO1, M: Chain1 ): (f: (a: A) => IO) => (first: Kind) => Kind export declare function chainFirstIOK( F: FromIO, M: Chain ): (f: (a: A) => IO) => (first: HKT) => HKT ``` Added in v2.10.0 ## chainIOK **Signature** ```ts export declare function chainIOK( F: FromIO4, M: Chain4 ): (f: (a: A) => IO) => (first: Kind4) => Kind4 export declare function chainIOK( F: FromIO3, M: Chain3 ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export declare function chainIOK( F: FromIO3C, M: Chain3C ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export declare function chainIOK( F: FromIO2, M: Chain2 ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export declare function chainIOK( F: FromIO2C, M: Chain2C ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export declare function chainIOK( F: FromIO1, M: Chain1 ): (f: (a: A) => IO) => (first: Kind) => Kind export declare function chainIOK( F: FromIO, M: Chain ): (f: (a: A) => IO) => (first: HKT) => HKT ``` Added in v2.10.0 ## fromIOK **Signature** ```ts export declare function fromIOK( F: FromIO4 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind4 export declare function fromIOK( F: FromIO3 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind3 export declare function fromIOK( F: FromIO3C ): , B>(f: (...a: A) => IO) => (...a: A) => Kind3 export declare function fromIOK( F: FromIO2 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind2 export declare function fromIOK( F: FromIO2C ): , B>(f: (...a: A) => IO) => (...a: A) => Kind2 export declare function fromIOK( F: FromIO1 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind export declare function fromIOK( F: FromIO ): , B>(f: (...a: A) => IO) => (...a: A) => HKT ``` Added in v2.10.0 ================================================ FILE: docs/modules/FromReader.ts.md ================================================ --- title: FromReader.ts nav_order: 37 parent: Modules --- ## FromReader overview Lift a computation from the `Reader` monad. Added in v2.11.0 ---

Table of contents

- [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [model](#model) - [FromReader (interface)](#fromreader-interface) - [FromReader2 (interface)](#fromreader2-interface) - [FromReader3 (interface)](#fromreader3-interface) - [FromReader3C (interface)](#fromreader3c-interface) - [FromReader4 (interface)](#fromreader4-interface) - [utils](#utils) - [chainFirstReaderK](#chainfirstreaderk) - [chainReaderK](#chainreaderk) - [fromReaderK](#fromreaderk) --- # constructors ## ask **Signature** ```ts export declare function ask(F: FromReader4): () => Kind4 export declare function ask(F: FromReader3): () => Kind3 export declare function ask(F: FromReader3C): () => Kind3 export declare function ask(F: FromReader2): () => Kind2 export declare function ask(F: FromReader): () => HKT2 ``` Added in v2.11.0 ## asks **Signature** ```ts export declare function asks(F: FromReader4): (f: (r: R) => A) => Kind4 export declare function asks(F: FromReader3): (f: (r: R) => A) => Kind3 export declare function asks(F: FromReader3C): (f: (r: R) => A) => Kind3 export declare function asks(F: FromReader2): (f: (r: R) => A) => Kind2 export declare function asks(F: FromReader): (f: (r: R) => A) => HKT2 ``` Added in v2.11.0 # model ## FromReader (interface) **Signature** ```ts export interface FromReader { readonly URI: F readonly fromReader: (fa: Reader) => HKT2 } ``` Added in v2.11.0 ## FromReader2 (interface) **Signature** ```ts export interface FromReader2 { readonly URI: F readonly fromReader: (fa: Reader) => Kind2 } ``` Added in v2.11.0 ## FromReader3 (interface) **Signature** ```ts export interface FromReader3 { readonly URI: F readonly fromReader: (fa: Reader) => Kind3 } ``` Added in v2.11.0 ## FromReader3C (interface) **Signature** ```ts export interface FromReader3C { readonly URI: F readonly _E: E readonly fromReader: (fa: Reader) => Kind3 } ``` Added in v2.11.0 ## FromReader4 (interface) **Signature** ```ts export interface FromReader4 { readonly URI: F readonly fromReader: (fa: Reader) => Kind4 } ``` Added in v2.11.0 # utils ## chainFirstReaderK **Signature** ```ts export declare function chainFirstReaderK( F: FromReader4, M: Chain4 ): (f: (a: A) => Reader) => (ma: Kind4) => Kind4 export declare function chainFirstReaderK( F: FromReader3, M: Chain3 ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export declare function chainFirstReaderK( F: FromReader3C, M: Chain3C ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export declare function chainFirstReaderK( F: FromReader2, M: Chain2 ): (f: (a: A) => Reader) => (ma: Kind2) => Kind2 export declare function chainFirstReaderK( F: FromReader, M: Chain ): (f: (a: A) => Reader) => (ma: HKT2) => HKT2 ``` Added in v2.11.0 ## chainReaderK **Signature** ```ts export declare function chainReaderK( F: FromReader4, M: Chain4 ): (f: (a: A) => Reader) => (ma: Kind4) => Kind4 export declare function chainReaderK( F: FromReader3, M: Chain3 ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export declare function chainReaderK( F: FromReader3C, M: Chain3C ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export declare function chainReaderK( F: FromReader2, M: Chain2 ): (f: (a: A) => Reader) => (ma: Kind2) => Kind2 export declare function chainReaderK( F: FromReader, M: Chain ): (f: (a: A) => Reader) => (ma: HKT2) => HKT2 ``` Added in v2.11.0 ## fromReaderK **Signature** ```ts export declare function fromReaderK( F: FromReader4 ):
, R, B>(f: (...a: A) => Reader) => (...a: A) => Kind4 export declare function fromReaderK( F: FromReader3 ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind3 export declare function fromReaderK( F: FromReader3C ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind3 export declare function fromReaderK( F: FromReader2 ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind2 export declare function fromReaderK( F: FromReader ): , R, B>(f: (...a: A) => Reader) => (...a: A) => HKT2 ``` Added in v2.11.0 ================================================ FILE: docs/modules/FromState.ts.md ================================================ --- title: FromState.ts nav_order: 38 parent: Modules --- ## FromState overview Lift a computation from the `State` monad. Added in v2.11.0 ---

Table of contents

- [constructors](#constructors) - [get](#get) - [gets](#gets) - [modify](#modify) - [put](#put) - [model](#model) - [FromState (interface)](#fromstate-interface) - [FromState2 (interface)](#fromstate2-interface) - [FromState3 (interface)](#fromstate3-interface) - [FromState3C (interface)](#fromstate3c-interface) - [FromState4 (interface)](#fromstate4-interface) - [utils](#utils) - [chainStateK](#chainstatek) - [fromStateK](#fromstatek) --- # constructors ## get **Signature** ```ts export declare function get(F: FromState4): () => Kind4 export declare function get(F: FromState3): () => Kind3 export declare function get(F: FromState3C): () => Kind3 export declare function get(F: FromState2): () => Kind2 export declare function get(F: FromState): () => HKT2 ``` Added in v2.11.0 ## gets **Signature** ```ts export declare function gets(F: FromState4): (f: (s: S) => A) => Kind4 export declare function gets(F: FromState3): (f: (s: S) => A) => Kind3 export declare function gets(F: FromState3C): (f: (s: S) => A) => Kind3 export declare function gets(F: FromState2): (f: (s: S) => A) => Kind2 export declare function gets(F: FromState): (f: (s: S) => A) => HKT2 ``` Added in v2.11.0 ## modify **Signature** ```ts export declare function modify( F: FromState4 ): (f: Endomorphism) => Kind4 export declare function modify(F: FromState3): (f: Endomorphism) => Kind3 export declare function modify( F: FromState3C ): (f: Endomorphism) => Kind3 export declare function modify(F: FromState2): (f: Endomorphism) => Kind2 export declare function modify(F: FromState): (f: Endomorphism) => HKT2 ``` Added in v2.11.0 ## put **Signature** ```ts export declare function put(F: FromState4): (s: S) => Kind4 export declare function put(F: FromState3): (s: S) => Kind3 export declare function put(F: FromState3C): (s: S) => Kind3 export declare function put(F: FromState2): (s: S) => Kind2 export declare function put(F: FromState): (s: S) => HKT2 ``` Added in v2.11.0 # model ## FromState (interface) **Signature** ```ts export interface FromState { readonly URI: F readonly fromState: (fa: State) => HKT2 } ``` Added in v2.11.0 ## FromState2 (interface) **Signature** ```ts export interface FromState2 { readonly URI: F readonly fromState: (fa: State) => Kind2 } ``` Added in v2.11.0 ## FromState3 (interface) **Signature** ```ts export interface FromState3 { readonly URI: F readonly fromState: (fa: State) => Kind3 } ``` Added in v2.11.0 ## FromState3C (interface) **Signature** ```ts export interface FromState3C { readonly URI: F readonly _E: E readonly fromState: (fa: State) => Kind3 } ``` Added in v2.11.0 ## FromState4 (interface) **Signature** ```ts export interface FromState4 { readonly URI: F readonly fromState: (fa: State) => Kind4 } ``` Added in v2.11.0 # utils ## chainStateK **Signature** ```ts export declare function chainStateK( F: FromState4, M: Chain4 ): (f: (a: A) => State) => (ma: Kind4) => Kind4 export declare function chainStateK( F: FromState3, M: Chain3 ): (f: (a: A) => State) => (ma: Kind3) => Kind3 export declare function chainStateK( F: FromState2, M: Chain2 ): (f: (a: A) => State) => (ma: Kind2) => Kind2 export declare function chainStateK( F: FromState, M: Chain ): (f: (a: A) => State) => (ma: HKT2) => HKT2 ``` Added in v2.11.0 ## fromStateK **Signature** ```ts export declare function fromStateK( F: FromState4 ):
, S, B>(f: (...a: A) => State) => (...a: A) => Kind4 export declare function fromStateK( F: FromState3 ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind3 export declare function fromStateK( F: FromState3C ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind3 export declare function fromStateK( F: FromState2 ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind2 export declare function fromStateK( F: FromState ): , S, B>(f: (...a: A) => State) => (...a: A) => HKT2 ``` Added in v2.11.0 ================================================ FILE: docs/modules/FromTask.ts.md ================================================ --- title: FromTask.ts nav_order: 39 parent: Modules --- ## FromTask overview Lift a computation from the `Task` monad Added in v2.10.0 ---

Table of contents

- [model](#model) - [FromTask (interface)](#fromtask-interface) - [FromTask1 (interface)](#fromtask1-interface) - [FromTask2 (interface)](#fromtask2-interface) - [FromTask2C (interface)](#fromtask2c-interface) - [FromTask3 (interface)](#fromtask3-interface) - [FromTask3C (interface)](#fromtask3c-interface) - [FromTask4 (interface)](#fromtask4-interface) - [utils](#utils) - [chainFirstTaskK](#chainfirsttaskk) - [chainTaskK](#chaintaskk) - [fromTaskK](#fromtaskk) --- # model ## FromTask (interface) **Signature** ```ts export interface FromTask extends FromIO { readonly fromTask:
(fa: Task) => HKT } ``` Added in v2.10.0 ## FromTask1 (interface) **Signature** ```ts export interface FromTask1 extends FromIO1 { readonly fromTask: (fa: Task) => Kind } ``` Added in v2.10.0 ## FromTask2 (interface) **Signature** ```ts export interface FromTask2 extends FromIO2 { readonly fromTask: (fa: Task) => Kind2 } ``` Added in v2.10.0 ## FromTask2C (interface) **Signature** ```ts export interface FromTask2C extends FromIO2C { readonly fromTask: (fa: Task) => Kind2 } ``` Added in v2.10.0 ## FromTask3 (interface) **Signature** ```ts export interface FromTask3 extends FromIO3 { readonly fromTask: (fa: Task) => Kind3 } ``` Added in v2.10.0 ## FromTask3C (interface) **Signature** ```ts export interface FromTask3C extends FromIO3C { readonly fromTask: (fa: Task) => Kind3 } ``` Added in v2.10.0 ## FromTask4 (interface) **Signature** ```ts export interface FromTask4 extends FromIO4 { readonly fromTask: (fa: Task) => Kind4 } ``` Added in v2.10.0 # utils ## chainFirstTaskK **Signature** ```ts export declare function chainFirstTaskK( F: FromTask4, M: Chain4 ): (f: (a: A) => Task) => (first: Kind4) => Kind4 export declare function chainFirstTaskK( F: FromTask3, M: Chain3 ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export declare function chainFirstTaskK( F: FromTask3C, M: Chain3C ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export declare function chainFirstTaskK( F: FromTask2, M: Chain2 ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export declare function chainFirstTaskK( F: FromTask2C, M: Chain2C ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export declare function chainFirstTaskK( F: FromTask1, M: Chain1 ): (f: (a: A) => Task) => (first: Kind) => Kind export declare function chainFirstTaskK( F: FromTask, M: Chain ): (f: (a: A) => Task) => (first: HKT) => HKT ``` Added in v2.10.0 ## chainTaskK **Signature** ```ts export declare function chainTaskK( F: FromTask4, M: Chain4 ): (f: (a: A) => Task) => (first: Kind4) => Kind4 export declare function chainTaskK( F: FromTask3, M: Chain3 ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export declare function chainTaskK( F: FromTask3C, M: Chain3C ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export declare function chainTaskK( F: FromTask2, M: Chain2 ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export declare function chainTaskK( F: FromTask2C, M: Chain2C ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export declare function chainTaskK( F: FromTask1, M: Chain1 ): (f: (a: A) => Task) => (first: Kind) => Kind export declare function chainTaskK( F: FromTask, M: Chain ): (f: (a: A) => Task) => (first: HKT) => HKT ``` Added in v2.10.0 ## fromTaskK **Signature** ```ts export declare function fromTaskK( F: FromTask4 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind4 export declare function fromTaskK( F: FromTask3 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind3 export declare function fromTaskK( F: FromTask3C ): , B>(f: (...a: A) => Task) => (...a: A) => Kind3 export declare function fromTaskK( F: FromTask2 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind2 export declare function fromTaskK( F: FromTask2C ): , B>(f: (...a: A) => Task) => (...a: A) => Kind2 export declare function fromTaskK( F: FromTask1 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind export declare function fromTaskK( F: FromTask ): , B>(f: (...a: A) => Task) => (...a: A) => HKT ``` Added in v2.10.0 ================================================ FILE: docs/modules/FromThese.ts.md ================================================ --- title: FromThese.ts nav_order: 40 parent: Modules --- ## FromThese overview The `FromThese` type class represents those data types which support errors and warnings. Added in v2.11.0 ---

Table of contents

- [model](#model) - [FromThese (interface)](#fromthese-interface) - [FromThese2 (interface)](#fromthese2-interface) - [FromThese2C (interface)](#fromthese2c-interface) - [FromThese3 (interface)](#fromthese3-interface) - [FromThese3C (interface)](#fromthese3c-interface) - [FromThese4 (interface)](#fromthese4-interface) - [utils](#utils) - [fromTheseK](#fromthesek) --- # model ## FromThese (interface) **Signature** ```ts export interface FromThese { readonly URI: F readonly fromThese: (e: These) => HKT2 } ``` Added in v2.11.0 ## FromThese2 (interface) **Signature** ```ts export interface FromThese2 { readonly URI: F readonly fromThese: (fa: These) => Kind2 } ``` Added in v2.11.0 ## FromThese2C (interface) **Signature** ```ts export interface FromThese2C { readonly URI: F readonly _E: E readonly fromThese:
(fa: These) => Kind2 } ``` Added in v2.11.0 ## FromThese3 (interface) **Signature** ```ts export interface FromThese3 { readonly URI: F readonly fromThese: (fa: These) => Kind3 } ``` Added in v2.11.0 ## FromThese3C (interface) **Signature** ```ts export interface FromThese3C { readonly URI: F readonly _E: E readonly fromThese: (fa: These) => Kind3 } ``` Added in v2.11.0 ## FromThese4 (interface) **Signature** ```ts export interface FromThese4 { readonly URI: F readonly fromThese: (fa: These) => Kind4 } ``` Added in v2.11.0 # utils ## fromTheseK **Signature** ```ts export declare function fromTheseK( F: FromThese4 ): , E, B>(f: (...a: A) => These) => (...a: A) => Kind4 export declare function fromTheseK( F: FromThese3 ): , E, B>(f: (...a: A) => These) => (...a: A) => Kind3 export declare function fromTheseK( F: FromThese3C ): , B>(f: (...a: A) => These) => (...a: A) => Kind3 export declare function fromTheseK( F: FromThese2 ): , E, B>(f: (...a: A) => These) => (...a: A) => Kind2 export declare function fromTheseK( F: FromThese2C ): , B>(f: (...a: A) => These) => (...a: A) => Kind2 export declare function fromTheseK( F: FromThese ): , E, B>(f: (...a: A) => These) => (...a: A) => HKT2 ``` Added in v2.11.0 ================================================ FILE: docs/modules/Functor.ts.md ================================================ --- title: Functor.ts nav_order: 42 parent: Modules --- ## Functor overview A `Functor` is a type constructor which supports a mapping operation `map`. `map` can be used to turn functions `a -> b` into functions `f a -> f b` whose argument and return types use the type constructor `f` to represent some computational context. Instances must satisfy the following laws: 1. Identity: `F.map(fa, a => a) <-> fa` 2. Composition: `F.map(fa, a => bc(ab(a))) <-> F.map(F.map(fa, ab), bc)` Added in v2.0.0 ---

Table of contents

- [mapping](#mapping) - [flap](#flap) - [model](#model) - [Functor (interface)](#functor-interface) - [Functor1 (interface)](#functor1-interface) - [Functor2 (interface)](#functor2-interface) - [Functor2C (interface)](#functor2c-interface) - [Functor3 (interface)](#functor3-interface) - [Functor3C (interface)](#functor3c-interface) - [Functor4 (interface)](#functor4-interface) - [utils](#utils) - [bindTo](#bindto) - [let](#let) - [let\_](#let_) - [map](#map) - [zone of death](#zone-of-death) - [~~FunctorComposition11~~ (interface)](#functorcomposition11-interface) - [~~FunctorComposition12C~~ (interface)](#functorcomposition12c-interface) - [~~FunctorComposition12~~ (interface)](#functorcomposition12-interface) - [~~FunctorComposition21~~ (interface)](#functorcomposition21-interface) - [~~FunctorComposition22C~~ (interface)](#functorcomposition22c-interface) - [~~FunctorComposition22~~ (interface)](#functorcomposition22-interface) - [~~FunctorComposition23C~~ (interface)](#functorcomposition23c-interface) - [~~FunctorComposition23~~ (interface)](#functorcomposition23-interface) - [~~FunctorComposition2C1~~ (interface)](#functorcomposition2c1-interface) - [~~FunctorCompositionHKT1~~ (interface)](#functorcompositionhkt1-interface) - [~~FunctorCompositionHKT2C~~ (interface)](#functorcompositionhkt2c-interface) - [~~FunctorCompositionHKT2~~ (interface)](#functorcompositionhkt2-interface) - [~~FunctorComposition~~ (interface)](#functorcomposition-interface) - [~~getFunctorComposition~~](#getfunctorcomposition) --- # mapping ## flap **Signature** ```ts export declare function flap( F: Functor4 ):
(a: A) => (fab: Kind4 B>) => Kind4 export declare function flap( F: Functor3 ): (a: A) => (fab: Kind3 B>) => Kind3 export declare function flap( F: Functor2 ): (a: A) => (fab: Kind2 B>) => Kind2 export declare function flap(F: Functor1): (a: A) => (fab: Kind B>) => Kind export declare function flap(F: Functor): (a: A) => (fab: HKT B>) => HKT ``` Added in v2.10.0 # model ## Functor (interface) **Signature** ```ts export interface Functor { readonly URI: F readonly map: (fa: HKT, f: (a: A) => B) => HKT } ``` Added in v2.0.0 ## Functor1 (interface) **Signature** ```ts export interface Functor1 { readonly URI: F readonly map: (fa: Kind, f: (a: A) => B) => Kind } ``` Added in v2.0.0 ## Functor2 (interface) **Signature** ```ts export interface Functor2 { readonly URI: F readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } ``` Added in v2.0.0 ## Functor2C (interface) **Signature** ```ts export interface Functor2C { readonly URI: F readonly _E: E readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } ``` Added in v2.0.0 ## Functor3 (interface) **Signature** ```ts export interface Functor3 { readonly URI: F readonly map: (fa: Kind3, f: (a: A) => B) => Kind3 } ``` Added in v2.0.0 ## Functor3C (interface) **Signature** ```ts export interface Functor3C { readonly URI: F readonly _E: E readonly map: (fa: Kind3, f: (a: A) => B) => Kind3 } ``` Added in v2.2.0 ## Functor4 (interface) **Signature** ```ts export interface Functor4 { readonly URI: F readonly map: (fa: Kind4, f: (a: A) => B) => Kind4 } ``` Added in v2.0.0 # utils ## bindTo **Signature** ```ts export declare function bindTo( F: Functor4 ): (name: N) => (fa: Kind4) => Kind4 export declare function bindTo( F: Functor3 ): (name: N) => (fa: Kind3) => Kind3 export declare function bindTo( F: Functor3C ): (name: N) => (fa: Kind3) => Kind3 export declare function bindTo( F: Functor2 ): (name: N) => (fa: Kind2) => Kind2 export declare function bindTo( F: Functor2C ): (name: N) => (fa: Kind2) => Kind2 export declare function bindTo( F: Functor1 ): (name: N) => (fa: Kind) => Kind export declare function bindTo( F: Functor ): (name: N) => (fa: HKT) => HKT ``` Added in v2.10.0 ## let **Signature** ```ts export declare const let: typeof let_ ``` Added in v2.13.0 ## let\_ **Signature** ```ts function let_( F: Functor4 ): ( name: Exclude, f: (a: A) => B ) => ( fa: Kind4 ) => Kind4 function let_( F: Functor3 ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind3) => Kind3 function let_( F: Functor3C ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind3) => Kind3 function let_( F: Functor2 ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind2) => Kind2 function let_( F: Functor2C ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind2) => Kind2 function let_( F: Functor1 ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind) => Kind function let_( F: Functor ): ( name: Exclude, f: (a: A) => B ) => (fa: HKT) => HKT ``` Added in v2.13.0 ## map `map` composition. **Signature** ```ts export declare function map( F: Functor3, G: Functor1 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor2, G: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor2, G: Functor1 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor1, G: Functor3 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export declare function map( F: Functor1, G: Functor2 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export declare function map( F: Functor1, G: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export declare function map( F: Functor, G: Functor2 ): (f: (a: A) => B) => (fa: HKT>) => HKT> export declare function map( F: Functor, G: Functor1 ): (f: (a: A) => B) => (fa: HKT>) => HKT> export declare function map( F: Functor, G: Functor ): (f: (a: A) => B) => (fa: HKT>) => HKT> ``` Added in v2.10.0 # zone of death ## ~~FunctorComposition11~~ (interface) **Signature** ```ts export interface FunctorComposition11 { readonly map: (fa: Kind>, f: (a: A) => B) => Kind> } ``` Added in v2.0.0 ## ~~FunctorComposition12C~~ (interface) **Signature** ```ts export interface FunctorComposition12C { readonly map: (fa: Kind>, f: (a: A) => B) => Kind> } ``` Added in v2.0.0 ## ~~FunctorComposition12~~ (interface) **Signature** ```ts export interface FunctorComposition12 { readonly map: (fa: Kind>, f: (a: A) => B) => Kind> } ``` Added in v2.0.0 ## ~~FunctorComposition21~~ (interface) **Signature** ```ts export interface FunctorComposition21 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorComposition22C~~ (interface) **Signature** ```ts export interface FunctorComposition22C { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorComposition22~~ (interface) **Signature** ```ts export interface FunctorComposition22 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorComposition23C~~ (interface) **Signature** ```ts export interface FunctorComposition23C { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } ``` Added in v2.2.0 ## ~~FunctorComposition23~~ (interface) **Signature** ```ts export interface FunctorComposition23 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } ``` Added in v2.2.0 ## ~~FunctorComposition2C1~~ (interface) **Signature** ```ts export interface FunctorComposition2C1 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorCompositionHKT1~~ (interface) **Signature** ```ts export interface FunctorCompositionHKT1 { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } ``` Added in v2.0.0 ## ~~FunctorCompositionHKT2C~~ (interface) **Signature** ```ts export interface FunctorCompositionHKT2C { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } ``` Added in v2.0.0 ## ~~FunctorCompositionHKT2~~ (interface) **Signature** ```ts export interface FunctorCompositionHKT2 { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } ``` Added in v2.0.0 ## ~~FunctorComposition~~ (interface) **Signature** ```ts export interface FunctorComposition { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } ``` Added in v2.0.0 ## ~~getFunctorComposition~~ Use [`map`](#map) instead. **Signature** ```ts export declare function getFunctorComposition( F: Functor2, G: Functor3C ): FunctorComposition23C export declare function getFunctorComposition( F: Functor2, G: Functor2C ): FunctorComposition22C export declare function getFunctorComposition( F: Functor2, G: Functor2 ): FunctorComposition22 export declare function getFunctorComposition( F: Functor2C, G: Functor1 ): FunctorComposition2C1 export declare function getFunctorComposition( F: Functor2, G: Functor1 ): FunctorComposition21 export declare function getFunctorComposition( F: Functor1, G: Functor2C ): FunctorComposition12C export declare function getFunctorComposition( F: Functor1, G: Functor2 ): FunctorComposition12 export declare function getFunctorComposition( F: Functor1, G: Functor1 ): FunctorComposition11 export declare function getFunctorComposition(F: Functor, G: Functor): FunctorComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/FunctorWithIndex.ts.md ================================================ --- title: FunctorWithIndex.ts nav_order: 43 parent: Modules --- ## FunctorWithIndex overview A `FunctorWithIndex` is a type constructor which supports a mapping operation `mapWithIndex`. `mapWithIndex` can be used to turn functions `i -> a -> b` into functions `f a -> f b` whose argument and return types use the type constructor `f` to represent some computational context. Instances must satisfy the following laws: 1. Identity: `F.mapWithIndex(fa, (_i, a) => a) <-> fa` 2. Composition: `F.mapWithIndex(fa, (_i, a) => bc(ab(a))) <-> F.mapWithIndex(F.mapWithIndex(fa, ab), bc)` Added in v2.0.0 ---

Table of contents

- [model](#model) - [FunctorWithIndex (interface)](#functorwithindex-interface) - [FunctorWithIndex1 (interface)](#functorwithindex1-interface) - [FunctorWithIndex2 (interface)](#functorwithindex2-interface) - [FunctorWithIndex2C (interface)](#functorwithindex2c-interface) - [FunctorWithIndex3 (interface)](#functorwithindex3-interface) - [FunctorWithIndex3C (interface)](#functorwithindex3c-interface) - [FunctorWithIndex4 (interface)](#functorwithindex4-interface) - [utils](#utils) - [mapWithIndex](#mapwithindex) - [zone of death](#zone-of-death) - [~~FunctorWithIndexComposition11~~ (interface)](#functorwithindexcomposition11-interface) - [~~FunctorWithIndexComposition12C~~ (interface)](#functorwithindexcomposition12c-interface) - [~~FunctorWithIndexComposition12~~ (interface)](#functorwithindexcomposition12-interface) - [~~FunctorWithIndexComposition21~~ (interface)](#functorwithindexcomposition21-interface) - [~~FunctorWithIndexComposition22C~~ (interface)](#functorwithindexcomposition22c-interface) - [~~FunctorWithIndexComposition22~~ (interface)](#functorwithindexcomposition22-interface) - [~~FunctorWithIndexComposition2C1~~ (interface)](#functorwithindexcomposition2c1-interface) - [~~FunctorWithIndexComposition~~ (interface)](#functorwithindexcomposition-interface) - [~~getFunctorWithIndexComposition~~](#getfunctorwithindexcomposition) --- # model ## FunctorWithIndex (interface) **Signature** ```ts export interface FunctorWithIndex extends Functor { readonly mapWithIndex: (fa: HKT, f: (i: I, a: A) => B) => HKT } ``` Added in v2.0.0 ## FunctorWithIndex1 (interface) **Signature** ```ts export interface FunctorWithIndex1 extends Functor1 { readonly mapWithIndex: (fa: Kind, f: (i: I, a: A) => B) => Kind } ``` Added in v2.0.0 ## FunctorWithIndex2 (interface) **Signature** ```ts export interface FunctorWithIndex2 extends Functor2 { readonly mapWithIndex: (fa: Kind2, f: (i: I, a: A) => B) => Kind2 } ``` Added in v2.0.0 ## FunctorWithIndex2C (interface) **Signature** ```ts export interface FunctorWithIndex2C extends Functor2C { readonly mapWithIndex: (fa: Kind2, f: (i: I, a: A) => B) => Kind2 } ``` Added in v2.0.0 ## FunctorWithIndex3 (interface) **Signature** ```ts export interface FunctorWithIndex3 extends Functor3 { readonly mapWithIndex: (fa: Kind3, f: (i: I, a: A) => B) => Kind3 } ``` Added in v2.0.0 ## FunctorWithIndex3C (interface) **Signature** ```ts export interface FunctorWithIndex3C extends Functor3C { readonly mapWithIndex: (fa: Kind3, f: (i: I, a: A) => B) => Kind3 } ``` Added in v2.2.0 ## FunctorWithIndex4 (interface) **Signature** ```ts export interface FunctorWithIndex4 extends Functor4 { readonly mapWithIndex: (fa: Kind4, f: (i: I, a: A) => B) => Kind4 } ``` Added in v2.0.0 # utils ## mapWithIndex `mapWithIndex` composition. **Signature** ```ts export declare function mapWithIndex( F: FunctorWithIndex1, G: FunctorWithIndex1 ): (f: (ij: readonly [I, J], a: A) => B) => (fa: Kind>) => Kind> export declare function mapWithIndex( F: FunctorWithIndex, G: FunctorWithIndex ): (f: (ij: readonly [I, J], a: A) => B) => (fa: HKT>) => HKT> ``` Added in v2.10.0 # zone of death ## ~~FunctorWithIndexComposition11~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition11 extends FunctorComposition11 { readonly mapWithIndex: (fa: Kind>, f: (i: [FI, GI], a: A) => B) => Kind> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition12C~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition12C extends FunctorComposition12C { readonly mapWithIndex: (fa: Kind>, f: (i: [FI, GI], a: A) => B) => Kind> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition12~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition12 extends FunctorComposition12 { readonly mapWithIndex: (fa: Kind>, f: (i: [FI, GI], a: A) => B) => Kind> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition21~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition21 extends FunctorComposition21 { readonly mapWithIndex: (fa: Kind2>, f: (i: [FI, GI], a: A) => B) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition22C~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition22C extends FunctorComposition22C { readonly mapWithIndex: ( fa: Kind2>, f: (i: [FI, GI], a: A) => B ) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition22~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition22 extends FunctorComposition22 { readonly mapWithIndex: ( fa: Kind2>, f: (i: [FI, GI], a: A) => B ) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition2C1~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition2C1 extends FunctorComposition2C1 { readonly mapWithIndex: (fa: Kind2>, f: (i: [FI, GI], a: A) => B) => Kind2> } ``` Added in v2.0.0 ## ~~FunctorWithIndexComposition~~ (interface) **Signature** ```ts export interface FunctorWithIndexComposition extends FunctorComposition { readonly mapWithIndex: (fga: HKT>, f: (i: [FI, GI], a: A) => B) => HKT> } ``` Added in v2.0.0 ## ~~getFunctorWithIndexComposition~~ Use [`mapWithIndex`](#mapwithindex) instead. **Signature** ```ts export declare function getFunctorWithIndexComposition( F: FunctorWithIndex2, G: FunctorWithIndex2C ): FunctorWithIndexComposition22C export declare function getFunctorWithIndexComposition( F: FunctorWithIndex2, G: FunctorWithIndex2 ): FunctorWithIndexComposition22 export declare function getFunctorWithIndexComposition( F: FunctorWithIndex2C, G: FunctorWithIndex1 ): FunctorWithIndexComposition2C1 export declare function getFunctorWithIndexComposition( F: FunctorWithIndex2, G: FunctorWithIndex1 ): FunctorWithIndexComposition21 export declare function getFunctorWithIndexComposition( F: FunctorWithIndex1, G: FunctorWithIndex2C ): FunctorWithIndexComposition12C export declare function getFunctorWithIndexComposition( F: FunctorWithIndex1, G: FunctorWithIndex2 ): FunctorWithIndexComposition12 export declare function getFunctorWithIndexComposition( F: FunctorWithIndex1, G: FunctorWithIndex1 ): FunctorWithIndexComposition11 export declare function getFunctorWithIndexComposition( F: FunctorWithIndex, G: FunctorWithIndex ): FunctorWithIndexComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/Group.ts.md ================================================ --- title: Group.ts nav_order: 44 parent: Modules --- ## Group overview A `Group` is a `Monoid` with inverses. Instances must satisfy the following law in addition to the monoid laws: - Inverse: `concat(inverse(a), a) <-> empty = concat(a, inverse(a))` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Group (interface)](#group-interface) --- # model ## Group (interface) **Signature** ```ts export interface Group
extends Monoid { readonly inverse: (a: A) => A } ``` Added in v2.0.0 ================================================ FILE: docs/modules/HKT.ts.md ================================================ --- title: HKT.ts nav_order: 46 parent: Modules --- ## HKT overview Type defunctionalization (as describe in [Lightweight higher-kinded polymorphism](https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf)) Added in v2.0.0 ---

Table of contents

- [utils](#utils) - [HKT (interface)](#hkt-interface) - [HKT2 (interface)](#hkt2-interface) - [HKT3 (interface)](#hkt3-interface) - [HKT4 (interface)](#hkt4-interface) - [Kind (type alias)](#kind-type-alias) - [Kind2 (type alias)](#kind2-type-alias) - [Kind3 (type alias)](#kind3-type-alias) - [Kind4 (type alias)](#kind4-type-alias) - [URIS (type alias)](#uris-type-alias) - [URIS2 (type alias)](#uris2-type-alias) - [URIS3 (type alias)](#uris3-type-alias) - [URIS4 (type alias)](#uris4-type-alias) - [URItoKind (interface)](#uritokind-interface) - [URItoKind2 (interface)](#uritokind2-interface) - [URItoKind3 (interface)](#uritokind3-interface) - [URItoKind4 (interface)](#uritokind4-interface) --- # utils ## HKT (interface) `* -> *` constructors **Signature** ```ts export interface HKT { readonly _URI: URI readonly _A: A } ``` Added in v2.0.0 ## HKT2 (interface) `* -> * -> *` constructors **Signature** ```ts export interface HKT2 extends HKT { readonly _E: E } ``` Added in v2.0.0 ## HKT3 (interface) `* -> * -> * -> *` constructors **Signature** ```ts export interface HKT3 extends HKT2 { readonly _R: R } ``` Added in v2.0.0 ## HKT4 (interface) `* -> * -> * -> * -> *` constructors **Signature** ```ts export interface HKT4 extends HKT3 { readonly _S: S } ``` Added in v2.0.0 ## Kind (type alias) `* -> *` constructors **Signature** ```ts export type Kind = URI extends URIS ? URItoKind
[URI] : any ``` Added in v2.0.0 ## Kind2 (type alias) `* -> * -> *` constructors **Signature** ```ts export type Kind2 = URI extends URIS2 ? URItoKind2[URI] : any ``` Added in v2.0.0 ## Kind3 (type alias) `* -> * -> * -> *` constructors **Signature** ```ts export type Kind3 = URI extends URIS3 ? URItoKind3[URI] : any ``` Added in v2.0.0 ## Kind4 (type alias) `* -> * -> * -> * -> *` constructors **Signature** ```ts export type Kind4 = URI extends URIS4 ? URItoKind4[URI] : any ``` Added in v2.0.0 ## URIS (type alias) `* -> *` constructors **Signature** ```ts export type URIS = keyof URItoKind ``` Added in v2.0.0 ## URIS2 (type alias) `* -> * -> *` constructors **Signature** ```ts export type URIS2 = keyof URItoKind2 ``` Added in v2.0.0 ## URIS3 (type alias) `* -> * -> * -> *` constructors **Signature** ```ts export type URIS3 = keyof URItoKind3 ``` Added in v2.0.0 ## URIS4 (type alias) `* -> * -> * -> * -> *` constructors **Signature** ```ts export type URIS4 = keyof URItoKind4 ``` Added in v2.0.0 ## URItoKind (interface) `* -> *` constructors **Signature** ```ts export interface URItoKind {} ``` Added in v2.0.0 ## URItoKind2 (interface) `* -> * -> *` constructors **Signature** ```ts export interface URItoKind2 {} ``` Added in v2.0.0 ## URItoKind3 (interface) `* -> * -> * -> *` constructors **Signature** ```ts export interface URItoKind3 {} ``` Added in v2.0.0 ## URItoKind4 (interface) `* -> * -> * -> * -> *` constructors **Signature** ```ts export interface URItoKind4 {} ``` Added in v2.0.0 ================================================ FILE: docs/modules/HeytingAlgebra.ts.md ================================================ --- title: HeytingAlgebra.ts nav_order: 45 parent: Modules --- ## HeytingAlgebra overview Heyting algebras are bounded (distributive) lattices that are also equipped with an additional binary operation `implies` (also written as `→`). Heyting algebras also define a complement operation `not` (sometimes written as `¬a`) However, in Heyting algebras this operation is only a pseudo-complement, since Heyting algebras do not necessarily provide the law of the excluded middle. This means that there is no guarantee that `a ∨ ¬a = 1`. Heyting algebras model intuitionistic logic. For a model of classical logic, see the boolean algebra type class implemented as `BooleanAlgebra`. A `HeytingAlgebra` must satisfy the following laws in addition to `BoundedDistributiveLattice` laws: - Implication: - `a → a <-> 1` - `a ∧ (a → b) <-> a ∧ b` - `b ∧ (a → b) <-> b` - `a → (b ∧ c) <-> (a → b) ∧ (a → c)` - Complemented - `¬a <-> a → 0` Added in v2.0.0 ---

Table of contents

- [model](#model) - [HeytingAlgebra (interface)](#heytingalgebra-interface) --- # model ## HeytingAlgebra (interface) **Signature** ```ts export interface HeytingAlgebra
extends BoundedDistributiveLattice { readonly implies: (x: A, y: A) => A readonly not: (x: A) => A } ``` Added in v2.0.0 ================================================ FILE: docs/modules/IO.ts.md ================================================ --- title: IO.ts nav_order: 50 parent: Modules --- ## IO overview ```ts interface IO { (): A } ``` `IO` represents a non-deterministic synchronous computation that can cause side effects, yields a value of type `A` and **never fails**. If you want to represent a synchronous computation that may fail, please see `IOEither`. If you want to represent a synchronous computation that may yield nothing, please see `IOOption`. Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [constructors](#constructors) - [of](#of) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [let](#let) - [instances](#instances) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [ChainRec](#chainrec) - [FromIO](#fromio) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [Pointed](#pointed) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [IO (interface)](#io-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatten](#flatten) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [zone of death](#zone-of-death) - [~~fromIO~~](#fromio) - [~~getMonoid~~](#getmonoid) - [~~getSemigroup~~](#getsemigroup) - [~~io~~](#io) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: IO
, f: (a: A) => IO<_>): IO (f: (a: A) => IO<_>): (self: IO) => IO } ``` Added in v2.15.0 # constructors ## of **Signature** ```ts export declare const of: (a: A) => IO ``` Added in v2.0.0 # do notation ## Do **Signature** ```ts export declare const Do: IO<{}> ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: IO ) => (fa: IO) => IO<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => IO ) => (ma: IO) => IO<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: IO) => IO<{ readonly [K in N]: A }> ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: IO) => IO<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # instances ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'IO'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'IO'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain1<'IO'> ``` Added in v2.10.0 ## ChainRec **Signature** ```ts export declare const ChainRec: ChainRec1<'IO'> ``` Added in v2.7.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO1<'IO'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'IO'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'IO'> ``` Added in v2.7.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO1<'IO'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'IO'> ``` Added in v2.10.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => IO) => (ma: IO) => IO ``` Added in v2.0.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => IO) => (first: IO) => IO ``` Added in v2.0.0 # mapping ## as Maps the value to the specified constant value. **Signature** ```ts export declare const as: { (a: A): <_>(self: IO<_>) => IO; <_, A>(self: IO<_>, a: A): IO } ``` Added in v2.16.0 ## asUnit Maps the value to the void constant value. **Signature** ```ts export declare const asUnit: <_>(self: IO<_>) => IO ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: IO<(a: A) => B>) => IO ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: IO) => IO ``` Added in v2.0.0 # model ## IO (interface) **Signature** ```ts export interface IO { (): A } ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => IO): (ma: IO) => IO (ma: IO, f: (a: A) => IO): IO } ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: IO>) => IO ``` Added in v2.0.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly IO[]) => IO ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: (f: (a: A) => IO) => (as: readonly A[]) => IO ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => IO ) => (as: readonly A[]) => IO ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => IO ) => (as: readonly A[]) => IO ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => IO ) => (as: ReadonlyNonEmptyArray) => IO> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'IO' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: IO ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: IO) => (fab: IO<(a: A) => B>) => IO ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: IO) => (first: IO) => IO ``` Added in v2.0.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: IO) => (first: IO) => IO ``` Added in v2.0.0 # zone of death ## ~~fromIO~~ **Signature** ```ts export declare const fromIO: (fa: IO) => IO ``` Added in v2.7.0 ## ~~getMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~io~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `IO.Functor` instead of `IO.io` (where `IO` is from `import IO from 'fp-ts/IO'`) **Signature** ```ts export declare const io: Monad1<'IO'> & MonadIO1<'IO'> & ChainRec1<'IO'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/IOEither.ts.md ================================================ --- title: IOEither.ts nav_order: 51 parent: Modules --- ## IOEither overview `IOEither` represents a synchronous computation that either yields a value of type `A` or fails yielding an error of type `E`. If you want to represent a synchronous computation that never fails, please see `IO`. If you want to represent a synchronous computation that may yield nothing, please see `IOOption`. Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapIO](#tapio) - [constructors](#constructors) - [left](#left) - [leftIO](#leftio) - [of](#of) - [right](#right) - [rightIO](#rightio) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromOption](#fromoption) - [toUnion](#tounion) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getAltIOValidation](#getaltiovalidation) - [getApplicativeIOValidation](#getapplicativeiovalidation) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [mapBoth](#mapboth) - [mapError](#maperror) - [orElse](#orelse) - [orElseFirstIOK](#orelsefirstiok) - [orElseW](#orelsew) - [orLeft](#orleft) - [tapError](#taperror) - [filtering](#filtering) - [filterOrElse](#filterorelse) - [filterOrElseW](#filterorelsew) - [getCompactable](#getcompactable) - [getFilterable](#getfilterable) - [instances](#instances) - [Alt](#alt) - [ApplicativePar](#applicativepar) - [ApplicativeSeq](#applicativeseq) - [ApplyPar](#applypar) - [Bifunctor](#bifunctor) - [Chain](#chain) - [FromEither](#fromeither) - [FromIO](#fromio) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [interop](#interop) - [tryCatch](#trycatch) - [tryCatchK](#trycatchk) - [legacy](#legacy) - [bimap](#bimap) - [chain](#chain) - [chainEitherK](#chaineitherk) - [chainEitherKW](#chaineitherkw) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstEitherKW](#chainfirsteitherkw) - [chainFirstIOK](#chainfirstiok) - [chainFirstW](#chainfirstw) - [chainIOK](#chainiok) - [chainOptionK](#chainoptionk) - [chainOptionKW](#chainoptionkw) - [chainW](#chainw) - [fromOptionK](#fromoptionk) - [mapLeft](#mapleft) - [orElseFirst](#orelsefirst) - [orElseFirstW](#orelsefirstw) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromIOK](#fromiok) - [fromPredicate](#frompredicate) - [liftNullable](#liftnullable) - [liftOption](#liftoption) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [IOEither (interface)](#ioeither-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapEither](#flatmapeither) - [flatMapIO](#flatmapio) - [flatMapNullable](#flatmapnullable) - [flatMapOption](#flatmapoption) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [sequenceSeqArray](#sequenceseqarray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [traverseSeqArray](#traverseseqarray) - [traverseSeqArrayWithIndex](#traverseseqarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [bracket](#bracket) - [bracketW](#bracketw) - [swap](#swap) - [throwError](#throwerror) - [zone of death](#zone-of-death) - [~~Applicative~~](#applicative) - [~~getApplyMonoid~~](#getapplymonoid) - [~~getApplySemigroup~~](#getapplysemigroup) - [~~getIOValidation~~](#getiovalidation) - [~~getSemigroup~~](#getsemigroup) - [~~ioEither~~](#ioeither) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: IOEither, f: (a: A) => IOEither): IOEither (f: (a: A) => IOEither): (self: IOEither) => IOEither } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => E.Either): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => E.Either): IOEither } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as IOE from 'fp-ts/IOEither' import * as E from 'fp-ts/Either' const compute = (value: string) => pipe( IOE.of(value), IOE.tapEither(() => (value.length > 0 ? E.right('ok') : E.left('error'))) ) assert.deepStrictEqual(compute('')(), E.left('error')) assert.deepStrictEqual(compute('fp-ts')(), E.right('fp-ts')) ``` Added in v2.16.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => I.IO<_>): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => I.IO<_>): IOEither } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as IOE from 'fp-ts/IOEither' import * as E from 'fp-ts/Either' import * as Console from 'fp-ts/Console' const sayHello = (value: string) => Console.log(`Hello, ${value}`) // Will produce `Hello, fp-ts` to the stdout const effectA = IOE.tapIO(IOE.of('fp-ts'), sayHello) // No output to the stdout const effectB = pipe(IOE.left('error'), IOE.tapIO(sayHello)) assert.deepStrictEqual(effectA(), E.right('fp-ts')) assert.deepStrictEqual(effectB(), E.left('error')) ``` Added in v2.16.0 # constructors ## left **Signature** ```ts export declare const left: (l: E) => IOEither ``` Added in v2.0.0 ## leftIO **Signature** ```ts export declare const leftIO: (me: I.IO) => IOEither ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => IOEither ``` Added in v2.8.5 ## right **Signature** ```ts export declare const right: (a: A) => IOEither ``` Added in v2.0.0 ## rightIO **Signature** ```ts export declare const rightIO: (ma: I.IO
) => IOEither ``` Added in v2.0.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: E.Either) => IOEither ``` Added in v2.0.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: I.IO) => IOEither ``` Added in v2.7.0 ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option) => IOEither ``` Added in v2.0.0 ## toUnion **Signature** ```ts export declare const toUnion: (fa: IOEither) => I.IO ``` Added in v2.10.0 # do notation ## Do **Signature** ```ts export declare const Do: IOEither ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: IOEither ) => (fa: IOEither) => IOEither ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: IOEither ) => (fa: IOEither) => IOEither ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => IOEither ) => (ma: IOEither) => IOEither ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: IOEither) => IOEither ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => IOEither ) => (fa: IOEither) => IOEither ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: IOEither) => IOEither ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. **Signature** ```ts export declare const alt: (that: LazyArg>) => (fa: IOEither) => IOEither ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the error and the return types will be merged. **Signature** ```ts export declare const altW: ( that: LazyArg> ) => (fa: IOEither) => IOEither ``` Added in v2.9.0 ## getAltIOValidation The default [`Alt`](#alt) instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getAltValidation`](./Either.ts.html#getaltvalidation). **Signature** ```ts export declare function getAltIOValidation(S: Semigroup): Alt2C ``` Added in v2.7.0 ## getApplicativeIOValidation The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getApplicativeValidation`](./Either.ts.html#getapplicativevalidation). **Signature** ```ts export declare function getApplicativeIOValidation(S: Semigroup): Applicative2C ``` Added in v2.7.0 ## getOrElse **Signature** ```ts export declare const getOrElse: (onLeft: (e: E) => I.IO) => (ma: IOEither) => I.IO ``` Added in v2.0.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: (onLeft: (e: E) => I.IO) => (ma: IOEither) => I.IO ``` Added in v2.6.0 ## mapBoth Returns a `IOEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. **Signature** ```ts export declare const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: IOEither) => IOEither (self: IOEither, f: (e: E) => G, g: (a: A) => B): IOEither } ``` **Example** ```ts import * as IOEither from 'fp-ts/IOEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) const g = (n: number) => n * 2 assert.deepStrictEqual(IOEither.mapBoth(IOEither.right(1), f, g)(), Either.right(2)) assert.deepStrictEqual(IOEither.mapBoth(IOEither.left('err'), f, g)(), Either.left(new Error('err'))) ``` Added in v2.16.0 ## mapError Returns a `IOEither` with its error channel mapped using the specified function. **Signature** ```ts export declare const mapError: { (f: (e: E) => G): (self: IOEither) => IOEither (self: IOEither, f: (e: E) => G): IOEither } ``` **Example** ```ts import * as IOEither from 'fp-ts/IOEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) assert.deepStrictEqual(IOEither.mapError(IOEither.right(1), f)(), Either.right(1)) assert.deepStrictEqual(IOEither.mapError(IOEither.left('err'), f)(), Either.left(new Error('err'))) ``` Added in v2.16.0 ## orElse **Signature** ```ts export declare const orElse: (onLeft: (e: E1) => IOEither) => (ma: IOEither) => IOEither ``` Added in v2.0.0 ## orElseFirstIOK **Signature** ```ts export declare const orElseFirstIOK: (onLeft: (e: E) => I.IO) => (ma: IOEither) => IOEither ``` Added in v2.12.0 ## orElseW Less strict version of [`orElse`](#orelse). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const orElseW: ( onLeft: (e: E1) => IOEither ) => (ma: IOEither) => IOEither ``` Added in v2.10.0 ## orLeft **Signature** ```ts export declare const orLeft: (onLeft: (e: E1) => I.IO) => (fa: IOEither) => IOEither ``` Added in v2.11.0 ## tapError Returns an effect that effectfully "peeks" at the failure of this effect. **Signature** ```ts export declare const tapError: { (onLeft: (e: E1) => IOEither): (self: IOEither) => IOEither (self: IOEither, onLeft: (e: E1) => IOEither): IOEither } ``` Added in v2.15.0 # filtering ## filterOrElse **Signature** ```ts export declare const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: IOEither) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (mb: IOEither) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (ma: IOEither) => IOEither } ``` Added in v2.0.0 ## filterOrElseW Less strict version of [`filterOrElse`](#filterorelse). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: IOEither ) => IOEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: IOEither ) => IOEither (predicate: Predicate, onFalse: (a: A) => E2): (ma: IOEither) => IOEither } ``` Added in v2.9.0 ## getCompactable **Signature** ```ts export declare const getCompactable: (M: Monoid) => Compactable2C<'IOEither', E> ``` Added in v2.10.0 ## getFilterable **Signature** ```ts export declare function getFilterable(M: Monoid): Filterable2C ``` Added in v2.1.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt2<'IOEither'> ``` Added in v2.7.0 ## ApplicativePar Runs computations in parallel. **Signature** ```ts export declare const ApplicativePar: Applicative2<'IOEither'> ``` Added in v2.8.4 ## ApplicativeSeq Runs computations sequentially. **Signature** ```ts export declare const ApplicativeSeq: Applicative2<'IOEither'> ``` Added in v2.8.4 ## ApplyPar Runs computations in parallel. **Signature** ```ts export declare const ApplyPar: Apply2<'IOEither'> ``` Added in v2.10.0 ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'IOEither'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'IOEither'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither2<'IOEither'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO2<'IOEither'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'IOEither'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'IOEither'> ``` Added in v2.7.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO2<'IOEither'> ``` Added in v2.7.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow2<'IOEither'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'IOEither'> ``` Added in v2.10.0 # interop ## tryCatch Constructs a new `IOEither` from a function that performs a side effect and might throw See also [`tryCatchK`](#trycatchk). **Signature** ```ts export declare const tryCatch: (f: LazyArg, onThrow: (reason: unknown) => E) => IOEither ``` Added in v2.0.0 ## tryCatchK Converts a function that may throw to one returning a `IOEither`. **Signature** ```ts export declare const tryCatchK: ( f: (...a: A) => B, onThrow: (reason: unknown) => E ) => (...a: A) => IOEither ``` Added in v2.10.0 # legacy ## bimap Alias of `mapBoth`. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: IOEither) => IOEither ``` Added in v2.0.0 ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => IOEither) => (ma: IOEither) => IOEither ``` Added in v2.0.0 ## chainEitherK Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherK: (f: (a: A) => E.Either) => (ma: IOEither) => IOEither ``` Added in v2.4.0 ## chainEitherKW Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherKW: ( f: (a: A) => E.Either ) => (ma: IOEither) => IOEither ``` Added in v2.6.1 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => IOEither) => (ma: IOEither) => IOEither ``` Added in v2.0.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: (f: (a: A) => E.Either) => (ma: IOEither) => IOEither ``` Added in v2.12.0 ## chainFirstEitherKW Alias of `tapEither`. The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: IOEither) => IOEither ``` Added in v2.12.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => I.IO) => (first: IOEither) => IOEither ``` Added in v2.10.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => IOEither ) => (ma: IOEither) => IOEither ``` Added in v2.8.0 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => I.IO) => (first: IOEither) => IOEither ``` Added in v2.10.0 ## chainOptionK Use `flatMapOption`. **Signature** ```ts export declare const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: IOEither) => IOEither ``` Added in v2.10.0 ## chainOptionKW Use `flatMapOption`. **Signature** ```ts export declare const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: IOEither) => IOEither ``` Added in v2.13.2 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => IOEither ) => (ma: IOEither) => IOEither ``` Added in v2.6.0 ## fromOptionK Use `liftOption`. **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => IOEither ``` Added in v2.10.0 ## mapLeft Alias of `mapError`. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: IOEither) => IOEither ``` Added in v2.0.0 ## orElseFirst Alias of `tapError`. **Signature** ```ts export declare const orElseFirst: (onLeft: (e: E) => IOEither) => (ma: IOEither) => IOEither ``` Added in v2.11.0 ## orElseFirstW Alias of `tapError`. **Signature** ```ts export declare const orElseFirstW: ( onLeft: (e: E1) => IOEither ) => (ma: IOEither) => IOEither ``` Added in v2.11.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => E.Either ) => (...a: A) => IOEither ``` Added in v2.4.0 ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => I.IO ) => (...a: A) => IOEither ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (b: B) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => IOEither } ``` Added in v2.0.0 ## liftNullable **Signature** ```ts export declare const liftNullable: ( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => IOEither> ``` Added in v2.15.0 ## liftOption **Signature** ```ts export declare const liftOption: ( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => IOEither ``` Added in v2.15.0 # mapping ## as Maps the `Right` value of this `IOEither` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: IOEither) => IOEither (self: IOEither, a: A): IOEither } ``` Added in v2.16.0 ## asUnit Maps the `Right` value of this `IOEither` to the void constant value. **Signature** ```ts export declare const asUnit: (self: IOEither) => IOEither ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: IOEither B>) => IOEither ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: IOEither) => IOEither ``` Added in v2.0.0 # model ## IOEither (interface) **Signature** ```ts export interface IOEither extends IO> {} ``` Added in v2.0.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: ( onLeft: (e: E) => I.IO, onRight: (a: A) => I.IO ) => (ma: IOEither) => I.IO ``` Added in v2.0.0 ## foldW Alias of [`matchEW`](#matchew). **Signature** ```ts export declare const foldW: ( onLeft: (e: E) => I.IO, onRight: (a: A) => I.IO ) => (ma: IOEither) => I.IO ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: IOEither) => I.IO ``` Added in v2.10.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`IO`). **Signature** ```ts export declare const matchE: ( onLeft: (e: E) => I.IO, onRight: (a: A) => I.IO ) => (ma: IOEither) => I.IO ``` Added in v2.10.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onLeft: (e: E) => I.IO, onRight: (a: A) => I.IO ) => (ma: IOEither) => I.IO ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C ) => (ma: IOEither) => I.IO ``` Added in v2.10.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => IOEither): (ma: IOEither) => IOEither (ma: IOEither, f: (a: A) => IOEither): IOEither } ``` Added in v2.14.0 ## flatMapEither **Signature** ```ts export declare const flatMapEither: { (f: (a: A) => E.Either): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => E.Either): IOEither } ``` Added in v2.15.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => I.IO): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => I.IO): IOEither } ``` Added in v2.16.0 ## flatMapNullable **Signature** ```ts export declare const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: IOEither ) => IOEither> (self: IOEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): IOEither< E1 | E2, NonNullable > } ``` Added in v2.15.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => Option, onNone: (a: A) => E2): IOEither } ``` Added in v2.15.0 ## flatten **Signature** ```ts export declare const flatten: (mma: IOEither>) => IOEither ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const flattenW: (mma: IOEither>) => IOEither ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly IOEither[]) => IOEither ``` Added in v2.9.0 ## sequenceSeqArray Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. **Signature** ```ts export declare const sequenceSeqArray: (arr: readonly IOEither[]) => IOEither ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => IOEither ) => (as: readonly A[]) => IOEither ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: readonly A[]) => IOEither ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: readonly A[]) => IOEither ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( f: (index: number, a: A) => IOEither ) => (as: readonly A[]) => IOEither ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: ReadonlyNonEmptyArray) => IOEither> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( f: (index: number, a: A) => IOEither ) => (as: ReadonlyNonEmptyArray) => IOEither> ``` Added in v2.11.0 ## traverseSeqArray Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArray: ( f: (a: A) => IOEither ) => (as: readonly A[]) => IOEither ``` Added in v2.9.0 ## traverseSeqArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: readonly A[]) => IOEither ``` Added in v2.9.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'IOEither' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: IOEither ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: IOEither) => (fab: IOEither B>) => IOEither ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: IOEither) => (first: IOEither) => IOEither ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apFirstW: ( second: IOEither ) => (first: IOEither) => IOEither ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: IOEither) => (first: IOEither) => IOEither ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apSecondW: ( second: IOEither ) => (first: IOEither) => IOEither ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apW: ( fa: IOEither ) => (fab: IOEither B>) => IOEither ``` Added in v2.8.0 ## bracket Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of whether the body action throws (\*) or returns. (\*) i.e. returns a `Left` **Signature** ```ts export declare const bracket: ( acquire: IOEither, use: (a: A) => IOEither, release: (a: A, e: E.Either) => IOEither ) => IOEither ``` Added in v2.0.0 ## bracketW Less strict version of [`bracket`](#bracket). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const bracketW: ( acquire: IOEither, use: (a: A) => IOEither, release: (a: A, e: E.Either) => IOEither ) => IOEither ``` Added in v2.12.0 ## swap **Signature** ```ts export declare const swap: (ma: IOEither) => IOEither ``` Added in v2.0.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => IOEither ``` Added in v2.7.0 # zone of death ## ~~Applicative~~ Use [`ApplicativePar`](#applicativepar) instead **Signature** ```ts export declare const Applicative: Applicative2<'IOEither'> ``` Added in v2.7.0 ## ~~getApplyMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getApplyMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getApplySemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getApplySemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getIOValidation~~ Use [`getApplicativeIOValidation`](#getapplicativeiovalidation) and [`getAltIOValidation`](#getaltiovalidation). **Signature** ```ts export declare function getIOValidation( SE: Semigroup ): Monad2C & Bifunctor2 & Alt2C & MonadIO2C & MonadThrow2C ``` Added in v2.0.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~ioEither~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `IOE.Functor` instead of `IOE.ioEither` (where `IOE` is from `import IOE from 'fp-ts/IOEither'`) **Signature** ```ts export declare const ioEither: Monad2<'IOEither'> & Bifunctor2<'IOEither'> & Alt2<'IOEither'> & MonadIO2<'IOEither'> & MonadThrow2<'IOEither'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/IOOption.ts.md ================================================ --- title: IOOption.ts nav_order: 52 parent: Modules --- ## IOOption overview `IOOption` represents a synchronous computation that either yields a value of type `A` or nothing. If you want to represent a synchronous computation that never fails, please see `IO`. If you want to represent a synchronous computation that may fail, please see `IOEither`. Added in v2.12.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapIO](#tapio) - [constructors](#constructors) - [none](#none) - [of](#of) - [some](#some) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromIOEither](#fromioeither) - [fromNullable](#fromnullable) - [fromOption](#fromoption) - [toNullable](#tonullable) - [toUndefined](#toundefined) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [guard](#guard) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [instances](#instances) - [Alt](#alt) - [Alternative](#alternative) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [Compactable](#compactable) - [Filterable](#filterable) - [FromEither](#fromeither) - [FromIO](#fromio) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [Pointed](#pointed) - [Zero](#zero) - [legacy](#legacy) - [chain](#chain) - [chainEitherK](#chaineitherk) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstIOK](#chainfirstiok) - [chainIOK](#chainiok) - [chainNullableK](#chainnullablek) - [chainOptionK](#chainoptionk) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromIOK](#fromiok) - [fromNullableK](#fromnullablek) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [IOOption (interface)](#iooption-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapEither](#flatmapeither) - [flatMapIO](#flatmapio) - [flatMapNullable](#flatmapnullable) - [flatMapOption](#flatmapoption) - [flatten](#flatten) - [traversing](#traversing) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [zero](#zero) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: IOOption
, f: (a: A) => IOOption<_>): IOOption (f: (a: A) => IOOption<_>): (self: IOOption) => IOOption } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => Either): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => Either): IOOption } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as IOO from 'fp-ts/IOOption' import * as O from 'fp-ts/Option' import * as E from 'fp-ts/Either' const compute = (value: number) => pipe( IOO.of(value), IOO.tapEither((value) => (value > 0 ? E.right('ok') : E.left('error'))) ) assert.deepStrictEqual(compute(1)(), O.of(1)) assert.deepStrictEqual(compute(-1)(), O.none) ``` Added in v2.16.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => I.IO<_>): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => I.IO<_>): IOOption } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as IOO from 'fp-ts/IOOption' import * as O from 'fp-ts/Option' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effectA = pipe( IOO.of('fp-ts'), IOO.tapIO((value) => Console.log(`Hello, ${value}`)) ) // No output to the stdout const effectB = pipe( IOO.none as IOO.IOOption, IOO.tapIO((value) => Console.log(`Hello, ${value}`)) ) async function test() { assert.deepStrictEqual(effectA(), O.of('fp-ts')) assert.deepStrictEqual(effectB(), O.none) } test() ``` Added in v2.16.0 # constructors ## none **Signature** ```ts export declare const none: IOOption ``` Added in v2.12.0 ## of **Signature** ```ts export declare const of: (a: A) => IOOption ``` Added in v2.12.0 ## some **Signature** ```ts export declare const some: (a: A) => IOOption ``` Added in v2.12.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: Either) => IOOption ``` Added in v2.12.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: I.IO) => IOOption ``` Added in v2.12.0 ## fromIOEither **Signature** ```ts export declare const fromIOEither: (fa: IOEither) => IOOption ``` Added in v2.12.0 ## fromNullable **Signature** ```ts export declare const fromNullable: (a: A) => IOOption> ``` Added in v2.12.0 ## fromOption **Signature** ```ts export declare const fromOption: (fa: O.Option) => IOOption ``` Added in v2.12.0 ## toNullable **Signature** ```ts export declare const toNullable: (ma: IOOption) => I.IO ``` Added in v2.12.0 ## toUndefined **Signature** ```ts export declare const toUndefined: (ma: IOOption) => I.IO ``` Added in v2.12.0 # do notation ## Do **Signature** ```ts export declare const Do: IOOption<{}> ``` Added in v2.12.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: IOOption ) => (fa: IOOption) => IOOption<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.12.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => IOOption ) => (ma: IOOption) => IOOption<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.12.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: IOOption) => IOOption<{ readonly [K in N]: A }> ``` Added in v2.12.0 ## guard **Signature** ```ts export declare const guard: (b: boolean) => IOOption ``` Added in v2.12.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: IOOption) => IOOption<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # error handling ## alt **Signature** ```ts export declare const alt: (second: LazyArg>) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (second: LazyArg>) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## getOrElse **Signature** ```ts export declare const getOrElse: (onNone: LazyArg>) => (fa: IOOption) => I.IO ``` Added in v2.12.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: (onNone: LazyArg>) => (ma: IOOption) => I.IO ``` Added in v2.12.0 # filtering ## compact **Signature** ```ts export declare const compact: (fa: IOOption>) => IOOption ``` Added in v2.12.0 ## filter **Signature** ```ts export declare const filter: { (refinement: Refinement): (fb: IOOption) => IOOption (predicate: Predicate): (fb: IOOption) => IOOption (predicate: Predicate): (fa: IOOption) => IOOption } ``` Added in v2.12.0 ## filterMap **Signature** ```ts export declare const filterMap: (f: (a: A) => O.Option) => (fga: IOOption) => IOOption ``` Added in v2.12.0 ## partition **Signature** ```ts export declare const partition: { (refinement: Refinement): (fb: IOOption) => Separated, IOOption> (predicate: Predicate): (fb: IOOption) => Separated, IOOption> (predicate: Predicate): (fa: IOOption) => Separated, IOOption> } ``` Added in v2.12.0 ## partitionMap **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: IOOption) => Separated, IOOption> ``` Added in v2.12.0 ## separate **Signature** ```ts export declare const separate: (fa: IOOption>) => Separated, IOOption> ``` Added in v2.12.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'IOOption'> ``` Added in v2.12.0 ## Alternative **Signature** ```ts export declare const Alternative: Alternative1<'IOOption'> ``` Added in v2.12.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'IOOption'> ``` Added in v2.12.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'IOOption'> ``` Added in v2.12.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain1<'IOOption'> ``` Added in v2.12.0 ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'IOOption'> ``` Added in v2.12.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'IOOption'> ``` Added in v2.12.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither1<'IOOption'> ``` Added in v2.12.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO1<'IOOption'> ``` Added in v2.12.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'IOOption'> ``` Added in v2.12.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'IOOption'> ``` Added in v2.12.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO1<'IOOption'> ``` Added in v2.12.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'IOOption'> ``` Added in v2.12.0 ## Zero **Signature** ```ts export declare const Zero: Zero1<'IOOption'> ``` Added in v2.12.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => IOOption) => (ma: IOOption) => IOOption ``` Added in v2.12.0 ## chainEitherK Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherK: (f: (a: A) => Either) => (ma: IOOption) => IOOption ``` Added in v2.12.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => IOOption) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: (f: (a: A) => Either) => (ma: IOOption) => IOOption ``` Added in v2.12.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => I.IO) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => I.IO) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## chainNullableK Alias of `flatMapNullable`. **Signature** ```ts export declare const chainNullableK: ( f: (a: A) => B | null | undefined ) => (ma: IOOption) => IOOption> ``` Added in v2.12.0 ## chainOptionK Alias of `flatMapOption`. **Signature** ```ts export declare const chainOptionK: (f: (a: A) => O.Option) => (ma: IOOption) => IOOption ``` Added in v2.12.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => Either ) => (...a: A) => IOOption ``` Added in v2.12.0 ## fromIOK **Signature** ```ts export declare const fromIOK: (f: (...a: A) => I.IO) => (...a: A) => IOOption ``` Added in v2.12.0 ## fromNullableK **Signature** ```ts export declare const fromNullableK: ( f: (...a: A) => B | null | undefined ) => (...a: A) => IOOption> ``` Added in v2.12.0 ## fromOptionK **Signature** ```ts export declare const fromOptionK: ( f: (...a: A) => O.Option ) => (...a: A) => IOOption ``` Added in v2.12.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement): (a: A) => IOOption (predicate: Predicate): (b: B) => IOOption (predicate: Predicate): (a: A) => IOOption } ``` Added in v2.12.0 # mapping ## as Maps the `Some` value of this `IOOption` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): <_>(self: IOOption<_>) => IOOption <_, A>(self: IOOption<_>, a: A): IOOption } ``` Added in v2.16.0 ## asUnit Maps the `Some` value of this `IOOption` to the void constant value. **Signature** ```ts export declare const asUnit: <_>(self: IOOption<_>) => IOOption ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: IOOption<(a: A) => B>) => IOOption ``` Added in v2.12.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: IOOption) => IOOption ``` Added in v2.12.0 # model ## IOOption (interface) **Signature** ```ts export interface IOOption extends IO> {} ``` Added in v2.12.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: (onNone: () => I.IO, onSome: (a: A) => I.IO) => (ma: IOOption) => I.IO ``` Added in v2.12.0 ## match **Signature** ```ts export declare const match: (onNone: () => B, onSome: (a: A) => B) => (ma: IOOption) => I.IO ``` Added in v2.12.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`IO`). **Signature** ```ts export declare const matchE: (onNone: () => I.IO, onSome: (a: A) => I.IO) => (ma: IOOption) => I.IO ``` Added in v2.12.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onNone: () => I.IO, onSome: (a: A) => I.IO ) => (ma: IOOption) => I.IO ``` Added in v2.12.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: (onNone: () => B, onSome: (a: A) => C) => (ma: IOOption) => I.IO ``` Added in v2.12.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => IOOption): (ma: IOOption) => IOOption (ma: IOOption, f: (a: A) => IOOption): IOOption } ``` Added in v2.14.0 ## flatMapEither **Signature** ```ts export declare const flatMapEither: { (f: (a: A) => Either<_, B>): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => Either<_, B>): IOOption } ``` Added in v2.16.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => I.IO): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => I.IO): IOOption } ``` Added in v2.16.0 ## flatMapNullable **Signature** ```ts export declare const flatMapNullable: { (f: (a: A) => B | null | undefined): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => B | null | undefined): IOOption } ``` Added in v2.16.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => O.Option): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => O.Option): IOOption } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: IOOption>) => IOOption ``` Added in v2.12.0 # traversing ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => IOOption ) => (as: readonly A[]) => IOOption ``` Added in v2.12.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => IOOption ) => (as: ReadonlyNonEmptyArray) => IOOption> ``` Added in v2.12.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'IOOption' ``` Added in v2.12.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.12.0 # utils ## ApT **Signature** ```ts export declare const ApT: IOOption ``` Added in v2.12.0 ## ap **Signature** ```ts export declare const ap: (fa: IOOption) => (fab: IOOption<(a: A) => B>) => IOOption ``` Added in v2.12.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: IOOption) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: IOOption) => (first: IOOption) => IOOption ``` Added in v2.12.0 ## zero **Signature** ```ts export declare const zero: () => IOOption ``` Added in v2.12.0 ================================================ FILE: docs/modules/IORef.ts.md ================================================ --- title: IORef.ts nav_order: 53 parent: Modules --- ## IORef overview Mutable references in the `IO` monad Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [newIORef](#newioref) - [model](#model) - [IORef (class)](#ioref-class) - [write (method)](#write-method) - [modify (method)](#modify-method) - [read (property)](#read-property) --- # constructors ## newIORef **Signature** ```ts export declare function newIORef
(a: A): IO> ``` Added in v2.0.0 # model ## IORef (class) **Signature** ```ts export declare class IORef { constructor(private value: A) } ``` **Example** ```ts import { flatMap } from 'fp-ts/IO' import { newIORef } from 'fp-ts/IORef' assert.strictEqual(flatMap(newIORef(1), (ref) => flatMap(ref.write(2), () => ref.read))(), 2) ``` Added in v2.0.0 ### write (method) **Signature** ```ts write(a: A): IO ``` Added in v2.0.0 ### modify (method) **Signature** ```ts modify(f: (a: A) => A): IO ``` Added in v2.0.0 ### read (property) **Signature** ```ts readonly read: IO ``` Added in v2.0.0 ================================================ FILE: docs/modules/Identity.ts.md ================================================ --- title: Identity.ts nav_order: 47 parent: Modules --- ## Identity overview Added in v2.0.0 ---

Table of contents

- [Extract](#extract) - [extract](#extract) - [combinators](#combinators) - [tap](#tap) - [constructors](#constructors) - [of](#of) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Alt](#alt) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [ChainRec](#chainrec) - [Comonad](#comonad) - [Foldable](#foldable) - [Functor](#functor) - [Monad](#monad) - [Pointed](#pointed) - [Traversable](#traversable) - [getEq](#geteq) - [getShow](#getshow) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [Identity (type alias)](#identity-type-alias) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatten](#flatten) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [duplicate](#duplicate) - [extend](#extend) - [zone of death](#zone-of-death) - [~~identity~~](#identity) --- # Extract ## extract **Signature** ```ts export declare const extract:
(wa: A) => A ``` Added in v2.6.2 # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: A, f: (a: A) => _): A; (f: (a: A) => _): (self: A) => A } ``` Added in v2.16.7 # constructors ## of **Signature** ```ts export declare const of: (a: A) => A ``` Added in v2.0.0 # do notation ## Do **Signature** ```ts export declare const Do: {} ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: B ) => (fa: A) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B } ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => B ) => (ma: A) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B } ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: A) => { readonly [K in N]: A } ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: A) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B } ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. **Signature** ```ts export declare const alt: (that: () => A) => (fa: A) => A ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (that: () => B) => (fa: A) => B | A ``` Added in v2.9.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: A) => M ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: A) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: A) => B ``` Added in v2.0.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'Identity'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'Identity'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'Identity'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: Chain1<'Identity'> ``` Added in v2.10.0 ## ChainRec **Signature** ```ts export declare const ChainRec: ChainRec1<'Identity'> ``` Added in v2.7.0 ## Comonad **Signature** ```ts export declare const Comonad: Comonad1<'Identity'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'Identity'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'Identity'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'Identity'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'Identity'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'Identity'> ``` Added in v2.7.0 ## getEq **Signature** ```ts export declare const getEq: (E: Eq) => Eq ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare const getShow: (S: Show) => Show ``` Added in v2.0.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => B) => (ma: A) => B ``` Added in v2.0.0 ## chainFirst Alias of `tap` **Signature** ```ts export declare const chainFirst: (f: (a: A) => B) => (first: A) => A ``` Added in v2.0.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: (a: A) => B) => B ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: A) => B ``` Added in v2.0.0 # model ## Identity (type alias) **Signature** ```ts export type Identity = A ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => B): (ma: A) => B; (ma: A, f: (a: A) => B): B } ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: A) => A ``` Added in v2.0.0 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence1<'Identity'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse1<'Identity'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Identity' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ap **Signature** ```ts export declare const ap: (fa: A) => (fab: (a: A) => B) => B ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: B) => (first: A) => A ``` Added in v2.0.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: B) => (first: A) => B ``` Added in v2.0.0 ## duplicate **Signature** ```ts export declare const duplicate: (ma: A) => A ``` Added in v2.0.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: A) => B) => (wa: A) => B ``` Added in v2.0.0 # zone of death ## ~~identity~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `I.Functor` instead of `I.identity` (where `I` is from `import I from 'fp-ts/Identity'`) **Signature** ```ts export declare const identity: Monad1<'Identity'> & Foldable1<'Identity'> & Traversable1<'Identity'> & Alt1<'Identity'> & Comonad1<'Identity'> & ChainRec1<'Identity'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Invariant.ts.md ================================================ --- title: Invariant.ts nav_order: 49 parent: Modules --- ## Invariant overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Invariant (interface)](#invariant-interface) - [Invariant1 (interface)](#invariant1-interface) - [Invariant2 (interface)](#invariant2-interface) - [Invariant2C (interface)](#invariant2c-interface) - [Invariant3 (interface)](#invariant3-interface) - [Invariant3C (interface)](#invariant3c-interface) - [Invariant4 (interface)](#invariant4-interface) --- # model ## Invariant (interface) **Signature** ```ts export interface Invariant { readonly URI: F readonly imap: (fa: HKT, f: (a: A) => B, g: (b: B) => A) => HKT } ``` Added in v2.0.0 ## Invariant1 (interface) **Signature** ```ts export interface Invariant1 { readonly URI: F readonly imap: (fa: Kind, f: (a: A) => B, g: (b: B) => A) => Kind } ``` Added in v2.0.0 ## Invariant2 (interface) **Signature** ```ts export interface Invariant2 { readonly URI: F readonly imap: (fa: Kind2, f: (a: A) => B, g: (b: B) => A) => Kind2 } ``` Added in v2.0.0 ## Invariant2C (interface) **Signature** ```ts export interface Invariant2C { readonly URI: F readonly _E: E readonly imap: (fa: Kind2, f: (a: A) => B, g: (b: B) => A) => Kind2 } ``` Added in v2.0.0 ## Invariant3 (interface) **Signature** ```ts export interface Invariant3 { readonly URI: F readonly imap: (fa: Kind3, f: (a: A) => B, g: (b: B) => A) => Kind3 } ``` Added in v2.0.0 ## Invariant3C (interface) **Signature** ```ts export interface Invariant3C { readonly URI: F readonly _E: E readonly imap: (fa: Kind3, f: (a: A) => B, g: (b: B) => A) => Kind3 } ``` Added in v2.4.2 ## Invariant4 (interface) **Signature** ```ts export interface Invariant4 { readonly URI: F readonly imap: (fa: Kind4, f: (a: A) => B, g: (b: B) => A) => Kind4 } ``` Added in v2.4.2 ================================================ FILE: docs/modules/JoinSemilattice.ts.md ================================================ --- title: JoinSemilattice.ts nav_order: 54 parent: Modules --- ## JoinSemilattice overview A join-semilattice (or upper semilattice) is a semilattice whose operation is called `join`, and which can be thought of as a least upper bound. A `JoinSemilattice` must satisfy the following laws: - Associativity: `a ∨ (b ∨ c) <-> (a ∨ b) ∨ c` - Commutativity: `a ∨ b <-> b ∨ a` - Idempotency: `a ∨ a <-> a` Added in v2.0.0 ---

Table of contents

- [model](#model) - [JoinSemilattice (interface)](#joinsemilattice-interface) --- # model ## JoinSemilattice (interface) **Signature** ```ts export interface JoinSemilattice
{ readonly join: (x: A, y: A) => A } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Json.ts.md ================================================ --- title: Json.ts nav_order: 55 parent: Modules --- ## Json overview Added in v2.10.0 ---

Table of contents

- [utils](#utils) - [Json (type alias)](#json-type-alias) - [JsonArray (interface)](#jsonarray-interface) - [JsonRecord (interface)](#jsonrecord-interface) - [parse](#parse) - [stringify](#stringify) --- # utils ## Json (type alias) **Signature** ```ts export type Json = boolean | number | string | null | JsonArray | JsonRecord ``` Added in v2.10.0 ## JsonArray (interface) **Signature** ```ts export interface JsonArray extends ReadonlyArray {} ``` Added in v2.10.0 ## JsonRecord (interface) **Signature** ```ts export interface JsonRecord { readonly [key: string]: Json } ``` Added in v2.10.0 ## parse Converts a JavaScript Object Notation (JSON) string into a `Json` type. **Signature** ```ts export declare const parse: (s: string) => Either ``` **Example** ```ts import * as J from 'fp-ts/Json' import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('{"a":1}', J.parse), E.right({ a: 1 })) assert.deepStrictEqual( pipe('{"a":}', J.parse), E.left(new SyntaxError(`Unexpected token '}', "{"a":}" is not valid JSON`)) ) ``` Added in v2.10.0 ## stringify Converts a JavaScript value to a JavaScript Object Notation (JSON) string. **Signature** ```ts export declare const stringify:
(a: A) => Either ``` **Example** ```ts import * as E from 'fp-ts/Either' import * as J from 'fp-ts/Json' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(J.stringify({ a: 1 }), E.right('{"a":1}')) const circular: any = { ref: null } circular.ref = circular assert.deepStrictEqual( pipe( J.stringify(circular), E.mapLeft((e) => e instanceof Error && e.message.includes('Converting circular structure to JSON')) ), E.left(true) ) ``` Added in v2.10.0 ================================================ FILE: docs/modules/Lattice.ts.md ================================================ --- title: Lattice.ts nav_order: 56 parent: Modules --- ## Lattice overview A `Lattice` must satisfy the following in addition to `JoinSemilattice` and `MeetSemilattice` laws: - Absorbtion law for meet: `a ∧ (a ∨ b) <-> a` - Absorbtion law for join: `a ∨ (a ∧ b) <-> a` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Lattice (interface)](#lattice-interface) --- # model ## Lattice (interface) **Signature** ```ts export interface Lattice
extends JoinSemilattice, MeetSemilattice {} ``` Added in v2.0.0 ================================================ FILE: docs/modules/Magma.ts.md ================================================ --- title: Magma.ts nav_order: 57 parent: Modules --- ## Magma overview A `Magma` is a pair `(A, concat)` in which `A` is a non-empty set and `concat` is a binary operation on `A` See [Semigroup](https://gcanti.github.io/fp-ts/modules/Semigroup.ts.html) for some instances. Added in v2.0.0 ---

Table of contents

- [model](#model) - [Magma (interface)](#magma-interface) - [utils](#utils) - [concatAll](#concatall) - [endo](#endo) - [filterFirst](#filterfirst) - [filterSecond](#filtersecond) - [reverse](#reverse) --- # model ## Magma (interface) **Signature** ```ts export interface Magma
{ readonly concat: (x: A, y: A) => A } ``` Added in v2.0.0 # utils ## concatAll Given a sequence of `as`, concat them and return the total. If `as` is empty, return the provided `startWith` value. **Signature** ```ts export declare const concatAll: (M: Magma) => (startWith: A) => (as: readonly A[]) => A ``` **Example** ```ts import { concatAll } from 'fp-ts/Magma' import * as N from 'fp-ts/number' const subAll = concatAll(N.MagmaSub)(0) assert.deepStrictEqual(subAll([1, 2, 3]), -6) ``` Added in v2.11.0 ## endo **Signature** ```ts export declare const endo: (f: Endomorphism) => (M: Magma) => Magma ``` Added in v2.11.0 ## filterFirst **Signature** ```ts export declare const filterFirst: (predicate: Predicate) => (M: Magma) => Magma ``` Added in v2.11.0 ## filterSecond **Signature** ```ts export declare const filterSecond: (predicate: Predicate) => (M: Magma) => Magma ``` Added in v2.11.0 ## reverse The dual of a `Magma`, obtained by swapping the arguments of `concat`. **Signature** ```ts export declare const reverse: (M: Magma) => Magma ``` **Example** ```ts import { reverse, concatAll } from 'fp-ts/Magma' import * as N from 'fp-ts/number' const subAll = concatAll(reverse(N.MagmaSub))(0) assert.deepStrictEqual(subAll([1, 2, 3]), 2) ``` Added in v2.11.0 ================================================ FILE: docs/modules/Map.ts.md ================================================ --- title: Map.ts nav_order: 58 parent: Modules --- ## Map overview Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [fromFoldable](#fromfoldable) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [getFilterableWithIndex](#getfilterablewithindex) - [getWitherable](#getwitherable) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [folding](#folding) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [getFoldable](#getfoldable) - [getFoldableWithIndex](#getfoldablewithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [instances](#instances) - [Compactable](#compactable) - [Filterable](#filterable) - [Functor](#functor) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getMonoid](#getmonoid) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [mapWithIndex](#mapwithindex) - [traversing](#traversing) - [getTraversableWithIndex](#gettraversablewithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [collect](#collect) - [deleteAt](#deleteat) - [difference](#difference) - [elem](#elem) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [intersection](#intersection) - [isEmpty](#isempty) - [isSubmap](#issubmap) - [keys](#keys) - [lookup](#lookup) - [lookupWithKey](#lookupwithkey) - [member](#member) - [modifyAt](#modifyat) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [pop](#pop) - [singleton](#singleton) - [size](#size) - [toArray](#toarray) - [toUnfoldable](#tounfoldable) - [union](#union) - [updateAt](#updateat) - [upsertAt](#upsertat) - [values](#values) - [zone of death](#zone-of-death) - [~~empty~~](#empty) - [~~insertAt~~](#insertat) - [~~map\_~~](#map_) --- # constructors ## fromFoldable Create a map from a foldable collection of key/value pairs, using the specified `Magma` to combine values for duplicate keys. **Signature** ```ts export declare function fromFoldable( E: Eq, M: Magma
, F: Foldable3 ): (fka: Kind3) => Map export declare function fromFoldable( E: Eq, M: Magma, F: Foldable2 ): (fka: Kind2) => Map export declare function fromFoldable( E: Eq, M: Magma, F: Foldable1 ): (fka: Kind) => Map export declare function fromFoldable(E: Eq, M: Magma, F: Foldable): (fka: HKT) => Map ``` Added in v2.0.0 # filtering ## compact **Signature** ```ts export declare const compact: (fa: Map>) => Map ``` Added in v2.0.0 ## filter **Signature** ```ts export declare const filter: { (refinement: Refinement): (fa: Map) => Map (predicate: Predicate): (fb: Map) => Map (predicate: Predicate): (fa: Map) => Map } ``` Added in v2.0.0 ## filterMap **Signature** ```ts export declare const filterMap: (f: (a: A) => O.Option) => (fa: Map) => Map ``` Added in v2.0.0 ## getFilterableWithIndex **Signature** ```ts export declare function getFilterableWithIndex(): FilterableWithIndex2C ``` Added in v2.0.0 ## getWitherable **Signature** ```ts export declare function getWitherable(O: Ord): Witherable2C & TraversableWithIndex2C ``` Added in v2.0.0 ## partition **Signature** ```ts export declare const partition: { (refinement: Refinement): (fa: Map) => Separated, Map> (predicate: Predicate): (fb: Map) => Separated, Map> (predicate: Predicate): (fa: Map) => Separated, Map> } ``` Added in v2.0.0 ## partitionMap **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: Map) => Separated, Map> ``` Added in v2.0.0 ## separate **Signature** ```ts export declare const separate: (fa: Map>) => Separated, Map> ``` Added in v2.0.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (O: Ord) => (M: Monoid) => (f: (a: A) => M) => (m: Map) => M ``` Added in v2.11.0 ## foldMapWithIndex **Signature** ```ts export declare const foldMapWithIndex: ( O: Ord ) => (M: Monoid) => (f: (k: K, a: A) => M) => (m: Map) => M ``` Added in v2.11.0 ## getFoldable **Signature** ```ts export declare const getFoldable: (O: Ord) => Foldable2C<'Map', K> ``` Added in v2.11.0 ## getFoldableWithIndex **Signature** ```ts export declare const getFoldableWithIndex: (O: Ord) => FoldableWithIndex2C<'Map', K, K> ``` Added in v2.10.0 ## reduce **Signature** ```ts export declare const reduce: (O: Ord) => (b: B, f: (b: B, a: A) => B) => (m: Map) => B ``` Added in v2.11.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (O: Ord) => (b: B, f: (a: A, b: B) => B) => (m: Map) => B ``` Added in v2.11.0 ## reduceRightWithIndex **Signature** ```ts export declare const reduceRightWithIndex: ( O: Ord ) => (b: B, f: (k: K, a: A, b: B) => B) => (m: Map) => B ``` Added in v2.11.0 ## reduceWithIndex **Signature** ```ts export declare const reduceWithIndex: (O: Ord) => (b: B, f: (k: K, b: B, a: A) => B) => (m: Map) => B ``` Added in v2.11.0 # instances ## Compactable **Signature** ```ts export declare const Compactable: Compactable2<'Map'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable2<'Map'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Map'> ``` Added in v2.7.0 ## getDifferenceMagma **Signature** ```ts export declare const getDifferenceMagma: (E: Eq) => () => Magma> ``` Added in v2.11.0 ## getEq **Signature** ```ts export declare const getEq: (SK: Eq, SA: Eq) => Eq> ``` Added in v2.0.0 ## getIntersectionSemigroup **Signature** ```ts export declare const getIntersectionSemigroup: (E: Eq, S: Semigroup) => Semigroup> ``` Added in v2.11.0 ## getMonoid Gets `Monoid` instance for Maps given `Semigroup` instance for their values **Signature** ```ts export declare function getMonoid(SK: Eq, SA: Semigroup): Monoid> ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare const getShow: (SK: Show, SA: Show) => Show> ``` Added in v2.0.0 ## getUnionMonoid **Signature** ```ts export declare const getUnionMonoid: (E: Eq, S: Semigroup) => Monoid> ``` Added in v2.11.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq, S: Semigroup) => Semigroup> ``` Added in v2.11.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Map B>) => Map ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Map) => Map ``` Added in v2.0.0 ## mapWithIndex **Signature** ```ts export declare const mapWithIndex: (f: (k: K, a: A) => B) => (fa: Map) => Map ``` Added in v2.7.1 # traversing ## getTraversableWithIndex **Signature** ```ts export declare const getTraversableWithIndex: (O: Ord) => TraversableWithIndex2C<'Map', K, K> ``` Added in v2.10.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Map' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## collect **Signature** ```ts export declare function collect(O: Ord): (f: (k: K, a: A) => B) => (m: Map) => Array ``` Added in v2.0.0 ## deleteAt Delete a key and value from a map **Signature** ```ts export declare const deleteAt: (E: Eq) => (k: K) => (m: Map) => Map ``` Added in v2.0.0 ## difference **Signature** ```ts export declare const difference: (E: Eq) => (_second: Map) => (first: Map) => Map ``` Added in v2.11.0 ## elem Test whether or not a value is a member of a map **Signature** ```ts export declare const elem: (E: Eq) => { (a: A): (m: Map) => boolean; (a: A, m: Map): boolean } ``` Added in v2.0.0 ## filterMapWithIndex **Signature** ```ts export declare const filterMapWithIndex: (f: (k: K, a: A) => O.Option) => (fa: Map) => Map ``` Added in v2.10.0 ## filterWithIndex **Signature** ```ts export declare function filterWithIndex(p: (k: K, a: A) => a is B): (m: Map) => Map export declare function filterWithIndex(p: (k: K, a: A) => boolean): (m: Map) => Map export declare function filterWithIndex(p: (k: K, a: A) => boolean): (m: Map) => Map ``` Added in v2.10.0 ## intersection **Signature** ```ts export declare const intersection: ( E: Eq, M: Magma ) => (second: Map) => (first: Map) => Map ``` Added in v2.11.0 ## isEmpty Test whether or not a map is empty **Signature** ```ts export declare const isEmpty: (m: Map) => boolean ``` Added in v2.0.0 ## isSubmap Test whether or not one `Map` contains all of the keys and values contained in another `Map` **Signature** ```ts export declare const isSubmap: ( SK: Eq, SA: Eq ) => { (that: Map): (me: Map) => boolean; (me: Map, that: Map): boolean } ``` Added in v2.0.0 ## keys Get a sorted `Array` of the keys contained in a `Map`. **Signature** ```ts export declare const keys: (O: Ord) => (m: Map) => K[] ``` Added in v2.0.0 ## lookup Lookup the value for a key in a `Map`. **Signature** ```ts export declare const lookup: (E: Eq) => { (k: K): (m: Map) => O.Option (k: K, m: Map): O.Option } ``` Added in v2.0.0 ## lookupWithKey Lookup the value for a key in a `Map`. If the result is a `Some`, the existing key is also returned. **Signature** ```ts export declare function lookupWithKey(E: Eq): { (k: K): (m: Map) => Option<[K, A]> (k: K, m: Map): Option<[K, A]> } ``` Added in v2.0.0 ## member Test whether or not a key exists in a map **Signature** ```ts export declare const member: (E: Eq) => { (k: K): (m: Map) => boolean; (k: K, m: Map): boolean } ``` Added in v2.0.0 ## modifyAt **Signature** ```ts export declare const modifyAt: (E: Eq) => (k: K, f: (a: A) => A) => (m: Map) => O.Option> ``` Added in v2.0.0 ## partitionMapWithIndex **Signature** ```ts export declare const partitionMapWithIndex: ( f: (k: K, a: A) => Either ) => (fa: Map) => Separated, Map> ``` Added in v2.10.0 ## partitionWithIndex **Signature** ```ts export declare function partitionWithIndex( predicateWithIndex: (k: K, a: A) => a is B ): (fa: Map) => Separated, Map> export declare function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (fb: Map) => Separated, Map> export declare function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (fa: Map) => Separated, Map> ``` Added in v2.10.0 ## pop Delete a key and value from a map, returning the value as well as the subsequent map **Signature** ```ts export declare function pop(E: Eq): (k: K) => (m: Map) => Option<[A, Map]> ``` Added in v2.0.0 ## singleton Create a map with one key/value pair **Signature** ```ts export declare const singleton: (k: K, a: A) => Map ``` Added in v2.0.0 ## size Calculate the number of key/value pairs in a map **Signature** ```ts export declare const size: (m: Map) => number ``` Added in v2.0.0 ## toArray Get a sorted `Array` of the key/value pairs contained in a `Map`. **Signature** ```ts export declare function toArray(O: Ord): (m: Map) => Array<[K, A]> ``` Added in v2.0.0 ## toUnfoldable Unfolds a map into a list of key/value pairs **Signature** ```ts export declare function toUnfoldable( ord: Ord, U: Unfoldable1 ): (d: Map) => Kind export declare function toUnfoldable(ord: Ord, U: Unfoldable): (d: Map) => HKT ``` Added in v2.0.0 ## union **Signature** ```ts export declare const union: (E: Eq, M: Magma) => (second: Map) => (first: Map) => Map ``` Added in v2.11.0 ## updateAt **Signature** ```ts export declare const updateAt: (E: Eq) => (k: K, a: A) => (m: Map) => O.Option> ``` Added in v2.0.0 ## upsertAt Insert or replace a key/value pair in a `Map`. **Signature** ```ts export declare const upsertAt: (E: Eq) => (k: K, a: A) => (m: Map) => Map ``` Added in v2.0.0 ## values Get a sorted `Array` of the values contained in a `Map`. **Signature** ```ts export declare const values: (O: Ord) => (m: Map) => A[] ``` Added in v2.0.0 # zone of death ## ~~empty~~ Use a `new Map()` instead. **Signature** ```ts export declare const empty: Map ``` Added in v2.0.0 ## ~~insertAt~~ Use [`upsertAt`](#upsertat) instead. **Signature** ```ts export declare const insertAt: (E: Eq) => (k: K, a: A) => (m: Map) => Map ``` Added in v2.0.0 ## ~~map\_~~ Use [`Filterable`](#filterable) instead. **Signature** ```ts export declare const map_: Filterable2<'Map'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/MeetSemilattice.ts.md ================================================ --- title: MeetSemilattice.ts nav_order: 59 parent: Modules --- ## MeetSemilattice overview A meet-semilattice (or lower semilattice) is a semilattice whose operation is called `meet`, and which can be thought of as a greatest lower bound. A `MeetSemilattice` must satisfy the following laws: - Associativity: `a ∧ (b ∧ c) <-> (a ∧ b) ∧ c` - Commutativity: `a ∧ b <-> b ∧ a` - Idempotency: `a ∧ a <-> a` Added in v2.0.0 ---

Table of contents

- [model](#model) - [MeetSemilattice (interface)](#meetsemilattice-interface) --- # model ## MeetSemilattice (interface) **Signature** ```ts export interface MeetSemilattice
{ readonly meet: (x: A, y: A) => A } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Monad.ts.md ================================================ --- title: Monad.ts nav_order: 60 parent: Modules --- ## Monad overview The `Monad` type class combines the operations of the `Chain` and `Applicative` type classes. Therefore, `Monad` instances represent type constructors which support sequential composition, and also lifting of functions of arbitrary arity. Instances must satisfy the following laws in addition to the `Applicative` and `Chain` laws: 1. Left identity: `M.chain(M.of(a), f) <-> f(a)` 2. Right identity: `M.chain(fa, M.of) <-> fa` Note. `Functor`'s `map` can be derived: `A.map = (fa, f) => A.chain(fa, a => A.of(f(a)))` Added in v2.0.0 ---

Table of contents

- [model](#model) - [Monad (interface)](#monad-interface) - [Monad1 (interface)](#monad1-interface) - [Monad2 (interface)](#monad2-interface) - [Monad2C (interface)](#monad2c-interface) - [Monad3 (interface)](#monad3-interface) - [Monad3C (interface)](#monad3c-interface) - [Monad4 (interface)](#monad4-interface) --- # model ## Monad (interface) **Signature** ```ts export interface Monad extends Applicative, Chain {} ``` Added in v2.0.0 ## Monad1 (interface) **Signature** ```ts export interface Monad1 extends Applicative1, Chain1 {} ``` Added in v2.0.0 ## Monad2 (interface) **Signature** ```ts export interface Monad2 extends Applicative2, Chain2 {} ``` Added in v2.0.0 ## Monad2C (interface) **Signature** ```ts export interface Monad2C extends Applicative2C, Chain2C {} ``` Added in v2.0.0 ## Monad3 (interface) **Signature** ```ts export interface Monad3 extends Applicative3, Chain3 {} ``` Added in v2.0.0 ## Monad3C (interface) **Signature** ```ts export interface Monad3C extends Applicative3C, Chain3C {} ``` Added in v2.2.0 ## Monad4 (interface) **Signature** ```ts export interface Monad4 extends Applicative4, Chain4 {} ``` Added in v2.0.0 ================================================ FILE: docs/modules/MonadIO.ts.md ================================================ --- title: MonadIO.ts nav_order: 61 parent: Modules --- ## MonadIO overview Lift a computation from the `IO` monad Added in v2.0.0 ---

Table of contents

- [model](#model) - [MonadIO (interface)](#monadio-interface) - [MonadIO1 (interface)](#monadio1-interface) - [MonadIO2 (interface)](#monadio2-interface) - [MonadIO2C (interface)](#monadio2c-interface) - [MonadIO3 (interface)](#monadio3-interface) - [MonadIO3C (interface)](#monadio3c-interface) - [MonadIO4 (interface)](#monadio4-interface) --- # model ## MonadIO (interface) **Signature** ```ts export interface MonadIO extends Monad, FromIO {} ``` Added in v2.0.0 ## MonadIO1 (interface) **Signature** ```ts export interface MonadIO1 extends Monad1, FromIO1 {} ``` Added in v2.0.0 ## MonadIO2 (interface) **Signature** ```ts export interface MonadIO2 extends Monad2, FromIO2 {} ``` Added in v2.0.0 ## MonadIO2C (interface) **Signature** ```ts export interface MonadIO2C extends Monad2C, FromIO2C {} ``` Added in v2.0.0 ## MonadIO3 (interface) **Signature** ```ts export interface MonadIO3 extends Monad3, FromIO3 {} ``` Added in v2.0.0 ## MonadIO3C (interface) **Signature** ```ts export interface MonadIO3C extends Monad3C, FromIO3C {} ``` Added in v2.2.0 ## MonadIO4 (interface) **Signature** ```ts export interface MonadIO4 extends Monad4, FromIO4 {} ``` Added in v2.4.4 ================================================ FILE: docs/modules/MonadTask.ts.md ================================================ --- title: MonadTask.ts nav_order: 62 parent: Modules --- ## MonadTask overview Lift a computation from the `Task` monad Added in v2.0.0 ---

Table of contents

- [model](#model) - [MonadTask (interface)](#monadtask-interface) - [MonadTask1 (interface)](#monadtask1-interface) - [MonadTask2 (interface)](#monadtask2-interface) - [MonadTask2C (interface)](#monadtask2c-interface) - [MonadTask3 (interface)](#monadtask3-interface) - [MonadTask3C (interface)](#monadtask3c-interface) - [MonadTask4 (interface)](#monadtask4-interface) --- # model ## MonadTask (interface) **Signature** ```ts export interface MonadTask extends MonadIO, FromTask {} ``` Added in v2.0.0 ## MonadTask1 (interface) **Signature** ```ts export interface MonadTask1 extends MonadIO1, FromTask1 {} ``` Added in v2.0.0 ## MonadTask2 (interface) **Signature** ```ts export interface MonadTask2 extends MonadIO2, FromTask2 {} ``` Added in v2.0.0 ## MonadTask2C (interface) **Signature** ```ts export interface MonadTask2C extends MonadIO2C, FromTask2C {} ``` Added in v2.0.0 ## MonadTask3 (interface) **Signature** ```ts export interface MonadTask3 extends MonadIO3, FromTask3 {} ``` Added in v2.0.0 ## MonadTask3C (interface) **Signature** ```ts export interface MonadTask3C extends MonadIO3C, FromTask3C {} ``` Added in v2.2.0 ## MonadTask4 (interface) **Signature** ```ts export interface MonadTask4 extends MonadIO4, FromTask4 {} ``` Added in v2.4.4 ================================================ FILE: docs/modules/MonadThrow.ts.md ================================================ --- title: MonadThrow.ts nav_order: 63 parent: Modules --- ## MonadThrow overview The `MonadThrow` type class represents those monads which support errors via `throwError`, where `throwError(e)` halts, yielding the error `e`. Laws: - Left zero: `M.chain(M.throwError(e), f) = M.throwError(e)` Added in v2.0.0 ---

Table of contents

- [model](#model) - [MonadThrow (interface)](#monadthrow-interface) - [MonadThrow1 (interface)](#monadthrow1-interface) - [MonadThrow2 (interface)](#monadthrow2-interface) - [MonadThrow2C (interface)](#monadthrow2c-interface) - [MonadThrow3 (interface)](#monadthrow3-interface) - [MonadThrow3C (interface)](#monadthrow3c-interface) - [MonadThrow4 (interface)](#monadthrow4-interface) --- # model ## MonadThrow (interface) **Signature** ```ts export interface MonadThrow extends Monad { readonly throwError: (e: E) => HKT } ``` Added in v2.0.0 ## MonadThrow1 (interface) **Signature** ```ts export interface MonadThrow1 extends Monad1 { readonly throwError: (e: E) => Kind } ``` Added in v2.0.0 ## MonadThrow2 (interface) **Signature** ```ts export interface MonadThrow2 extends Monad2 { readonly throwError: (e: E) => Kind2 } ``` Added in v2.0.0 ## MonadThrow2C (interface) **Signature** ```ts export interface MonadThrow2C extends Monad2C { readonly throwError:
(e: E) => Kind2 } ``` Added in v2.0.0 ## MonadThrow3 (interface) **Signature** ```ts export interface MonadThrow3 extends Monad3 { readonly throwError: (e: E) => Kind3 } ``` Added in v2.0.0 ## MonadThrow3C (interface) **Signature** ```ts export interface MonadThrow3C extends Monad3C { readonly throwError: (e: E) => Kind3 } ``` Added in v2.2.0 ## MonadThrow4 (interface) **Signature** ```ts export interface MonadThrow4 extends Monad4 { readonly throwError: (e: E) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Monoid.ts.md ================================================ --- title: Monoid.ts nav_order: 64 parent: Modules --- ## Monoid overview `Monoid` extends the power of `Semigroup` by providing an additional `empty` value. ```ts interface Semigroup { readonly concat: (x: A, y: A) => A } interface Monoid extends Semigroup { readonly empty: A } ``` This `empty` value should be an identity for the `concat` operation, which means the following equalities hold for any choice of `x`. ```ts concat(x, empty) = concat(empty, x) = x ``` Many types that form a `Semigroup` also form a `Monoid`, such as `number`s (with `0`) and `string`s (with `''`). ```ts import { Monoid } from 'fp-ts/Monoid' const monoidString: Monoid = { concat: (x, y) => x + y, empty: '', } ``` _Adapted from https://typelevel.org/cats_ Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [max](#max) - [min](#min) - [model](#model) - [Monoid (interface)](#monoid-interface) - [utils](#utils) - [concatAll](#concatall) - [reverse](#reverse) - [struct](#struct) - [tuple](#tuple) - [zone of death](#zone-of-death) - [~~fold~~](#fold) - [~~getDualMonoid~~](#getdualmonoid) - [~~getEndomorphismMonoid~~](#getendomorphismmonoid) - [~~getFunctionMonoid~~](#getfunctionmonoid) - [~~getJoinMonoid~~](#getjoinmonoid) - [~~getMeetMonoid~~](#getmeetmonoid) - [~~getStructMonoid~~](#getstructmonoid) - [~~getTupleMonoid~~](#gettuplemonoid) - [~~monoidAll~~](#monoidall) - [~~monoidAny~~](#monoidany) - [~~monoidProduct~~](#monoidproduct) - [~~monoidString~~](#monoidstring) - [~~monoidSum~~](#monoidsum) - [~~monoidVoid~~](#monoidvoid) --- # constructors ## max Get a monoid where `concat` will return the maximum, based on the provided bounded order. The `empty` value is the `bottom` value. **Signature** ```ts export declare const max:
(B: Bounded) => Monoid ``` **Example** ```ts import * as N from 'fp-ts/number' import * as M from 'fp-ts/Monoid' const M1 = M.max(N.Bounded) assert.deepStrictEqual(M1.concat(1, 2), 2) ``` Added in v2.10.0 ## min Get a monoid where `concat` will return the minimum, based on the provided bounded order. The `empty` value is the `top` value. **Signature** ```ts export declare const min: (B: Bounded) => Monoid ``` **Example** ```ts import * as N from 'fp-ts/number' import * as M from 'fp-ts/Monoid' const M1 = M.min(N.Bounded) assert.deepStrictEqual(M1.concat(1, 2), 1) ``` Added in v2.10.0 # model ## Monoid (interface) **Signature** ```ts export interface Monoid extends Se.Semigroup { readonly empty: A } ``` Added in v2.0.0 # utils ## concatAll Given a sequence of `as`, concat them and return the total. If `as` is empty, return the monoid `empty` value. **Signature** ```ts export declare const concatAll: (M: Monoid) => (as: readonly A[]) => A ``` **Example** ```ts import { concatAll } from 'fp-ts/Monoid' import * as N from 'fp-ts/number' assert.deepStrictEqual(concatAll(N.MonoidSum)([1, 2, 3]), 6) assert.deepStrictEqual(concatAll(N.MonoidSum)([]), 0) ``` Added in v2.10.0 ## reverse The dual of a `Monoid`, obtained by swapping the arguments of `concat`. **Signature** ```ts export declare const reverse: (M: Monoid) => Monoid ``` **Example** ```ts import { reverse } from 'fp-ts/Monoid' import * as S from 'fp-ts/string' assert.deepStrictEqual(reverse(S.Monoid).concat('a', 'b'), 'ba') ``` Added in v2.10.0 ## struct Given a struct of monoids returns a monoid for the struct. **Signature** ```ts export declare const struct: (monoids: { [K in keyof A]: Monoid }) => Monoid<{ readonly [K in keyof A]: A[K] }> ``` **Example** ```ts import { struct } from 'fp-ts/Monoid' import * as N from 'fp-ts/number' interface Point { readonly x: number readonly y: number } const M = struct({ x: N.MonoidSum, y: N.MonoidSum, }) assert.deepStrictEqual(M.concat({ x: 1, y: 2 }, { x: 3, y: 4 }), { x: 4, y: 6 }) ``` Added in v2.10.0 ## tuple Given a tuple of monoids returns a monoid for the tuple. **Signature** ```ts export declare const tuple: ( ...monoids: { [K in keyof A]: Monoid } ) => Monoid> ``` **Example** ```ts import { tuple } from 'fp-ts/Monoid' import * as B from 'fp-ts/boolean' import * as N from 'fp-ts/number' import * as S from 'fp-ts/string' const M1 = tuple(S.Monoid, N.MonoidSum) assert.deepStrictEqual(M1.concat(['a', 1], ['b', 2]), ['ab', 3]) const M2 = tuple(S.Monoid, N.MonoidSum, B.MonoidAll) assert.deepStrictEqual(M2.concat(['a', 1, true], ['b', 2, false]), ['ab', 3, false]) ``` Added in v2.10.0 # zone of death ## ~~fold~~ Use [`concatAll`](#concatall) instead. **Signature** ```ts export declare const fold: (M: Monoid) => (as: readonly A[]) => A ``` Added in v2.0.0 ## ~~getDualMonoid~~ Use [`reverse`](#reverse) instead. **Signature** ```ts export declare const getDualMonoid: (M: Monoid) => Monoid ``` Added in v2.0.0 ## ~~getEndomorphismMonoid~~ Use [`getEndomorphismMonoid`](./function.ts.html#getendomorphismmonoid) instead. **Note**. The execution order in [`getEndomorphismMonoid`](./function.ts.html#getendomorphismmonoid) is reversed. **Signature** ```ts export declare const getEndomorphismMonoid: () => Monoid> ``` Added in v2.0.0 ## ~~getFunctionMonoid~~ Use [`getMonoid`](./function.ts.html#getmonoid) instead. **Signature** ```ts export declare const getFunctionMonoid: (M: Monoid) => () => Monoid<(a: A) => M> ``` Added in v2.0.0 ## ~~getJoinMonoid~~ Use [`max`](#max) instead. **Signature** ```ts export declare const getJoinMonoid: (B: Bounded) => Monoid ``` Added in v2.0.0 ## ~~getMeetMonoid~~ Use [`min`](#min) instead. **Signature** ```ts export declare const getMeetMonoid: (B: Bounded) => Monoid ``` Added in v2.0.0 ## ~~getStructMonoid~~ Use [`struct`](#struct) instead. **Signature** ```ts export declare const getStructMonoid: >>(monoids: { [K in keyof O]: Monoid }) => Monoid ``` Added in v2.0.0 ## ~~getTupleMonoid~~ Use [`tuple`](#tuple) instead. **Signature** ```ts export declare const getTupleMonoid: []>( ...monoids: T ) => Monoid<{ [K in keyof T]: T[K] extends Se.Semigroup ? A : never }> ``` Added in v2.0.0 ## ~~monoidAll~~ Use [`MonoidAll`](./boolean.ts.html#monoidall) instead. **Signature** ```ts export declare const monoidAll: Monoid ``` Added in v2.0.0 ## ~~monoidAny~~ Use [`MonoidAny`](./boolean.ts.html#monoidany) instead. **Signature** ```ts export declare const monoidAny: Monoid ``` Added in v2.0.0 ## ~~monoidProduct~~ Use [`MonoidProduct`](./number.ts.html#monoidproduct) instead. **Signature** ```ts export declare const monoidProduct: Monoid ``` Added in v2.0.0 ## ~~monoidString~~ Use [`Monoid`](./string.ts.html#monoid) instead. **Signature** ```ts export declare const monoidString: Monoid ``` Added in v2.0.0 ## ~~monoidSum~~ Use [`MonoidSum`](./number.ts.html#monoidsum) instead. **Signature** ```ts export declare const monoidSum: Monoid ``` Added in v2.0.0 ## ~~monoidVoid~~ Use [`Monoid`](./void.ts.html#monoid) instead. **Signature** ```ts export declare const monoidVoid: Monoid ``` Added in v2.0.0 ================================================ FILE: docs/modules/NaturalTransformation.ts.md ================================================ --- title: NaturalTransformation.ts nav_order: 65 parent: Modules --- ## NaturalTransformation overview A type for natural transformations. A natural transformation is a mapping between type constructors of kind `* -> *` where the mapping operation has no ability to manipulate the inner values. The definition of a natural transformation in category theory states that `F` and `G` should be functors, but the `Functor` constraint is not enforced here; that the types are of kind `* -> *` is enough for our purposes. Added in v2.11.0 ---

Table of contents

- [utils](#utils) - [NaturalTransformation (interface)](#naturaltransformation-interface) - [NaturalTransformation11 (interface)](#naturaltransformation11-interface) - [NaturalTransformation12 (interface)](#naturaltransformation12-interface) - [NaturalTransformation12C (interface)](#naturaltransformation12c-interface) - [NaturalTransformation13 (interface)](#naturaltransformation13-interface) - [NaturalTransformation13C (interface)](#naturaltransformation13c-interface) - [NaturalTransformation14 (interface)](#naturaltransformation14-interface) - [NaturalTransformation14C (interface)](#naturaltransformation14c-interface) - [NaturalTransformation21 (interface)](#naturaltransformation21-interface) - [NaturalTransformation22 (interface)](#naturaltransformation22-interface) - [NaturalTransformation22C (interface)](#naturaltransformation22c-interface) - [NaturalTransformation23 (interface)](#naturaltransformation23-interface) - [NaturalTransformation23C (interface)](#naturaltransformation23c-interface) - [NaturalTransformation23R (interface)](#naturaltransformation23r-interface) - [NaturalTransformation23RC (interface)](#naturaltransformation23rc-interface) - [NaturalTransformation24 (interface)](#naturaltransformation24-interface) - [NaturalTransformation24R (interface)](#naturaltransformation24r-interface) - [NaturalTransformation24S (interface)](#naturaltransformation24s-interface) - [NaturalTransformation33 (interface)](#naturaltransformation33-interface) - [NaturalTransformation34 (interface)](#naturaltransformation34-interface) --- # utils ## NaturalTransformation (interface) **Signature** ```ts export interface NaturalTransformation {
(fa: HKT): HKT } ``` Added in v2.11.0 ## NaturalTransformation11 (interface) **Signature** ```ts export interface NaturalTransformation11 { (fa: Kind): Kind } ``` Added in v2.11.0 ## NaturalTransformation12 (interface) **Signature** ```ts export interface NaturalTransformation12 { (fa: Kind): Kind2 } ``` Added in v2.11.0 ## NaturalTransformation12C (interface) **Signature** ```ts export interface NaturalTransformation12C { (fa: Kind): Kind2 } ``` Added in v2.11.0 ## NaturalTransformation13 (interface) **Signature** ```ts export interface NaturalTransformation13 { (fa: Kind): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation13C (interface) **Signature** ```ts export interface NaturalTransformation13C { (fa: Kind): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation14 (interface) **Signature** ```ts export interface NaturalTransformation14 { (fa: Kind): Kind4 } ``` Added in v2.11.0 ## NaturalTransformation14C (interface) **Signature** ```ts export interface NaturalTransformation14C { (fa: Kind): Kind4 } ``` Added in v2.11.0 ## NaturalTransformation21 (interface) **Signature** ```ts export interface NaturalTransformation21 { (fa: Kind2): Kind } ``` Added in v2.11.0 ## NaturalTransformation22 (interface) **Signature** ```ts export interface NaturalTransformation22 { (fa: Kind2): Kind2 } ``` Added in v2.11.0 ## NaturalTransformation22C (interface) **Signature** ```ts export interface NaturalTransformation22C { (fa: Kind2): Kind2 } ``` Added in v2.11.0 ## NaturalTransformation23 (interface) **Signature** ```ts export interface NaturalTransformation23 { (fa: Kind2): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation23C (interface) **Signature** ```ts export interface NaturalTransformation23C { (fa: Kind2): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation23R (interface) **Signature** ```ts export interface NaturalTransformation23R { (fa: Kind2): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation23RC (interface) **Signature** ```ts export interface NaturalTransformation23RC { (fa: Kind2): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation24 (interface) **Signature** ```ts export interface NaturalTransformation24 { (fa: Kind2): Kind4 } ``` Added in v2.11.0 ## NaturalTransformation24R (interface) **Signature** ```ts export interface NaturalTransformation24R { (fa: Kind2): Kind4 } ``` Added in v2.11.0 ## NaturalTransformation24S (interface) **Signature** ```ts export interface NaturalTransformation24S { (fa: Kind2): Kind4 } ``` Added in v2.11.0 ## NaturalTransformation33 (interface) **Signature** ```ts export interface NaturalTransformation33 { (fa: Kind3): Kind3 } ``` Added in v2.11.0 ## NaturalTransformation34 (interface) **Signature** ```ts export interface NaturalTransformation34 { (fa: Kind3): Kind4 } ``` Added in v2.11.0 ================================================ FILE: docs/modules/NonEmptyArray.ts.md ================================================ --- title: NonEmptyArray.ts nav_order: 66 parent: Modules --- ## NonEmptyArray overview Data structure which represents non-empty arrays. ```ts export type NonEmptyArray = Array & { 0: A } ``` Note that you don't need any conversion, a `NonEmptyArray` is an `Array`, so all `Array`'s APIs can be used with a `NonEmptyArray` without further ado. Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [makeBy](#makeby) - [of](#of) - [range](#range) - [replicate](#replicate) - [conversions](#conversions) - [fromArray](#fromarray) - [fromReadonlyNonEmptyArray](#fromreadonlynonemptyarray) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [folding](#folding) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [instances](#instances) - [Alt](#alt) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [Comonad](#comonad) - [Foldable](#foldable) - [FoldableWithIndex](#foldablewithindex) - [Functor](#functor) - [FunctorWithIndex](#functorwithindex) - [Monad](#monad) - [Pointed](#pointed) - [Traversable](#traversable) - [TraversableWithIndex](#traversablewithindex) - [getEq](#geteq) - [getSemigroup](#getsemigroup) - [getShow](#getshow) - [legacy](#legacy) - [chain](#chain) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [mapWithIndex](#mapwithindex) - [model](#model) - [NonEmptyArray (interface)](#nonemptyarray-interface) - [pattern matching](#pattern-matching) - [matchLeft](#matchleft) - [matchRight](#matchright) - [sequencing](#sequencing) - [chainFirst](#chainfirst) - [chainWithIndex](#chainwithindex) - [flatMap](#flatmap) - [flatten](#flatten) - [traverseWithIndex](#traversewithindex) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [chop](#chop) - [chunksOf](#chunksof) - [concat](#concat) - [concatAll](#concatall) - [concatW](#concatw) - [copy](#copy) - [duplicate](#duplicate) - [extend](#extend) - [extract](#extract) - [getUnionSemigroup](#getunionsemigroup) - [group](#group) - [groupBy](#groupby) - [head](#head) - [init](#init) - [insertAt](#insertat) - [intercalate](#intercalate) - [intersperse](#intersperse) - [last](#last) - [max](#max) - [min](#min) - [modifyAt](#modifyat) - [modifyHead](#modifyhead) - [modifyLast](#modifylast) - [prependAll](#prependall) - [reverse](#reverse) - [rotate](#rotate) - [sort](#sort) - [sortBy](#sortby) - [splitAt](#splitat) - [tail](#tail) - [unappend](#unappend) - [union](#union) - [uniq](#uniq) - [unprepend](#unprepend) - [unzip](#unzip) - [updateAt](#updateat) - [updateHead](#updatehead) - [updateLast](#updatelast) - [zip](#zip) - [zipWith](#zipwith) - [zone of death](#zone-of-death) - [~~cons~~](#cons) - [~~filterWithIndex~~](#filterwithindex) - [~~filter~~](#filter) - [~~fold~~](#fold) - [~~groupSort~~](#groupsort) - [~~nonEmptyArray~~](#nonemptyarray) - [~~prependToAll~~](#prependtoall) - [~~snoc~~](#snoc) - [~~uncons~~](#uncons) - [~~unsnoc~~](#unsnoc) --- # constructors ## makeBy Return a `NonEmptyArray` of length `n` with element `i` initialized with `f(i)`. **Note**. `n` is normalized to a natural number. **Signature** ```ts export declare const makeBy:
(f: (i: number) => A) => (n: number) => NonEmptyArray ``` **Example** ```ts import { makeBy } from 'fp-ts/NonEmptyArray' import { pipe } from 'fp-ts/function' const double = (n: number): number => n * 2 assert.deepStrictEqual(pipe(5, makeBy(double)), [0, 2, 4, 6, 8]) ``` Added in v2.11.0 ## of **Signature** ```ts export declare const of: (a: A) => NonEmptyArray ``` Added in v2.0.0 ## range Create a `NonEmptyArray` containing a range of integers, including both endpoints. **Signature** ```ts export declare const range: (start: number, end: number) => NonEmptyArray ``` **Example** ```ts import { range } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(range(1, 5), [1, 2, 3, 4, 5]) ``` Added in v2.11.0 ## replicate Create a `NonEmptyArray` containing a value repeated the specified number of times. **Note**. `n` is normalized to a natural number. **Signature** ```ts export declare const replicate: (a: A) => (n: number) => RNEA.ReadonlyNonEmptyArray ``` **Example** ```ts import { replicate } from 'fp-ts/NonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(3, replicate('a')), ['a', 'a', 'a']) ``` Added in v2.11.0 # conversions ## fromArray Builds a `NonEmptyArray` from an `Array` returning `none` if `as` is an empty array **Signature** ```ts export declare const fromArray: (as: A[]) => Option> ``` Added in v2.0.0 ## fromReadonlyNonEmptyArray **Signature** ```ts export declare const fromReadonlyNonEmptyArray: (as: RNEA.ReadonlyNonEmptyArray) => NonEmptyArray ``` Added in v2.10.0 # do notation ## Do **Signature** ```ts export declare const Do: NonEmptyArray<{}> ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: NonEmptyArray ) => (fa: NonEmptyArray) => NonEmptyArray<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => NonEmptyArray ) => (ma: NonEmptyArray) => NonEmptyArray<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: NonEmptyArray) => NonEmptyArray<{ readonly [K in N]: A }> ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: NonEmptyArray) => NonEmptyArray<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. In case of `NonEmptyArray` concatenates the inputs into a single array. **Signature** ```ts export declare const alt: (that: LazyArg>) => (fa: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import * as NEA from 'fp-ts/NonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], NEA.alt(() => [4, 5]) ), [1, 2, 3, 4, 5] ) ``` Added in v2.6.2 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (that: LazyArg>) => (as: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import * as NEA from 'fp-ts/NonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3] as NEA.NonEmptyArray, NEA.altW(() => ['a', 'b']) ), [1, 2, 3, 'a', 'b'] ) ``` Added in v2.9.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (S: Se.Semigroup) => (f: (a: A) => S) => (fa: NonEmptyArray) => S ``` Added in v2.0.0 ## foldMapWithIndex **Signature** ```ts export declare const foldMapWithIndex: ( S: Se.Semigroup ) => (f: (i: number, a: A) => S) => (fa: NonEmptyArray) => S ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: NonEmptyArray) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: NonEmptyArray) => B ``` Added in v2.0.0 ## reduceRightWithIndex **Signature** ```ts export declare const reduceRightWithIndex: (b: B, f: (i: number, a: A, b: B) => B) => (fa: NonEmptyArray) => B ``` Added in v2.0.0 ## reduceWithIndex **Signature** ```ts export declare const reduceWithIndex: (b: B, f: (i: number, b: B, a: A) => B) => (fa: NonEmptyArray) => B ``` Added in v2.0.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'NonEmptyArray'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'NonEmptyArray'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'NonEmptyArray'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: Chain1<'NonEmptyArray'> ``` Added in v2.10.0 ## Comonad **Signature** ```ts export declare const Comonad: Comonad1<'NonEmptyArray'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'NonEmptyArray'> ``` Added in v2.7.0 ## FoldableWithIndex **Signature** ```ts export declare const FoldableWithIndex: FoldableWithIndex1<'NonEmptyArray', number> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'NonEmptyArray'> ``` Added in v2.7.0 ## FunctorWithIndex **Signature** ```ts export declare const FunctorWithIndex: FunctorWithIndex1<'NonEmptyArray', number> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'NonEmptyArray'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'NonEmptyArray'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'NonEmptyArray'> ``` Added in v2.7.0 ## TraversableWithIndex **Signature** ```ts export declare const TraversableWithIndex: TraversableWithIndex1<'NonEmptyArray', number> ``` Added in v2.7.0 ## getEq **Signature** ```ts export declare const getEq: (E: Eq) => Eq> ``` **Example** ```ts import { getEq } from 'fp-ts/NonEmptyArray' import * as N from 'fp-ts/number' const E = getEq(N.Eq) assert.strictEqual(E.equals([1, 2], [1, 2]), true) assert.strictEqual(E.equals([1, 2], [1, 3]), false) ``` Added in v2.0.0 ## getSemigroup Builds a `Semigroup` instance for `NonEmptyArray` **Signature** ```ts export declare const getSemigroup: () => Se.Semigroup> ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare const getShow: (S: Show) => Show> ``` Added in v2.0.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => NonEmptyArray) => (ma: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: NonEmptyArray<(a: A) => B>) => NonEmptyArray ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 ## mapWithIndex **Signature** ```ts export declare const mapWithIndex: (f: (i: number, a: A) => B) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 # model ## NonEmptyArray (interface) **Signature** ```ts export interface NonEmptyArray extends Array { 0: A } ``` Added in v2.0.0 # pattern matching ## matchLeft Break an `Array` into its first element and remaining elements. **Signature** ```ts export declare const matchLeft: (f: (head: A, tail: A[]) => B) => (as: NonEmptyArray) => B ``` Added in v2.11.0 ## matchRight Break an `Array` into its initial elements and the last element. **Signature** ```ts export declare const matchRight: (f: (init: A[], last: A) => B) => (as: NonEmptyArray) => B ``` Added in v2.11.0 # sequencing ## chainFirst Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const chainFirst: (f: (a: A) => NonEmptyArray) => (first: NonEmptyArray) => NonEmptyArray ``` Added in v2.5.0 ## chainWithIndex **Signature** ```ts export declare const chainWithIndex: ( f: (i: number, a: A) => NonEmptyArray ) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.10.0 ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A, i: number) => NonEmptyArray): (ma: NonEmptyArray) => NonEmptyArray (ma: NonEmptyArray, f: (a: A, i: number) => NonEmptyArray): NonEmptyArray } ``` **Example** ```ts import * as NEA from 'fp-ts/NonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], NEA.flatMap((n) => [`a${n}`, `b${n}`]) ), ['a1', 'b1', 'a2', 'b2', 'a3', 'b3'] ) ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: NonEmptyArray>) => NonEmptyArray ``` Added in v2.5.0 ## traverseWithIndex **Signature** ```ts export declare const traverseWithIndex: PipeableTraverseWithIndex1<'NonEmptyArray', number> ``` Added in v2.6.3 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence1<'NonEmptyArray'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse1<'NonEmptyArray'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'NonEmptyArray' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ap Apply a function to an argument under a type constructor. **Signature** ```ts export declare const ap: (as: NonEmptyArray) => (fab: NonEmptyArray<(a: A) => B>) => NonEmptyArray ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: NonEmptyArray) => (first: NonEmptyArray) => NonEmptyArray ``` Added in v2.5.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: NonEmptyArray) => (first: NonEmptyArray) => NonEmptyArray ``` Added in v2.5.0 ## chop **Signature** ```ts export declare const chop: (f: (as: NonEmptyArray) => [B, A[]]) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.10.0 ## chunksOf **Signature** ```ts export declare const chunksOf: (n: number) => (as: NonEmptyArray) => NonEmptyArray> ``` Added in v2.10.0 ## concat **Signature** ```ts export declare function concat(second: NonEmptyArray): (first: Array) => NonEmptyArray export declare function concat(second: Array): (first: NonEmptyArray) => NonEmptyArray export declare function concat(first: Array, second: NonEmptyArray): NonEmptyArray export declare function concat(first: NonEmptyArray, second: Array): NonEmptyArray ``` Added in v2.2.0 ## concatAll **Signature** ```ts export declare const concatAll: (S: Se.Semigroup) => (as: NonEmptyArray) => A ``` Added in v2.10.0 ## concatW **Signature** ```ts export declare function concatW(second: NonEmptyArray): (first: Array) => NonEmptyArray export declare function concatW(second: Array): (first: NonEmptyArray) => NonEmptyArray ``` Added in v2.11.0 ## copy **Signature** ```ts export declare const copy: (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 ## duplicate **Signature** ```ts export declare const duplicate: (ma: NonEmptyArray) => NonEmptyArray> ``` Added in v2.5.0 ## extend **Signature** ```ts export declare const extend: (f: (as: NonEmptyArray) => B) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 ## extract **Signature** ```ts export declare const extract: (wa: NonEmptyArray) => A ``` Added in v2.7.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq) => Se.Semigroup> ``` Added in v2.11.0 ## group Group equal, consecutive elements of an array into non empty arrays. **Signature** ```ts export declare function group(E: Eq): { (as: NonEmptyArray): NonEmptyArray> (as: Array): Array> } ``` **Example** ```ts import { group } from 'fp-ts/NonEmptyArray' import * as N from 'fp-ts/number' assert.deepStrictEqual(group(N.Ord)([1, 2, 1, 1]), [[1], [2], [1, 1]]) ``` Added in v2.0.0 ## groupBy Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning function on each element, and grouping the results according to values returned **Signature** ```ts export declare const groupBy: (f: (a: A) => string) => (as: A[]) => Record> ``` **Example** ```ts import { groupBy } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(groupBy((s: string) => String(s.length))(['a', 'b', 'ab']), { '1': ['a', 'b'], '2': ['ab'], }) ``` Added in v2.0.0 ## head **Signature** ```ts export declare const head: (nea: NonEmptyArray) => A ``` Added in v2.0.0 ## init Get all but the last element of a non empty array, creating a new array. **Signature** ```ts export declare const init: (as: NonEmptyArray) => A[] ``` **Example** ```ts import { init } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(init([1, 2, 3]), [1, 2]) assert.deepStrictEqual(init([1]), []) ``` Added in v2.2.0 ## insertAt **Signature** ```ts export declare const insertAt: (i: number, a: A) => (as: A[]) => Option> ``` Added in v2.0.0 ## intercalate Places an element in between members of a `NonEmptyArray`, then folds the results using the provided `Semigroup`. **Signature** ```ts export declare const intercalate: (S: Se.Semigroup) => (middle: A) => (as: NonEmptyArray) => A ``` **Example** ```ts import * as S from 'fp-ts/string' import { intercalate } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(intercalate(S.Semigroup)('-')(['a', 'b', 'c']), 'a-b-c') ``` Added in v2.12.0 ## intersperse Places an element in between members of an array **Signature** ```ts export declare const intersperse: (middle: A) => (as: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import { intersperse } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.9.0 ## last **Signature** ```ts export declare const last: (nea: NonEmptyArray) => A ``` Added in v2.0.0 ## max **Signature** ```ts export declare const max: (ord: Ord) => (nea: NonEmptyArray) => A ``` Added in v2.0.0 ## min **Signature** ```ts export declare const min: (ord: Ord) => (nea: NonEmptyArray) => A ``` Added in v2.0.0 ## modifyAt **Signature** ```ts export declare const modifyAt: (i: number, f: (a: A) => A) => (as: NonEmptyArray) => Option> ``` Added in v2.0.0 ## modifyHead Apply a function to the head, creating a new `NonEmptyArray`. **Signature** ```ts export declare const modifyHead: (f: Endomorphism) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.11.0 ## modifyLast Apply a function to the last element, creating a new `NonEmptyArray`. **Signature** ```ts export declare const modifyLast: (f: Endomorphism) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.11.0 ## prependAll Prepend an element to every member of an array **Signature** ```ts export declare const prependAll: (middle: A) => (as: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import { prependAll } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.10.0 ## reverse **Signature** ```ts export declare const reverse: (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 ## rotate Rotate a `NonEmptyArray` by `n` steps. **Signature** ```ts export declare const rotate: (n: number) => (as: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import { rotate } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) assert.deepStrictEqual(rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) ``` Added in v2.11.0 ## sort **Signature** ```ts export declare const sort: (O: Ord) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.0.0 ## sortBy Sort the elements of a `NonEmptyArray` in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, etc... **Signature** ```ts export declare const sortBy: (ords: Ord[]) => (as: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import * as NEA from 'fp-ts/NonEmptyArray' import { contramap } from 'fp-ts/Ord' import * as S from 'fp-ts/string' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' interface Person { name: string age: number } const byName = pipe( S.Ord, contramap((p: Person) => p.name) ) const byAge = pipe( N.Ord, contramap((p: Person) => p.age) ) const sortByNameByAge = NEA.sortBy([byName, byAge]) const persons: NEA.NonEmptyArray = [ { name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 }, ] assert.deepStrictEqual(sortByNameByAge(persons), [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, ]) ``` Added in v2.11.0 ## splitAt Splits a `NonEmptyArray` into two pieces, the first piece has max `n` elements. **Signature** ```ts export declare const splitAt: (n: number) => (as: NonEmptyArray) => [NonEmptyArray, A[]] ``` Added in v2.10.0 ## tail **Signature** ```ts export declare const tail: (as: NonEmptyArray) => A[] ``` Added in v2.0.0 ## unappend Return the tuple of the `init` and the `last`. **Signature** ```ts export declare const unappend: (as: NonEmptyArray) => [A[], A] ``` **Example** ```ts import { unappend } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) ``` Added in v2.9.0 ## union **Signature** ```ts export declare const union: (E: Eq) => (second: NonEmptyArray) => (first: NonEmptyArray) => NonEmptyArray ``` Added in v2.11.0 ## uniq Remove duplicates from a `NonEmptyArray`, keeping the first occurrence of an element. **Signature** ```ts export declare const uniq: (E: Eq) => (as: NonEmptyArray) => NonEmptyArray ``` **Example** ```ts import { uniq } from 'fp-ts/NonEmptyArray' import * as N from 'fp-ts/number' assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) ``` Added in v2.11.0 ## unprepend Return the tuple of the `head` and the `tail`. **Signature** ```ts export declare const unprepend: (as: NonEmptyArray) => [A, A[]] ``` **Example** ```ts import { unprepend } from 'fp-ts/NonEmptyArray' assert.deepStrictEqual(unprepend([1, 2, 3]), [1, [2, 3]]) ``` Added in v2.9.0 ## unzip **Signature** ```ts export declare const unzip: (abs: NonEmptyArray<[A, B]>) => [NonEmptyArray, NonEmptyArray] ``` Added in v2.5.1 ## updateAt **Signature** ```ts export declare const updateAt: (i: number, a: A) => (as: NonEmptyArray) => Option> ``` Added in v2.0.0 ## updateHead Change the head, creating a new `NonEmptyArray`. **Signature** ```ts export declare const updateHead: (a: A) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.11.0 ## updateLast Change the last element, creating a new `NonEmptyArray`. **Signature** ```ts export declare const updateLast: (a: A) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.11.0 ## zip **Signature** ```ts export declare function zip(bs: NonEmptyArray): (as: NonEmptyArray) => NonEmptyArray<[A, B]> export declare function zip(as: NonEmptyArray, bs: NonEmptyArray): NonEmptyArray<[A, B]> ``` Added in v2.5.1 ## zipWith **Signature** ```ts export declare const zipWith: ( as: NonEmptyArray, bs: NonEmptyArray, f: (a: A, b: B) => C ) => NonEmptyArray ``` Added in v2.5.1 # zone of death ## ~~cons~~ Use [`prepend`](./Array.ts.html#prepend) instead. **Signature** ```ts export declare function cons(head: A): (tail: Array) => NonEmptyArray export declare function cons(head: A, tail: Array): NonEmptyArray ``` Added in v2.0.0 ## ~~filterWithIndex~~ Use [`filterWithIndex`](./Array.ts.html#filterwithindex) instead. **Signature** ```ts export declare const filterWithIndex: ( predicate: (i: number, a: A) => boolean ) => (as: NonEmptyArray) => Option> ``` Added in v2.0.0 ## ~~filter~~ Use [`filter`](./Array.ts.html#filter) instead. **Signature** ```ts export declare function filter( refinement: Refinement ): (as: NonEmptyArray) => Option> export declare function filter( predicate: Predicate ): (bs: NonEmptyArray) => Option> export declare function filter(predicate: Predicate): (as: NonEmptyArray) => Option> ``` Added in v2.0.0 ## ~~fold~~ Use [`concatAll`](#concatall) instead. **Signature** ```ts export declare const fold: (S: Se.Semigroup) => (fa: NonEmptyArray) => A ``` Added in v2.5.0 ## ~~groupSort~~ This is just `sort` followed by `group`. **Signature** ```ts export declare function groupSort(O: Ord): { (as: NonEmptyArray): NonEmptyArray> (as: Array): Array> } ``` Added in v2.0.0 ## ~~nonEmptyArray~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `NEA.Functor` instead of `NEA.nonEmptyArray` (where `NEA` is from `import NEA from 'fp-ts/NonEmptyArray'`) **Signature** ```ts export declare const nonEmptyArray: Monad1<'NonEmptyArray'> & Comonad1<'NonEmptyArray'> & TraversableWithIndex1<'NonEmptyArray', number> & FunctorWithIndex1<'NonEmptyArray', number> & FoldableWithIndex1<'NonEmptyArray', number> & Alt1<'NonEmptyArray'> ``` Added in v2.0.0 ## ~~prependToAll~~ Use [`prependAll`](#prependall) instead. **Signature** ```ts export declare const prependToAll: (middle: A) => (as: NonEmptyArray) => NonEmptyArray ``` Added in v2.9.0 ## ~~snoc~~ Use [`append`](./Array.ts.html#append) instead. **Signature** ```ts export declare const snoc: (init: A[], end: A) => NonEmptyArray ``` Added in v2.0.0 ## ~~uncons~~ Use [`unprepend`](#unprepend) instead. **Signature** ```ts export declare const uncons: (as: NonEmptyArray) => [A, A[]] ``` Added in v2.9.0 ## ~~unsnoc~~ Use [`unappend`](#unappend) instead. **Signature** ```ts export declare const unsnoc: (as: NonEmptyArray) => [A[], A] ``` Added in v2.9.0 ================================================ FILE: docs/modules/Option.ts.md ================================================ --- title: Option.ts nav_order: 68 parent: Modules --- ## Option overview ```ts type Option = None | Some ``` `Option` is a container for an optional value of type `A`. If the value of type `A` is present, the `Option` is an instance of `Some`, containing the present value of type `A`. If the value is absent, the `Option` is an instance of `None`. An option could be looked at as a collection or foldable structure with either one or zero elements. Another way to look at `Option` is: it represents the effect of a possibly failing computation. **Example** ```ts import * as O from 'fp-ts/Option' import { pipe } from 'fp-ts/function' const double = (n: number): number => n * 2 export const imperative = (as: ReadonlyArray): string => { const head = (as: ReadonlyArray): number => { if (as.length === 0) { throw new Error() } return as[0] } const inverse = (n: number): number => { if (n === 0) { throw new Error() } return 1 / n } try { return `Result is ${inverse(double(head(as)))}` } catch (e) { return 'no result' } } export const functional = (as: ReadonlyArray): string => { const head = (as: ReadonlyArray): O.Option => (as.length === 0 ? O.none : O.some(as[0])) const inverse = (n: number): O.Option => (n === 0 ? O.none : O.some(1 / n)) return pipe( as, head, O.map(double), O.flatMap(inverse), O.match( () => 'no result', // onNone handler (head) => `Result is ${head}` // onSome handler ) ) } assert.deepStrictEqual(imperative([1, 2, 3]), functional([1, 2, 3])) assert.deepStrictEqual(imperative([]), functional([])) assert.deepStrictEqual(imperative([0]), functional([0])) ``` Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [constructors](#constructors) - [getLeft](#getleft) - [getRight](#getright) - [none](#none) - [of](#of) - [some](#some) - [conversions](#conversions) - [fromEither](#fromeither) - [fromNullable](#fromnullable) - [toNullable](#tonullable) - [toUndefined](#toundefined) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [guard](#guard) - [let](#let) - [error handling](#error-handling) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [orElse](#orelse) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [wilt](#wilt) - [wither](#wither) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Alt](#alt) - [Alternative](#alternative) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [Compactable](#compactable) - [Extend](#extend) - [Filterable](#filterable) - [Foldable](#foldable) - [FromEither](#fromeither) - [Functor](#functor) - [Monad](#monad) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [Traversable](#traversable) - [Witherable](#witherable) - [Zero](#zero) - [getEq](#geteq) - [getMonoid](#getmonoid) - [getOrd](#getord) - [getShow](#getshow) - [interop](#interop) - [tryCatch](#trycatch) - [tryCatchK](#trycatchk) - [legacy](#legacy) - [alt](#alt) - [altW](#altw) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromNullableK](#fromnullablek) - [fromPredicate](#frompredicate) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [None (interface)](#none-interface) - [Option (type alias)](#option-type-alias) - [Some (interface)](#some-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchW](#matchw) - [refinements](#refinements) - [isNone](#isnone) - [isSome](#issome) - [sequencing](#sequencing) - [chainEitherK](#chaineitherk) - [chainNullableK](#chainnullablek) - [flatMap](#flatmap) - [flatten](#flatten) - [traversing](#traversing) - [sequence](#sequence) - [sequenceArray](#sequencearray) - [traverse](#traverse) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [duplicate](#duplicate) - [elem](#elem) - [exists](#exists) - [extend](#extend) - [throwError](#throwerror) - [zero](#zero) - [zone of death](#zone-of-death) - [~~getApplyMonoid~~](#getapplymonoid) - [~~getApplySemigroup~~](#getapplysemigroup) - [~~getFirstMonoid~~](#getfirstmonoid) - [~~getLastMonoid~~](#getlastmonoid) - [~~getRefinement~~](#getrefinement) - [~~mapNullable~~](#mapnullable) - [~~option~~](#option) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: Option
, f: (a: A) => Option<_>): Option (f: (a: A) => Option<_>): (self: Option) => Option } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => Either): (self: Option) => Option (self: Option, f: (a: A) => Either): Option } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as O from 'fp-ts/Option' import * as E from 'fp-ts/Either' const compute = (value: number) => pipe( O.of(value), O.tapEither((value) => (value > 0 ? E.right('ok') : E.left('error'))) ) assert.deepStrictEqual(compute(1), O.of(1)) assert.deepStrictEqual(compute(-42), O.none) ``` Added in v2.16.0 # constructors ## getLeft Returns the `Left` value of an `Either` if possible. **Signature** ```ts export declare const getLeft: (ma: Either) => Option ``` **Example** ```ts import { getLeft, none, some } from 'fp-ts/Option' import { right, left } from 'fp-ts/Either' assert.deepStrictEqual(getLeft(right(1)), none) assert.deepStrictEqual(getLeft(left('a')), some('a')) ``` Added in v2.0.0 ## getRight Returns the `Right` value of an `Either` if possible. **Signature** ```ts export declare const getRight: (ma: Either) => Option ``` **Example** ```ts import { getRight, none, some } from 'fp-ts/Option' import { right, left } from 'fp-ts/Either' assert.deepStrictEqual(getRight(right(1)), some(1)) assert.deepStrictEqual(getRight(left('a')), none) ``` Added in v2.0.0 ## none `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value. **Signature** ```ts export declare const none: Option ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => Option ``` Added in v2.7.0 ## some Constructs a `Some`. Represents an optional value that exists. **Signature** ```ts export declare const some: (a: A) => Option ``` Added in v2.0.0 # conversions ## fromEither Transforms an `Either` to an `Option` discarding the error. Alias of [getRight](#getright) **Signature** ```ts export declare const fromEither: (fa: Either) => Option ``` Added in v2.0.0 ## fromNullable Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise returns the value wrapped in a `Some`. **Signature** ```ts export declare const fromNullable: (a: A) => Option> ``` **Example** ```ts import { none, some, fromNullable } from 'fp-ts/Option' assert.deepStrictEqual(fromNullable(undefined), none) assert.deepStrictEqual(fromNullable(null), none) assert.deepStrictEqual(fromNullable(1), some(1)) ``` Added in v2.0.0 ## toNullable Extracts the value out of the structure, if it exists. Otherwise returns `null`. **Signature** ```ts export declare const toNullable: (ma: Option) => A | null ``` **Example** ```ts import { some, none, toNullable } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.strictEqual(pipe(some(1), toNullable), 1) assert.strictEqual(pipe(none, toNullable), null) ``` Added in v2.0.0 ## toUndefined Extracts the value out of the structure, if it exists. Otherwise returns `undefined`. **Signature** ```ts export declare const toUndefined: (ma: Option) => A | undefined ``` **Example** ```ts import { some, none, toUndefined } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.strictEqual(pipe(some(1), toUndefined), 1) assert.strictEqual(pipe(none, toUndefined), undefined) ``` Added in v2.0.0 # do notation ## Do **Signature** ```ts export declare const Do: Option<{}> ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: Option ) => (fa: Option) => Option<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => Option ) => (ma: Option) => Option<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: Option) => Option<{ readonly [K in N]: A }> ``` Added in v2.8.0 ## guard **Signature** ```ts export declare const guard: (b: boolean) => Option ``` Added in v2.11.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: Option) => Option<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # error handling ## getOrElse Extracts the value out of the structure, if it exists. Otherwise returns the given default value **Signature** ```ts export declare const getOrElse: (onNone: LazyArg) => (ma: Option) => A ``` **Example** ```ts import { some, none, getOrElse } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.strictEqual( pipe( some(1), getOrElse(() => 0) ), 1 ) assert.strictEqual( pipe( none, getOrElse(() => 0) ), 0 ) ``` Added in v2.0.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: (onNone: LazyArg) => (ma: Option) => B | A ``` Added in v2.6.0 ## orElse Returns the provided `Option` `that` if `self` is `None`, otherwise returns `self`. **Signature** ```ts export declare const orElse: { (that: LazyArg>): (self: Option) => Option (self: Option, that: LazyArg>): Option } ``` **Example** ```ts import * as O from 'fp-ts/Option' assert.deepStrictEqual( O.orElse(O.none, () => O.none), O.none ) assert.deepStrictEqual( O.orElse(O.some(1), () => O.none), O.some(1) ) assert.deepStrictEqual( O.orElse(O.none, () => O.some('b')), O.some('b') ) assert.deepStrictEqual( O.orElse(O.some(1), () => O.some('b')), O.some(1) ) ``` Added in v2.16.0 # filtering ## compact **Signature** ```ts export declare const compact: (fa: Option>) => Option ``` Added in v2.0.0 ## filter **Signature** ```ts export declare const filter: { (refinement: Refinement): (fa: Option) => Option (predicate: Predicate): (fb: Option) => Option (predicate: Predicate): (fa: Option) => Option } ``` Added in v2.0.0 ## filterMap **Signature** ```ts export declare const filterMap: (f: (a: A) => Option) => (fa: Option) => Option ``` Added in v2.0.0 ## partition **Signature** ```ts export declare const partition: { (refinement: Refinement): (fa: Option) => Separated, Option> (predicate: Predicate): (fb: Option) => Separated, Option> (predicate: Predicate): (fa: Option) => Separated, Option> } ``` Added in v2.0.0 ## partitionMap **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: Option) => Separated, Option> ``` Added in v2.0.0 ## separate **Signature** ```ts export declare const separate: (ma: Option>) => Separated, Option> ``` Added in v2.0.0 ## wilt **Signature** ```ts export declare const wilt: PipeableWilt1<'Option'> ``` Added in v2.6.5 ## wither **Signature** ```ts export declare const wither: PipeableWither1<'Option'> ``` Added in v2.6.5 # folding ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Option) => M ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Option) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Option) => B ``` Added in v2.0.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'Option'> ``` Added in v2.7.0 ## Alternative **Signature** ```ts export declare const Alternative: Alternative1<'Option'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'Option'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'Option'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain1<'Option'> ``` Added in v2.10.0 ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'Option'> ``` Added in v2.7.0 ## Extend **Signature** ```ts export declare const Extend: Extend1<'Option'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'Option'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'Option'> ``` Added in v2.7.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither1<'Option'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'Option'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'Option'> ``` Added in v2.7.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow1<'Option'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'Option'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'Option'> ``` Added in v2.7.0 ## Witherable **Signature** ```ts export declare const Witherable: Witherable1<'Option'> ``` Added in v2.7.0 ## Zero **Signature** ```ts export declare const Zero: Zero1<'Option'> ``` Added in v2.11.0 ## getEq **Signature** ```ts export declare const getEq: (E: Eq) => Eq> ``` **Example** ```ts import { none, some, getEq } from 'fp-ts/Option' import * as N from 'fp-ts/number' const E = getEq(N.Eq) assert.strictEqual(E.equals(none, none), true) assert.strictEqual(E.equals(none, some(1)), false) assert.strictEqual(E.equals(some(1), none), false) assert.strictEqual(E.equals(some(1), some(2)), false) assert.strictEqual(E.equals(some(1), some(1)), true) ``` Added in v2.0.0 ## getMonoid Monoid returning the left-most non-`None` value. If both operands are `Some`s then the inner values are concatenated using the provided `Semigroup` | x | y | concat(x, y) | | ------- | ------- | ------------------ | | none | none | none | | some(a) | none | some(a) | | none | some(b) | some(b) | | some(a) | some(b) | some(concat(a, b)) | **Signature** ```ts export declare const getMonoid: (S: Semigroup) => Monoid> ``` **Example** ```ts import { getMonoid, some, none } from 'fp-ts/Option' import { SemigroupSum } from 'fp-ts/number' const M = getMonoid(SemigroupSum) assert.deepStrictEqual(M.concat(none, none), none) assert.deepStrictEqual(M.concat(some(1), none), some(1)) assert.deepStrictEqual(M.concat(none, some(1)), some(1)) assert.deepStrictEqual(M.concat(some(1), some(2)), some(3)) ``` Added in v2.0.0 ## getOrd The `Ord` instance allows `Option` values to be compared with `compare`, whenever there is an `Ord` instance for the type the `Option` contains. `None` is considered to be less than any `Some` value. **Signature** ```ts export declare const getOrd: (O: Ord) => Ord> ``` **Example** ```ts import { none, some, getOrd } from 'fp-ts/Option' import * as N from 'fp-ts/number' const O = getOrd(N.Ord) assert.strictEqual(O.compare(none, none), 0) assert.strictEqual(O.compare(none, some(1)), -1) assert.strictEqual(O.compare(some(1), none), 1) assert.strictEqual(O.compare(some(1), some(2)), -1) assert.strictEqual(O.compare(some(1), some(1)), 0) ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare const getShow: (S: Show) => Show> ``` Added in v2.0.0 # interop ## tryCatch Transforms an exception into an `Option`. If `f` throws, returns `None`, otherwise returns the output wrapped in a `Some`. See also [`tryCatchK`](#trycatchk). **Signature** ```ts export declare const tryCatch: (f: LazyArg) => Option ``` **Example** ```ts import { none, some, tryCatch } from 'fp-ts/Option' assert.deepStrictEqual( tryCatch(() => { throw new Error() }), none ) assert.deepStrictEqual( tryCatch(() => 1), some(1) ) ``` Added in v2.0.0 ## tryCatchK Converts a function that may throw to one returning a `Option`. **Signature** ```ts export declare const tryCatchK: (f: (...a: A) => B) => (...a: A) => Option ``` Added in v2.10.0 # legacy ## alt Alias of `orElse`. **Signature** ```ts export declare const alt: (that: LazyArg>) => (fa: Option) => Option ``` Added in v2.0.0 ## altW Alias of `orElse`. Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (that: LazyArg>) => (fa: Option) => Option ``` Added in v2.9.0 ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => Option) => (ma: Option) => Option ``` Added in v2.0.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => Option) => (first: Option) => Option ``` Added in v2.0.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: (f: (a: A) => Either) => (ma: Option) => Option ``` Added in v2.12.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => Either ) => (...a: A) => Option ``` Added in v2.11.0 ## fromNullableK Returns a _smart constructor_ from a function that returns a nullable value. **Signature** ```ts export declare const fromNullableK: ( f: (...a: A) => B | null | undefined ) => (...a: A) => Option> ``` **Example** ```ts import { fromNullableK, none, some } from 'fp-ts/Option' const f = (s: string): number | undefined => { const n = parseFloat(s) return isNaN(n) ? undefined : n } const g = fromNullableK(f) assert.deepStrictEqual(g('1'), some(1)) assert.deepStrictEqual(g('a'), none) ``` Added in v2.9.0 ## fromPredicate Returns a _smart constructor_ based on the given predicate. **Signature** ```ts export declare function fromPredicate(refinement: Refinement): (a: A) => Option export declare function fromPredicate(predicate: Predicate): (b: B) => Option export declare function fromPredicate(predicate: Predicate): (a: A) => Option ``` **Example** ```ts import { none, some, fromPredicate } from 'fp-ts/Option' const getOption = fromPredicate((n: number) => n >= 0) assert.deepStrictEqual(getOption(-1), none) assert.deepStrictEqual(getOption(1), some(1)) ``` Added in v2.0.0 # mapping ## as Maps the `Some` value of this `Option` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): <_>(self: Option<_>) => Option; <_, A>(self: Option<_>, a: A): Option } ``` Added in v2.16.0 ## asUnit Maps the `Some` value of this `Option` to the void constant value. **Signature** ```ts export declare const asUnit: <_>(self: Option<_>) => Option ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Option<(a: A) => B>) => Option ``` Added in v2.10.0 ## map **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Option) => Option ``` Added in v2.0.0 # model ## None (interface) **Signature** ```ts export interface None { readonly _tag: 'None' } ``` Added in v2.0.0 ## Option (type alias) **Signature** ```ts export type Option = None | Some ``` Added in v2.0.0 ## Some (interface) **Signature** ```ts export interface Some { readonly _tag: 'Some' readonly value: A } ``` Added in v2.0.0 # pattern matching ## fold Alias of [`match`](#match). **Signature** ```ts export declare const fold: (onNone: LazyArg, onSome: (a: A) => B) => (ma: Option) => B ``` Added in v2.0.0 ## foldW Alias of [`matchW`](#matchw). **Signature** ```ts export declare const foldW: (onNone: LazyArg, onSome: (a: A) => C) => (ma: Option) => B | C ``` Added in v2.10.0 ## match Takes a (lazy) default value, a function, and an `Option` value, if the `Option` value is `None` the default value is returned, otherwise the function is applied to the value inside the `Some` and the result is returned. **Signature** ```ts export declare const match: (onNone: LazyArg, onSome: (a: A) => B) => (ma: Option) => B ``` **Example** ```ts import { some, none, match } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.strictEqual( pipe( some(1), match( () => 'a none', (a) => `a some containing ${a}` ) ), 'a some containing 1' ) assert.strictEqual( pipe( none, match( () => 'a none', (a) => `a some containing ${a}` ) ), 'a none' ) ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: (onNone: LazyArg, onSome: (a: A) => C) => (ma: Option) => B | C ``` Added in v2.10.0 # refinements ## isNone Returns `true` if the option is `None`, `false` otherwise. **Signature** ```ts export declare const isNone: (fa: Option) => fa is None ``` **Example** ```ts import { some, none, isNone } from 'fp-ts/Option' assert.strictEqual(isNone(some(1)), false) assert.strictEqual(isNone(none), true) ``` Added in v2.0.0 ## isSome Returns `true` if the option is an instance of `Some`, `false` otherwise. **Signature** ```ts export declare const isSome: (fa: Option) => fa is Some ``` **Example** ```ts import { some, none, isSome } from 'fp-ts/Option' assert.strictEqual(isSome(some(1)), true) assert.strictEqual(isSome(none), false) ``` Added in v2.0.0 # sequencing ## chainEitherK **Signature** ```ts export declare const chainEitherK: (f: (a: A) => Either) => (ma: Option) => Option ``` Added in v2.11.0 ## chainNullableK This is `chain` + `fromNullable`, useful when working with optional values. **Signature** ```ts export declare const chainNullableK: ( f: (a: A) => B | null | undefined ) => (ma: Option) => Option> ``` **Example** ```ts import { some, none, fromNullable, chainNullableK } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' interface Employee { readonly company?: { readonly address?: { readonly street?: { readonly name?: string } } } } const employee1: Employee = { company: { address: { street: { name: 'high street' } } } } assert.deepStrictEqual( pipe( fromNullable(employee1.company), chainNullableK((company) => company.address), chainNullableK((address) => address.street), chainNullableK((street) => street.name) ), some('high street') ) const employee2: Employee = { company: { address: { street: {} } } } assert.deepStrictEqual( pipe( fromNullable(employee2.company), chainNullableK((company) => company.address), chainNullableK((address) => address.street), chainNullableK((street) => street.name) ), none ) ``` Added in v2.9.0 ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => Option): (ma: Option) => Option (ma: Option, f: (a: A) => Option): Option } ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: Option>) => Option ``` Added in v2.0.0 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence1<'Option'> ``` Added in v2.6.3 ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly Option[]) => Option ``` Added in v2.9.0 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse1<'Option'> ``` Added in v2.6.3 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: (f: (a: A) => Option) => (as: readonly A[]) => Option ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => Option ) => (as: readonly A[]) => Option ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => Option ) => (as: readonly A[]) => Option ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => Option ) => (as: ReadonlyNonEmptyArray) => Option> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Option' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: Option ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: Option) => (fab: Option<(a: A) => B>) => Option ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: Option) => (first: Option) => Option ``` Added in v2.0.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: Option) => (first: Option) => Option ``` Added in v2.0.0 ## duplicate **Signature** ```ts export declare const duplicate: (ma: Option) => Option> ``` Added in v2.0.0 ## elem Returns `true` if `ma` contains `a` **Signature** ```ts export declare function elem(E: Eq): { (a: A): (ma: Option) => boolean (a: A, ma: Option): boolean } ``` **Example** ```ts import { some, none, elem } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' import * as N from 'fp-ts/number' assert.strictEqual(pipe(some(1), elem(N.Eq)(1)), true) assert.strictEqual(pipe(some(1), elem(N.Eq)(2)), false) assert.strictEqual(pipe(none, elem(N.Eq)(1)), false) ``` Added in v2.0.0 ## exists Returns `true` if the predicate is satisfied by the wrapped value **Signature** ```ts export declare const exists: (predicate: Predicate) => (ma: Option) => boolean ``` **Example** ```ts import { some, none, exists } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.strictEqual( pipe( some(1), exists((n) => n > 0) ), true ) assert.strictEqual( pipe( some(1), exists((n) => n > 1) ), false ) assert.strictEqual( pipe( none, exists((n) => n > 0) ), false ) ``` Added in v2.0.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: Option) => B) => (wa: Option) => Option ``` Added in v2.0.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => Option ``` Added in v2.7.0 ## zero **Signature** ```ts export declare const zero: () => Option ``` Added in v2.7.0 # zone of death ## ~~getApplyMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getApplyMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getApplySemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getApplySemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getFirstMonoid~~ Use ```ts import { first } from 'fp-ts/Semigroup' import { getMonoid } from 'fp-ts/Option' getMonoid(first()) ``` instead. Monoid returning the left-most non-`None` value | x | y | concat(x, y) | | ------- | ------- | ------------ | | none | none | none | | some(a) | none | some(a) | | none | some(b) | some(b) | | some(a) | some(b) | some(a) | **Signature** ```ts export declare const getFirstMonoid: () => Monoid> ``` **Example** ```ts import { getFirstMonoid, some, none } from 'fp-ts/Option' const M = getFirstMonoid() assert.deepStrictEqual(M.concat(none, none), none) assert.deepStrictEqual(M.concat(some(1), none), some(1)) assert.deepStrictEqual(M.concat(none, some(2)), some(2)) assert.deepStrictEqual(M.concat(some(1), some(2)), some(1)) ``` Added in v2.0.0 ## ~~getLastMonoid~~ Use ```ts import { last } from 'fp-ts/Semigroup' import { getMonoid } from 'fp-ts/Option' getMonoid(last()) ``` instead. Monoid returning the right-most non-`None` value | x | y | concat(x, y) | | ------- | ------- | ------------ | | none | none | none | | some(a) | none | some(a) | | none | some(b) | some(b) | | some(a) | some(b) | some(b) | **Signature** ```ts export declare const getLastMonoid: () => Monoid> ``` **Example** ```ts import { getLastMonoid, some, none } from 'fp-ts/Option' const M = getLastMonoid() assert.deepStrictEqual(M.concat(none, none), none) assert.deepStrictEqual(M.concat(some(1), none), some(1)) assert.deepStrictEqual(M.concat(none, some(2)), some(2)) assert.deepStrictEqual(M.concat(some(1), some(2)), some(2)) ``` Added in v2.0.0 ## ~~getRefinement~~ Use `Refinement` module instead. **Signature** ```ts export declare function getRefinement(getOption: (a: A) => Option): Refinement ``` Added in v2.0.0 ## ~~mapNullable~~ Use [`chainNullableK`](#chainnullablek) instead. **Signature** ```ts export declare const mapNullable: (f: (a: A) => B | null | undefined) => (ma: Option) => Option> ``` Added in v2.0.0 ## ~~option~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `O.Functor` instead of `O.option` (where `O` is from `import O from 'fp-ts/Option'`) **Signature** ```ts export declare const option: Monad1<'Option'> & Foldable1<'Option'> & Alternative1<'Option'> & Extend1<'Option'> & Witherable1<'Option'> & MonadThrow1<'Option'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/OptionT.ts.md ================================================ --- title: OptionT.ts nav_order: 69 parent: Modules --- ## OptionT overview Added in v2.0.0 ---

Table of contents

- [lifting](#lifting) - [fromPredicate](#frompredicate) - [pattern matching](#pattern-matching) - [match](#match) - [utils](#utils) - [alt](#alt) - [ap](#ap) - [chain](#chain) - [chainNullableK](#chainnullablek) - [chainOptionK](#chainoptionk) - [fromEither](#fromeither) - [fromF](#fromf) - [fromNullable](#fromnullable) - [fromNullableK](#fromnullablek) - [fromOptionK](#fromoptionk) - [getOrElse](#getorelse) - [map](#map) - [matchE](#matche) - [some](#some) - [zero](#zero) - [zone of death](#zone-of-death) - [~~OptionM1~~ (interface)](#optionm1-interface) - [~~OptionM2C~~ (interface)](#optionm2c-interface) - [~~OptionM2~~ (interface)](#optionm2-interface) - [~~OptionM~~ (interface)](#optionm-interface) - [~~OptionT1~~ (type alias)](#optiont1-type-alias) - [~~OptionT2~~ (type alias)](#optiont2-type-alias) - [~~OptionT~~ (interface)](#optiont-interface) - [~~getOptionM~~](#getoptionm) --- # lifting ## fromPredicate **Signature** ```ts export declare function fromPredicate( F: Pointed4 ): { (refinement: Refinement): (a: A) => Kind4>
(predicate: Predicate): (b: B) => Kind4> (predicate: Predicate): (a: A) => Kind4> } export declare function fromPredicate( F: Pointed3 ): { (refinement: Refinement): (a: A) => Kind3> (predicate: Predicate): (b: B) => Kind3> (predicate: Predicate): (a: A) => Kind3> } export declare function fromPredicate( F: Pointed3C ): { (refinement: Refinement): (a: A) => Kind3> (predicate: Predicate): (b: B) => Kind3> (predicate: Predicate): (a: A) => Kind3> } export declare function fromPredicate( F: Pointed2 ): { (refinement: Refinement): (a: A) => Kind2> (predicate: Predicate): (b: B) => Kind2> (predicate: Predicate): (a: A) => Kind2> } export declare function fromPredicate( F: Pointed2C ): { (refinement: Refinement): (a: A) => Kind2> (predicate: Predicate): (b: B) => Kind2> (predicate: Predicate): (a: A) => Kind2> } export declare function fromPredicate( F: Pointed1 ): { (refinement: Refinement): (a: A) => Kind> (predicate: Predicate): (b: B) => Kind> (predicate: Predicate): (a: A) => Kind> } export declare function fromPredicate(F: Pointed): { (refinement: Refinement): (a: A) => HKT> (predicate: Predicate): (b: B) => HKT> (predicate: Predicate): (a: A) => HKT> } ``` Added in v2.10.0 # pattern matching ## match **Signature** ```ts export declare function match( F: Functor4 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind4>) => Kind4 export declare function match( F: Functor3 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind3>) => Kind3 export declare function match( F: Functor3C ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind3>) => Kind3 export declare function match( F: Functor2 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind2>) => Kind2 export declare function match( F: Functor2C ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind2>) => Kind2 export declare function match( F: Functor1 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind>) => Kind export declare function match( F: Functor ): (onNone: () => B, onSome: (a: A) => B) => (ma: HKT>) => HKT ``` Added in v2.10.0 # utils ## alt **Signature** ```ts export declare function alt( M: Monad4 ): ( second: LazyArg>> ) => (first: Kind4>) => Kind4> export declare function alt( M: Monad3 ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export declare function alt( M: Monad3C ): (second: LazyArg>>) => (first: Kind3>) => Kind3> export declare function alt( M: Monad2 ): (second: LazyArg>>) => (first: Kind2>) => Kind2> export declare function alt( M: Monad2C ): (second: LazyArg>>) => (first: Kind2>) => Kind2> export declare function alt( M: Monad1 ): (second: LazyArg>>) => (first: Kind>) => Kind> export declare function alt( M: Monad ): (second: LazyArg>>) => (first: HKT>) => HKT> ``` Added in v2.10.0 ## ap **Signature** ```ts export declare function ap( F: Apply4 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export declare function ap( F: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C ): (fa: Kind3>) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply2 ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply1 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> ``` Added in v2.10.0 ## chain **Signature** ```ts export declare function chain( M: Monad4 ): ( f: (a: A) => Kind4> ) => (ma: Kind4>) => Kind4> export declare function chain( M: Monad3 ): (f: (a: A) => Kind3>) => (ma: Kind3>) => Kind3> export declare function chain( M: Monad3C ): (f: (a: A) => Kind3>) => (ma: Kind3>) => Kind3> export declare function chain( M: Monad2 ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export declare function chain( M: Monad2C ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export declare function chain( M: Monad1 ): (f: (a: A) => Kind>) => (ma: Kind>) => Kind> export declare function chain( M: Monad ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> ``` Added in v2.10.0 ## chainNullableK **Signature** ```ts export declare function chainNullableK( M: Monad4 ): ( f: (a: A) => B | null | undefined ) => (ma: Kind4>) => Kind4>> export declare function chainNullableK( M: Monad3 ): ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export declare function chainNullableK( M: Monad3C ): ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export declare function chainNullableK( M: Monad2 ): (f: (a: A) => B | null | undefined) => (ma: Kind2>) => Kind2>> export declare function chainNullableK( M: Monad2C ): (f: (a: A) => B | null | undefined) => (ma: Kind2>) => Kind2>> export declare function chainNullableK( M: Monad1 ): (f: (a: A) => B | null | undefined) => (ma: Kind>) => Kind>> export declare function chainNullableK( M: Monad ): (f: (a: A) => B | null | undefined) => (ma: HKT>) => HKT>> ``` Added in v2.10.0 ## chainOptionK **Signature** ```ts export declare function chainOptionK( M: Monad4 ): (f: (a: A) => Option) => (ma: Kind4>) => Kind4> export declare function chainOptionK( M: Monad3 ): (f: (a: A) => Option) => (ma: Kind3>) => Kind3> export declare function chainOptionK( M: Monad3C ): (f: (a: A) => Option) => (ma: Kind3>) => Kind3> export declare function chainOptionK( M: Monad2 ): (f: (a: A) => Option) => (ma: Kind2>) => Kind2> export declare function chainOptionK( M: Monad2C ): (f: (a: A) => Option) => (ma: Kind2>) => Kind2> export declare function chainOptionK( M: Monad1 ): (f: (a: A) => Option) => (ma: Kind>) => Kind> export declare function chainOptionK( M: Monad ): (f: (a: A) => Option) => (ma: HKT>) => HKT> ``` Added in v2.10.0 ## fromEither **Signature** ```ts export declare function fromEither( F: Pointed4 ): (e: Either) => Kind4> export declare function fromEither( F: Pointed3 ): (e: Either) => Kind3> export declare function fromEither( F: Pointed3C ): (e: Either) => Kind3> export declare function fromEither( F: Pointed2 ): (e: Either) => Kind2> export declare function fromEither( F: Pointed2C ): (e: Either) => Kind2> export declare function fromEither( F: Pointed2C ): (e: Either) => Kind2> export declare function fromEither(F: Pointed1): (e: Either) => Kind> export declare function fromEither(F: Pointed): (e: Either) => HKT> ``` Added in v2.10.0 ## fromF **Signature** ```ts export declare function fromF( F: Functor4 ): (ma: Kind4) => Kind4> export declare function fromF( F: Functor3 ): (ma: Kind3) => Kind3> export declare function fromF( F: Functor3C ): (ma: Kind3) => Kind3> export declare function fromF(F: Functor2): (ma: Kind2) => Kind2> export declare function fromF(F: Functor2C): (ma: Kind2) => Kind2> export declare function fromF(F: Functor1): (ma: Kind) => Kind> export declare function fromF(F: Functor): (ma: HKT) => HKT> ``` Added in v2.10.0 ## fromNullable **Signature** ```ts export declare function fromNullable( F: Pointed4 ): (a: A) => Kind4>> export declare function fromNullable( F: Pointed3 ): (a: A) => Kind3>> export declare function fromNullable( F: Pointed3C ): (a: A) => Kind3>> export declare function fromNullable( F: Pointed2 ): (a: A) => Kind2>> export declare function fromNullable( F: Pointed2C ): (a: A) => Kind2>> export declare function fromNullable(F: Pointed1): (a: A) => Kind>> export declare function fromNullable(F: Pointed): (a: A) => HKT>> ``` Added in v2.10.0 ## fromNullableK **Signature** ```ts export declare function fromNullableK( F: Pointed4 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind4>> export declare function fromNullableK( F: Pointed3 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export declare function fromNullableK( F: Pointed3C ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export declare function fromNullableK( F: Pointed2 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export declare function fromNullableK( F: Pointed2C ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export declare function fromNullableK( F: Pointed1 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind>> export declare function fromNullableK( F: Pointed ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => HKT>> ``` Added in v2.10.0 ## fromOptionK **Signature** ```ts export declare function fromOptionK( F: Pointed4 ): , B>( f: (...a: A) => Option ) => (...a: A) => Kind4> export declare function fromOptionK( F: Pointed3 ): , B>(f: (...a: A) => Option) => (...a: A) => Kind3> export declare function fromOptionK( F: Pointed3C ): , B>(f: (...a: A) => Option) => (...a: A) => Kind3> export declare function fromOptionK( F: Pointed2 ): , B>(f: (...a: A) => Option) => (...a: A) => Kind2> export declare function fromOptionK( F: Pointed2C ): , B>(f: (...a: A) => Option) => (...a: A) => Kind2> export declare function fromOptionK( F: Pointed1 ): , B>(f: (...a: A) => Option) => (...a: A) => Kind> export declare function fromOptionK( F: Pointed ): , B>(f: (...a: A) => Option) => (...a: A) => HKT> ``` Added in v2.10.0 ## getOrElse **Signature** ```ts export declare function getOrElse( M: Monad4 ): (onNone: LazyArg>) => (fa: Kind4>) => Kind4 export declare function getOrElse( M: Monad3 ): (onNone: LazyArg>) => (fa: Kind3>) => Kind3 export declare function getOrElse( M: Monad3C ): (onNone: LazyArg>) => (fa: Kind3>) => Kind3 export declare function getOrElse( M: Monad2 ): (onNone: LazyArg>) => (fa: Kind2>) => Kind2 export declare function getOrElse( M: Monad2C ): (onNone: LazyArg>) => (fa: Kind2>) => Kind2 export declare function getOrElse( M: Monad1 ): (onNone: LazyArg>) => (fa: Kind>) => Kind export declare function getOrElse( M: Monad ): (onNone: LazyArg>) => (fa: HKT>) => HKT ``` Added in v2.10.0 ## map **Signature** ```ts export declare function map( F: Functor4 ): (f: (a: A) => B) => (fa: Kind4>) => Kind4> export declare function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export declare function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> ``` Added in v2.10.0 ## matchE **Signature** ```ts export declare function matchE( M: Chain4 ): ( onNone: () => Kind4, onSome: (a: A) => Kind4 ) => (ma: Kind4>) => Kind4 export declare function matchE( M: Chain3 ): ( onNone: () => Kind3, onSome: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export declare function matchE( M: Chain3C ): ( onNone: () => Kind3, onSome: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export declare function matchE( M: Chain2 ): ( onNone: () => Kind2, onSome: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export declare function matchE( M: Chain2C ): ( onNone: () => Kind2, onSome: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export declare function matchE( M: Chain1 ): (onNone: () => Kind, onSome: (a: A) => Kind) => (ma: Kind>) => Kind export declare function matchE( M: Chain ): (onNone: () => HKT, onSome: (a: A) => HKT) => (ma: HKT>) => HKT ``` Added in v2.10.0 ## some **Signature** ```ts export declare function some(F: Pointed4): (a: A) => Kind4> export declare function some(F: Pointed3): (a: A) => Kind3> export declare function some(F: Pointed3C): (a: A) => Kind3> export declare function some(F: Pointed2): (a: A) => Kind2> export declare function some(F: Pointed2C): (a: A) => Kind2> export declare function some(F: Pointed1): (a: A) => Kind> export declare function some(F: Pointed): (a: A) => HKT> ``` Added in v2.10.0 ## zero **Signature** ```ts export declare function zero(F: Pointed4): () => Kind4> export declare function zero(F: Pointed3): () => Kind3> export declare function zero(F: Pointed3C): () => Kind3> export declare function zero(F: Pointed2): () => Kind2> export declare function zero(F: Pointed2C): () => Kind2> export declare function zero(F: Pointed1): () => Kind> export declare function zero(F: Pointed): () => HKT> ``` Added in v2.10.0 # zone of death ## ~~OptionM1~~ (interface) **Signature** ```ts export interface OptionM1 extends ApplicativeComposition11 { readonly chain: (ma: OptionT1, f: (a: A) => OptionT1) => OptionT1 readonly alt: (fa: OptionT1, that: LazyArg>) => OptionT1 readonly fold: (ma: OptionT1, onNone: LazyArg>, onSome: (a: A) => Kind) => Kind readonly getOrElse: (ma: OptionT1, onNone: LazyArg>) => Kind readonly fromM: (ma: Kind) => OptionT1 readonly none: () => OptionT1 } ``` Added in v2.0.0 ## ~~OptionM2C~~ (interface) **Signature** ```ts export interface OptionM2C extends ApplicativeComposition2C1 { readonly chain: (ma: OptionT2, f: (a: A) => OptionT2) => OptionT2 readonly alt: (fa: OptionT2, that: LazyArg>) => OptionT2 readonly fold: ( ma: OptionT2, onNone: LazyArg>, onSome: (a: A) => Kind2 ) => Kind2 readonly getOrElse: (ma: OptionT2, onNone: LazyArg>) => Kind2 readonly fromM: (ma: Kind2) => OptionT2 readonly none: () => OptionT2 } ``` Added in v2.2.0 ## ~~OptionM2~~ (interface) **Signature** ```ts export interface OptionM2 extends ApplicativeComposition21 { readonly chain: (ma: OptionT2, f: (a: A) => OptionT2) => OptionT2 readonly alt: (fa: OptionT2, that: LazyArg>) => OptionT2 readonly fold: ( ma: OptionT2, onNone: LazyArg>, onSome: (a: A) => Kind2 ) => Kind2 readonly getOrElse: (ma: OptionT2, onNone: LazyArg>) => Kind2 readonly fromM: (ma: Kind2) => OptionT2 readonly none: () => OptionT2 } ``` Added in v2.0.0 ## ~~OptionM~~ (interface) **Signature** ```ts export interface OptionM extends ApplicativeCompositionHKT1 { readonly chain: (ma: OptionT, f: (a: A) => OptionT) => OptionT readonly alt: (fa: OptionT, that: LazyArg>) => OptionT readonly fold: (ma: OptionT, onNone: LazyArg>, onSome: (a: A) => HKT) => HKT readonly getOrElse: (ma: OptionT, onNone: LazyArg>) => HKT readonly fromM: (ma: HKT) => OptionT readonly none: () => OptionT } ``` Added in v2.0.0 ## ~~OptionT1~~ (type alias) **Signature** ```ts export type OptionT1 = Kind> ``` Added in v2.0.0 ## ~~OptionT2~~ (type alias) **Signature** ```ts export type OptionT2 = Kind2> ``` Added in v2.0.0 ## ~~OptionT~~ (interface) **Signature** ```ts export interface OptionT extends HKT> {} ``` Added in v2.0.0 ## ~~getOptionM~~ **Signature** ```ts export declare function getOptionM(M: Monad2): OptionM2 export declare function getOptionM(M: Monad2C): OptionM2C export declare function getOptionM(M: Monad1): OptionM1 export declare function getOptionM(M: Monad): OptionM ``` Added in v2.0.0 ================================================ FILE: docs/modules/Ord.ts.md ================================================ --- title: Ord.ts nav_order: 70 parent: Modules --- ## Ord overview The `Ord` type class represents types which support comparisons with a _total order_. Instances should satisfy the laws of total orderings: 1. Reflexivity: `S.compare(a, a) <= 0` 2. Antisymmetry: if `S.compare(a, b) <= 0` and `S.compare(b, a) <= 0` then `a <-> b` 3. Transitivity: if `S.compare(a, b) <= 0` and `S.compare(b, c) <= 0` then `S.compare(a, c) <= 0` Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [fromCompare](#fromcompare) - [defaults](#defaults) - [equalsDefault](#equalsdefault) - [instances](#instances) - [Contravariant](#contravariant) - [getMonoid](#getmonoid) - [getSemigroup](#getsemigroup) - [model](#model) - [Ord (interface)](#ord-interface) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [between](#between) - [clamp](#clamp) - [contramap](#contramap) - [equals](#equals) - [geq](#geq) - [gt](#gt) - [leq](#leq) - [lt](#lt) - [max](#max) - [min](#min) - [reverse](#reverse) - [trivial](#trivial) - [tuple](#tuple) - [zone of death](#zone-of-death) - [~~getDualOrd~~](#getdualord) - [~~getTupleOrd~~](#gettupleord) - [~~ordBoolean~~](#ordboolean) - [~~ordDate~~](#orddate) - [~~ordNumber~~](#ordnumber) - [~~ordString~~](#ordstring) - [~~ord~~](#ord) --- # constructors ## fromCompare **Signature** ```ts export declare const fromCompare:
(compare: (first: A, second: A) => Ordering) => Ord ``` Added in v2.0.0 # defaults ## equalsDefault **Signature** ```ts export declare const equalsDefault: (compare: (first: A, second: A) => Ordering) => (x: A, y: A) => boolean ``` Added in v2.10.0 # instances ## Contravariant **Signature** ```ts export declare const Contravariant: Contravariant1<'Ord'> ``` Added in v2.7.0 ## getMonoid Returns a `Monoid` such that: - its `concat(ord1, ord2)` operation will order first by `ord1`, and then by `ord2` - its `empty` value is an `Ord` that always considers compared elements equal **Signature** ```ts export declare const getMonoid: () => Monoid> ``` **Example** ```ts import { sort } from 'fp-ts/Array' import { contramap, reverse, getMonoid } from 'fp-ts/Ord' import * as S from 'fp-ts/string' import * as B from 'fp-ts/boolean' import { pipe } from 'fp-ts/function' import { concatAll } from 'fp-ts/Monoid' import * as N from 'fp-ts/number' interface User { readonly id: number readonly name: string readonly age: number readonly rememberMe: boolean } const byName = pipe( S.Ord, contramap((p: User) => p.name) ) const byAge = pipe( N.Ord, contramap((p: User) => p.age) ) const byRememberMe = pipe( B.Ord, contramap((p: User) => p.rememberMe) ) const M = getMonoid() const users: Array = [ { id: 1, name: 'Guido', age: 47, rememberMe: false }, { id: 2, name: 'Guido', age: 46, rememberMe: true }, { id: 3, name: 'Giulio', age: 44, rememberMe: false }, { id: 4, name: 'Giulio', age: 44, rememberMe: true }, ] // sort by name, then by age, then by `rememberMe` const O1 = concatAll(M)([byName, byAge, byRememberMe]) assert.deepStrictEqual(sort(O1)(users), [ { id: 3, name: 'Giulio', age: 44, rememberMe: false }, { id: 4, name: 'Giulio', age: 44, rememberMe: true }, { id: 2, name: 'Guido', age: 46, rememberMe: true }, { id: 1, name: 'Guido', age: 47, rememberMe: false }, ]) // now `rememberMe = true` first, then by name, then by age const O2 = concatAll(M)([reverse(byRememberMe), byName, byAge]) assert.deepStrictEqual(sort(O2)(users), [ { id: 4, name: 'Giulio', age: 44, rememberMe: true }, { id: 2, name: 'Guido', age: 46, rememberMe: true }, { id: 3, name: 'Giulio', age: 44, rememberMe: false }, { id: 1, name: 'Guido', age: 47, rememberMe: false }, ]) ``` Added in v2.4.0 ## getSemigroup A typical use case for the `Semigroup` instance of `Ord` is merging two or more orderings. For example the following snippet builds an `Ord` for a type `User` which sorts by `created` date descending, and **then** `lastName` **Signature** ```ts export declare const getSemigroup: () => Semigroup> ``` **Example** ```ts import * as D from 'fp-ts/Date' import { pipe } from 'fp-ts/function' import { contramap, getSemigroup, Ord, reverse } from 'fp-ts/Ord' import * as RA from 'fp-ts/ReadonlyArray' import * as S from 'fp-ts/string' interface User { readonly id: string readonly lastName: string readonly created: Date } const ordByLastName: Ord = pipe( S.Ord, contramap((user) => user.lastName) ) const ordByCreated: Ord = pipe( D.Ord, contramap((user) => user.created) ) const ordUserByCreatedDescThenLastName = getSemigroup().concat(reverse(ordByCreated), ordByLastName) assert.deepStrictEqual( RA.sort(ordUserByCreatedDescThenLastName)([ { id: 'c', lastName: 'd', created: new Date(1973, 10, 30) }, { id: 'a', lastName: 'b', created: new Date(1973, 10, 30) }, { id: 'e', lastName: 'f', created: new Date(1980, 10, 30) }, ]), [ { id: 'e', lastName: 'f', created: new Date(1980, 10, 30) }, { id: 'a', lastName: 'b', created: new Date(1973, 10, 30) }, { id: 'c', lastName: 'd', created: new Date(1973, 10, 30) }, ] ) ``` Added in v2.0.0 # model ## Ord (interface) **Signature** ```ts export interface Ord extends Eq { readonly compare: (first: A, second: A) => Ordering } ``` Added in v2.0.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Ord' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## between Test whether a value is between a minimum and a maximum (inclusive) **Signature** ```ts export declare const between: (O: Ord) => (low: A, hi: A) => (a: A) => boolean ``` Added in v2.0.0 ## clamp Clamp a value between a minimum and a maximum **Signature** ```ts export declare const clamp: (O: Ord) => (low: A, hi: A) => (a: A) => A ``` Added in v2.0.0 ## contramap A typical use case for `contramap` would be like, given some `User` type, to construct an `Ord`. We can do so with a function from `User -> X` where `X` is some value that we know how to compare for ordering (meaning we have an `Ord`) For example, given the following `User` type, there are lots of possible choices for `X`, but let's say we want to sort a list of users by `lastName`. If we have a way of comparing `lastName`s for ordering (`ordLastName: Ord`) and we know how to go from `User -> string`, using `contramap` we can do this **Signature** ```ts export declare const contramap: (f: (b: B) => A) => (fa: Ord) => Ord ``` **Example** ```ts import { pipe } from 'fp-ts/function' import { contramap, Ord } from 'fp-ts/Ord' import * as RA from 'fp-ts/ReadonlyArray' import * as S from 'fp-ts/string' interface User { readonly firstName: string readonly lastName: string } const ordLastName: Ord = S.Ord const ordByLastName: Ord = pipe( ordLastName, contramap((user) => user.lastName) ) assert.deepStrictEqual( RA.sort(ordByLastName)([ { firstName: 'a', lastName: 'd' }, { firstName: 'c', lastName: 'b' }, ]), [ { firstName: 'c', lastName: 'b' }, { firstName: 'a', lastName: 'd' }, ] ) ``` Added in v2.0.0 ## equals **Signature** ```ts export declare const equals: (O: Ord) => (second: A) => (first: A) => boolean ``` Added in v2.11.0 ## geq Test whether one value is _non-strictly greater than_ another **Signature** ```ts export declare const geq: (O: Ord) => (first: A, second: A) => boolean ``` Added in v2.0.0 ## gt Test whether one value is _strictly greater than_ another **Signature** ```ts export declare const gt: (O: Ord) => (first: A, second: A) => boolean ``` Added in v2.0.0 ## leq Test whether one value is _non-strictly less than_ another **Signature** ```ts export declare const leq: (O: Ord) => (first: A, second: A) => boolean ``` Added in v2.0.0 ## lt Test whether one value is _strictly less than_ another **Signature** ```ts export declare const lt: (O: Ord) => (first: A, second: A) => boolean ``` Added in v2.0.0 ## max Take the maximum of two values. If they are considered equal, the first argument is chosen **Signature** ```ts export declare const max: (O: Ord) => (first: A, second: A) => A ``` Added in v2.0.0 ## min Take the minimum of two values. If they are considered equal, the first argument is chosen **Signature** ```ts export declare const min: (O: Ord) => (first: A, second: A) => A ``` Added in v2.0.0 ## reverse **Signature** ```ts export declare const reverse: (O: Ord) => Ord ``` Added in v2.10.0 ## trivial **Signature** ```ts export declare const trivial: Ord ``` Added in v2.11.0 ## tuple Given a tuple of `Ord`s returns an `Ord` for the tuple. **Signature** ```ts export declare const tuple: (...ords: { [K in keyof A]: Ord }) => Ord> ``` **Example** ```ts import { tuple } from 'fp-ts/Ord' import * as B from 'fp-ts/boolean' import * as S from 'fp-ts/string' import * as N from 'fp-ts/number' const O = tuple(S.Ord, N.Ord, B.Ord) assert.strictEqual(O.compare(['a', 1, true], ['b', 2, true]), -1) assert.strictEqual(O.compare(['a', 1, true], ['a', 2, true]), -1) assert.strictEqual(O.compare(['a', 1, true], ['a', 1, false]), 1) ``` Added in v2.10.0 # zone of death ## ~~getDualOrd~~ Use [`reverse`](#reverse) instead. **Signature** ```ts export declare const getDualOrd: (O: Ord) => Ord ``` Added in v2.0.0 ## ~~getTupleOrd~~ Use [`tuple`](#tuple) instead. **Signature** ```ts export declare const getTupleOrd: []>( ...ords: T ) => Ord<{ [K in keyof T]: T[K] extends Ord ? A : never }> ``` Added in v2.0.0 ## ~~ordBoolean~~ Use [`Ord`](./boolean.ts.html#ord) instead. **Signature** ```ts export declare const ordBoolean: Ord ``` Added in v2.0.0 ## ~~ordDate~~ Use [`Ord`](./Date.ts.html#ord) instead. **Signature** ```ts export declare const ordDate: Ord ``` Added in v2.0.0 ## ~~ordNumber~~ Use [`Ord`](./number.ts.html#ord) instead. **Signature** ```ts export declare const ordNumber: Ord ``` Added in v2.0.0 ## ~~ordString~~ Use [`Ord`](./string.ts.html#ord) instead. **Signature** ```ts export declare const ordString: Ord ``` Added in v2.0.0 ## ~~ord~~ Use [`Contravariant`](#contravariant) instead. **Signature** ```ts export declare const ord: Contravariant1<'Ord'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Ordering.ts.md ================================================ --- title: Ordering.ts nav_order: 71 parent: Modules --- ## Ordering overview Added in v2.0.0 ---

Table of contents

- [instances](#instances) - [Eq](#eq) - [Monoid](#monoid) - [Semigroup](#semigroup) - [model](#model) - [Ordering (type alias)](#ordering-type-alias) - [pattern matching](#pattern-matching) - [match](#match) - [matchW](#matchw) - [utils](#utils) - [reverse](#reverse) - [sign](#sign) - [zone of death](#zone-of-death) - [~~eqOrdering~~](#eqordering) - [~~invert~~](#invert) - [~~monoidOrdering~~](#monoidordering) - [~~semigroupOrdering~~](#semigroupordering) --- # instances ## Eq **Signature** ```ts export declare const Eq: E.Eq ``` Added in v2.10.0 ## Monoid **Signature** ```ts export declare const Monoid: M.Monoid ``` Added in v2.10.0 ## Semigroup **Signature** ```ts export declare const Semigroup: S.Semigroup ``` Added in v2.10.0 # model ## Ordering (type alias) **Signature** ```ts export type Ordering = -1 | 0 | 1 ``` Added in v2.0.0 # pattern matching ## match **Signature** ```ts export declare const match:
(onLessThan: () => A, onEqual: () => A, onGreaterThan: () => A) => (o: Ordering) => A ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLessThan: () => A, onEqual: () => B, onGreaterThan: () => C ) => (o: Ordering) => A | B | C ``` Added in v2.12.0 # utils ## reverse **Signature** ```ts export declare const reverse: (o: Ordering) => Ordering ``` Added in v2.10.0 ## sign **Signature** ```ts export declare const sign: (n: number) => Ordering ``` Added in v2.0.0 # zone of death ## ~~eqOrdering~~ Use [`Eq`](#eq) instead **Signature** ```ts export declare const eqOrdering: E.Eq ``` Added in v2.0.0 ## ~~invert~~ Use [`reverse`](#reverse) instead. **Signature** ```ts export declare const invert: (o: Ordering) => Ordering ``` Added in v2.0.0 ## ~~monoidOrdering~~ Use [`Monoid`](#monoid) instead **Signature** ```ts export declare const monoidOrdering: M.Monoid ``` Added in v2.4.0 ## ~~semigroupOrdering~~ Use [`Semigroup`](#semigroup) instead **Signature** ```ts export declare const semigroupOrdering: S.Semigroup ``` Added in v2.0.0 ================================================ FILE: docs/modules/Pointed.ts.md ================================================ --- title: Pointed.ts nav_order: 73 parent: Modules --- ## Pointed overview Added in v2.10.0 ---

Table of contents

- [model](#model) - [Pointed (interface)](#pointed-interface) - [Pointed1 (interface)](#pointed1-interface) - [Pointed2 (interface)](#pointed2-interface) - [Pointed2C (interface)](#pointed2c-interface) - [Pointed3 (interface)](#pointed3-interface) - [Pointed3C (interface)](#pointed3c-interface) - [Pointed4 (interface)](#pointed4-interface) --- # model ## Pointed (interface) **Signature** ```ts export interface Pointed { readonly URI: F readonly of:
(a: A) => HKT } ``` Added in v2.10.0 ## Pointed1 (interface) **Signature** ```ts export interface Pointed1 { readonly URI: F readonly of: (a: A) => Kind } ``` Added in v2.10.0 ## Pointed2 (interface) **Signature** ```ts export interface Pointed2 { readonly URI: F readonly of: (a: A) => Kind2 } ``` Added in v2.10.0 ## Pointed2C (interface) **Signature** ```ts export interface Pointed2C { readonly URI: F readonly _E: E readonly of: (a: A) => Kind2 } ``` Added in v2.10.0 ## Pointed3 (interface) **Signature** ```ts export interface Pointed3 { readonly URI: F readonly of: (a: A) => Kind3 } ``` Added in v2.10.0 ## Pointed3C (interface) **Signature** ```ts export interface Pointed3C { readonly URI: F readonly _E: E readonly of: (a: A) => Kind3 } ``` Added in v2.10.0 ## Pointed4 (interface) **Signature** ```ts export interface Pointed4 { readonly URI: F readonly of: (a: A) => Kind4 } ``` Added in v2.10.0 ================================================ FILE: docs/modules/Predicate.ts.md ================================================ --- title: Predicate.ts nav_order: 74 parent: Modules --- ## Predicate overview Added in v2.11.0 ---

Table of contents

- [instances](#instances) - [Contravariant](#contravariant) - [getMonoidAll](#getmonoidall) - [getMonoidAny](#getmonoidany) - [getSemigroupAll](#getsemigroupall) - [getSemigroupAny](#getsemigroupany) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [Predicate (interface)](#predicate-interface) - [and](#and) - [contramap](#contramap) - [not](#not) - [or](#or) --- # instances ## Contravariant **Signature** ```ts export declare const Contravariant: Contravariant1<'Predicate'> ``` Added in v2.11.0 ## getMonoidAll **Signature** ```ts export declare const getMonoidAll:
() => Monoid> ``` Added in v2.11.0 ## getMonoidAny **Signature** ```ts export declare const getMonoidAny: () => Monoid> ``` Added in v2.11.0 ## getSemigroupAll **Signature** ```ts export declare const getSemigroupAll: () => Semigroup> ``` Added in v2.11.0 ## getSemigroupAny **Signature** ```ts export declare const getSemigroupAny: () => Semigroup> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Predicate' ``` Added in v2.11.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.11.0 # utils ## Predicate (interface) **Signature** ```ts export interface Predicate { (a: A): boolean } ``` Added in v2.11.0 ## and **Signature** ```ts export declare const and: (second: Predicate) => (first: Predicate) => Predicate ``` Added in v2.11.0 ## contramap **Signature** ```ts export declare const contramap: (f: (b: B) => A) => (predicate: Predicate) => Predicate ``` Added in v2.11.0 ## not **Signature** ```ts export declare const not: (predicate: Predicate) => Predicate ``` Added in v2.11.0 ## or **Signature** ```ts export declare const or: (second: Predicate) => (first: Predicate) => Predicate ``` Added in v2.11.0 ================================================ FILE: docs/modules/Profunctor.ts.md ================================================ --- title: Profunctor.ts nav_order: 75 parent: Modules --- ## Profunctor overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Profunctor (interface)](#profunctor-interface) - [Profunctor2 (interface)](#profunctor2-interface) - [Profunctor2C (interface)](#profunctor2c-interface) - [Profunctor3 (interface)](#profunctor3-interface) - [Profunctor3C (interface)](#profunctor3c-interface) - [Profunctor4 (interface)](#profunctor4-interface) --- # model ## Profunctor (interface) **Signature** ```ts export interface Profunctor { readonly URI: F readonly map: (fa: HKT2, f: (a: A) => B) => HKT readonly promap: (fea: HKT2, f: (d: D) => E, g: (a: A) => B) => HKT2 } ``` Added in v2.0.0 ## Profunctor2 (interface) **Signature** ```ts export interface Profunctor2 extends Functor2 { readonly promap: (fea: Kind2, f: (d: D) => E, g: (a: A) => B) => Kind2 } ``` Added in v2.0.0 ## Profunctor2C (interface) **Signature** ```ts export interface Profunctor2C extends Functor2C { readonly promap: (fea: Kind2, f: (d: D) => E, g: (a: A) => B) => Kind2 } ``` Added in v2.0.0 ## Profunctor3 (interface) **Signature** ```ts export interface Profunctor3 extends Functor3 { readonly promap: (fea: Kind3, f: (d: D) => E, g: (a: A) => B) => Kind3 } ``` Added in v2.0.0 ## Profunctor3C (interface) **Signature** ```ts export interface Profunctor3C extends Functor3C { readonly promap: (fea: Kind3, f: (d: D) => E, g: (a: A) => B) => Kind3 } ``` Added in v2.2.0 ## Profunctor4 (interface) **Signature** ```ts export interface Profunctor4 extends Functor4 { readonly promap: (fea: Kind4, f: (d: D) => E, g: (a: A) => B) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Random.ts.md ================================================ --- title: Random.ts nav_order: 76 parent: Modules --- ## Random overview Added in v2.0.0 ---

Table of contents

- [utils](#utils) - [random](#random) - [randomBool](#randombool) - [randomElem](#randomelem) - [randomInt](#randomint) - [randomRange](#randomrange) --- # utils ## random Returns a random number between 0 (inclusive) and 1 (exclusive). This is a direct wrapper around JavaScript's `Math.random()`. **Signature** ```ts export declare const random: IO ``` Added in v2.0.0 ## randomBool Returns a random boolean value with an equal chance of being `true` or `false` **Signature** ```ts export declare const randomBool: IO ``` Added in v2.0.0 ## randomElem Returns a random element of a `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const randomElem:
(as: ReadonlyNonEmptyArray) => IO ``` Added in v2.10.0 ## randomInt Takes a range specified by `low` (the first argument) and `high` (the second), and returns a random integer uniformly distributed in the closed interval `[low, high]`. It is unspecified what happens if `low > high`, or if either of `low` or `high` is not an integer. **Signature** ```ts export declare function randomInt(low: number, high: number): IO ``` Added in v2.0.0 ## randomRange Returns a random number between a minimum value (inclusive) and a maximum value (exclusive). It is unspecified what happens if `maximum < minimum`. **Signature** ```ts export declare function randomRange(min: number, max: number): IO ``` Added in v2.0.0 ================================================ FILE: docs/modules/Reader.ts.md ================================================ --- title: Reader.ts nav_order: 77 parent: Modules --- ## Reader overview The `Reader` monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. Using `Reader` monad for such computations is often clearer and easier than using the `State` monad. In this example the `Reader` monad provides access to variable bindings. `Bindings` are a map of `number` variables. The variable count contains number of variables in the bindings. You can see how to run a `Reader` monad and retrieve data from it, how to access the `Reader` data with `ask` and `asks`. **Example** ```ts import { pipe } from 'fp-ts/function' import * as O from 'fp-ts/Option' import * as R from 'fp-ts/Reader' import * as RR from 'fp-ts/ReadonlyRecord' interface Bindings extends RR.ReadonlyRecord {} // The Reader monad, which implements this complicated check. const isCountCorrect: R.Reader = pipe( R.Do, R.bind('count', () => R.asks(lookupVar('count'))), R.bind('bindings', () => R.ask()), R.map(({ count, bindings }) => count === RR.size(bindings)) ) // The selector function to use with 'asks'. // Returns value of the variable with specified name. const lookupVar = (name: string) => (bindings: Bindings): number => pipe( bindings, RR.lookup(name), O.getOrElse(() => 0) ) const sampleBindings: Bindings = { count: 3, a: 1, b: 2 } assert.deepStrictEqual(isCountCorrect(sampleBindings), true) ``` Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [asksReader](#asksreader) - [asksReaderW](#asksreaderw) - [id](#id) - [of](#of) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [instances](#instances) - [Applicative](#applicative) - [Apply](#apply) - [Category](#category) - [Chain](#chain) - [Choice](#choice) - [Functor](#functor) - [Monad](#monad) - [Pointed](#pointed) - [Profunctor](#profunctor) - [Strong](#strong) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstW](#chainfirstw) - [chainW](#chainw) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [Reader (interface)](#reader-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [compose](#compose) - [first](#first) - [left](#left) - [local](#local) - [promap](#promap) - [right](#right) - [second](#second) - [zone of death](#zone-of-death) - [~~getMonoid~~](#getmonoid) - [~~getSemigroup~~](#getsemigroup) - [~~reader~~](#reader) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: Reader, f: (a: A) => Reader): Reader (f: (a: A) => Reader): (self: Reader) => Reader } ``` Added in v2.15.0 # constructors ## ask Reads the current context **Signature** ```ts export declare const ask: () => Reader ``` Added in v2.0.0 ## asks Projects a value from the global context in a Reader **Signature** ```ts export declare const asks: (f: (r: R) => A) => Reader ``` Added in v2.0.0 ## asksReader Effectfully accesses the environment. **Signature** ```ts export declare const asksReader: (f: (r: R) => Reader) => Reader ``` Added in v2.11.0 ## asksReaderW Less strict version of [`asksReader`](#asksreader). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const asksReaderW: (f: (r1: R1) => Reader) => Reader ``` Added in v2.11.0 ## id **Signature** ```ts export declare const id:
() => Reader ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => Reader ``` Added in v2.0.0 # do notation ## Do **Signature** ```ts export declare const Do: Reader ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: Reader ) => (fa: Reader) => Reader ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: Reader ) => (fa: Reader) => Reader ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => Reader ) => (ma: Reader) => Reader ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: Reader) => Reader ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => Reader ) => (fa: Reader) => Reader ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: Reader) => Reader ``` Added in v2.13.0 # instances ## Applicative **Signature** ```ts export declare const Applicative: Applicative2<'Reader'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply2<'Reader'> ``` Added in v2.10.0 ## Category **Signature** ```ts export declare const Category: Category2<'Reader'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'Reader'> ``` Added in v2.10.0 ## Choice **Signature** ```ts export declare const Choice: Choice2<'Reader'> ``` Added in v2.8.3 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Reader'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'Reader'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'Reader'> ``` Added in v2.10.0 ## Profunctor **Signature** ```ts export declare const Profunctor: Profunctor2<'Reader'> ``` Added in v2.7.0 ## Strong **Signature** ```ts export declare const Strong: Strong2<'Reader'> ``` Added in v2.8.3 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => Reader) => (ma: Reader) => Reader ``` Added in v2.0.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => Reader) => (first: Reader) => Reader ``` Added in v2.0.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => Reader ) => (ma: Reader) => Reader ``` Added in v2.11.0 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: (f: (a: A) => Reader) => (ma: Reader) => Reader ``` Added in v2.6.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Reader B>) => Reader ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Reader) => Reader ``` Added in v2.0.0 # model ## Reader (interface) **Signature** ```ts export interface Reader { (r: R): A } ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => Reader): (ma: Reader) => Reader (ma: Reader, f: (a: A) => Reader): Reader } ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: Reader>) => Reader ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const flattenW: (mma: Reader>) => Reader ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly Reader[]) => Reader ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => Reader ) => (as: readonly A[]) => Reader ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => Reader ) => (as: readonly A[]) => Reader ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => Reader ) => (as: readonly A[]) => Reader ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => Reader ) => (as: ReadonlyNonEmptyArray) => Reader> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Reader' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: Reader ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: Reader) => (fab: Reader B>) => Reader ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: Reader) => (first: Reader) => Reader ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apFirstW: (second: Reader) => (first: Reader) => Reader ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: Reader) => (first: Reader) => Reader ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apSecondW: (second: Reader) => (first: Reader) => Reader ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apW: (fa: Reader) => (fab: Reader B>) => Reader ``` Added in v2.8.0 ## compose **Signature** ```ts export declare const compose: (ab: Reader) => (bc: Reader) => Reader ``` Added in v2.0.0 ## first **Signature** ```ts export declare const first: (pab: Reader) => Reader<[A, C], [B, C]> ``` Added in v2.10.0 ## left **Signature** ```ts export declare const left: (pab: Reader) => Reader, E.Either> ``` Added in v2.10.0 ## local Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s `contramap`). **Signature** ```ts export declare const local: (f: (r2: R2) => R1) => (ma: Reader) => Reader ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as R from 'fp-ts/Reader' import * as string from 'fp-ts/string' const calculateContentLen: R.Reader = pipe( R.Do, R.bind('content', () => R.ask()), R.map(({ content }) => string.size(content)) ) // Calls calculateContentLen after adding a prefix to the Reader content. const calculateModifiedContentLen: R.Reader = pipe( calculateContentLen, R.local((s) => 'Prefix ' + s) ) const s = '12345' assert.deepStrictEqual( "Modified 's' length: " + calculateModifiedContentLen(s) + '\n' + "Original 's' length: " + calculateContentLen(s), "Modified 's' length: 12\nOriginal 's' length: 5" ) ``` Added in v2.0.0 ## promap **Signature** ```ts export declare const promap: (f: (d: D) => E, g: (a: A) => B) => (fea: Reader) => Reader ``` Added in v2.0.0 ## right **Signature** ```ts export declare const right: (pbc: Reader) => Reader, E.Either> ``` Added in v2.10.0 ## second **Signature** ```ts export declare const second: (pab: Reader) => Reader<[A, B], [A, C]> ``` Added in v2.10.0 # zone of death ## ~~getMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~reader~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `R.Functor` instead of `R.reader` (where `R` is from `import R from 'fp-ts/Reader'`) **Signature** ```ts export declare const reader: Monad2<'Reader'> & Profunctor2<'Reader'> & Category2<'Reader'> & Strong2<'Reader'> & Choice2<'Reader'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/ReaderEither.ts.md ================================================ --- title: ReaderEither.ts nav_order: 78 parent: Modules --- ## ReaderEither overview Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapReader](#tapreader) - [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [asksReaderEither](#asksreadereither) - [asksReaderEitherW](#asksreadereitherw) - [left](#left) - [leftReader](#leftreader) - [of](#of) - [right](#right) - [rightReader](#rightreader) - [conversions](#conversions) - [fromEither](#fromeither) - [fromOption](#fromoption) - [fromReader](#fromreader) - [toUnion](#tounion) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getAltReaderValidation](#getaltreadervalidation) - [getApplicativeReaderValidation](#getapplicativereadervalidation) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [mapBoth](#mapboth) - [mapError](#maperror) - [orElse](#orelse) - [orElseW](#orelsew) - [orLeft](#orleft) - [orLeftW](#orleftw) - [tapError](#taperror) - [filtering](#filtering) - [filterOrElse](#filterorelse) - [filterOrElseW](#filterorelsew) - [getCompactable](#getcompactable) - [getFilterable](#getfilterable) - [instances](#instances) - [Alt](#alt) - [Applicative](#applicative) - [Apply](#apply) - [Bifunctor](#bifunctor) - [Chain](#chain) - [FromEither](#fromeither) - [FromReader](#fromreader) - [Functor](#functor) - [Monad](#monad) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [legacy](#legacy) - [bimap](#bimap) - [chain](#chain) - [chainEitherK](#chaineitherk) - [chainEitherKW](#chaineitherkw) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstEitherKW](#chainfirsteitherkw) - [chainFirstReaderK](#chainfirstreaderk) - [chainFirstReaderKW](#chainfirstreaderkw) - [chainFirstW](#chainfirstw) - [chainOptionK](#chainoptionk) - [chainOptionKW](#chainoptionkw) - [chainReaderK](#chainreaderk) - [chainReaderKW](#chainreaderkw) - [chainW](#chainw) - [fromOptionK](#fromoptionk) - [mapLeft](#mapleft) - [orElseFirst](#orelsefirst) - [orElseFirstW](#orelsefirstw) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromPredicate](#frompredicate) - [fromReaderK](#fromreaderk) - [liftNullable](#liftnullable) - [liftOption](#liftoption) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [ReaderEither (interface)](#readereither-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapEither](#flatmapeither) - [flatMapNullable](#flatmapnullable) - [flatMapOption](#flatmapoption) - [flatMapReader](#flatmapreader) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [local](#local) - [swap](#swap) - [throwError](#throwerror) - [zone of death](#zone-of-death) - [~~getApplyMonoid~~](#getapplymonoid) - [~~getApplySemigroup~~](#getapplysemigroup) - [~~getReaderValidation~~](#getreadervalidation) - [~~getSemigroup~~](#getsemigroup) - [~~readerEither~~](#readereither) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: ReaderEither, f: (a: A) => ReaderEither): ReaderEither< R1 & R2, E1 | E2, A > (f: (a: A) => ReaderEither): ( self: ReaderEither ) => ReaderEither } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => E.Either): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => E.Either): ReaderEither } ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as RE from 'fp-ts/ReaderEither' const checkString = (value: string) => pipe( RE.ask(), RE.tapEither((minLength) => (value.length > minLength ? E.right('ok') : E.left('error'))) ) assert.deepStrictEqual(checkString('')(1), E.left('error')) assert.deepStrictEqual(checkString('fp-ts')(2), E.right(2)) ``` Added in v2.16.0 ## tapReader Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReader: { (f: (a: A) => R.Reader): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => R.Reader): ReaderEither } ``` Added in v2.16.0 # constructors ## ask Reads the current context. **Signature** ```ts export declare const ask: () => ReaderEither ``` Added in v2.0.0 ## asks Projects a value from the global context in a `ReaderEither`. **Signature** ```ts export declare const asks: (f: (r: R) => A) => ReaderEither ``` Added in v2.0.0 ## asksReaderEither Effectfully accesses the environment. **Signature** ```ts export declare const asksReaderEither: (f: (r: R) => ReaderEither) => ReaderEither ``` Added in v2.11.0 ## asksReaderEitherW Less strict version of [`asksReaderEither`](#asksreadereither). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const asksReaderEitherW: ( f: (r1: R1) => ReaderEither ) => ReaderEither ``` Added in v2.11.0 ## left **Signature** ```ts export declare const left: (e: E) => ReaderEither ``` Added in v2.0.0 ## leftReader **Signature** ```ts export declare const leftReader: (me: R.Reader) => ReaderEither ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => ReaderEither ``` Added in v2.8.5 ## right **Signature** ```ts export declare const right: (a: A) => ReaderEither ``` Added in v2.0.0 ## rightReader **Signature** ```ts export declare const rightReader: (ma: R.Reader) => ReaderEither ``` Added in v2.0.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: E.Either) => ReaderEither ``` Added in v2.0.0 ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option
) => ReaderEither ``` Added in v2.0.0 ## fromReader **Signature** ```ts export declare const fromReader: (fa: R.Reader) => ReaderEither ``` Added in v2.11.0 ## toUnion **Signature** ```ts export declare const toUnion: (fa: ReaderEither) => R.Reader ``` Added in v2.10.0 # do notation ## Do **Signature** ```ts export declare const Do: ReaderEither ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: ReaderEither ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: ReaderEither ) => ( fa: ReaderEither ) => ReaderEither ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: ( name: N ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => ReaderEither ) => ( fa: ReaderEither ) => ReaderEither ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => ( fa: ReaderEither ) => ReaderEither ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. **Signature** ```ts export declare const alt: ( that: () => ReaderEither ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the environment, the error and the return types will be merged. **Signature** ```ts export declare const altW: ( that: () => ReaderEither ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.9.0 ## getAltReaderValidation The default [`Alt`](#alt) instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getAltValidation`](./Either.ts.html#getaltvalidation). **Signature** ```ts export declare function getAltReaderValidation(S: Semigroup): Alt3C ``` Added in v2.7.0 ## getApplicativeReaderValidation The default [`Applicative`](#applicative) instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getApplicativeValidation`](./Either.ts.html#getapplicativevalidation). **Signature** ```ts export declare function getApplicativeReaderValidation(S: Semigroup): Applicative3C ``` Added in v2.7.0 ## getOrElse **Signature** ```ts export declare const getOrElse: ( onLeft: (e: E) => R.Reader ) => (ma: ReaderEither) => R.Reader ``` Added in v2.0.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: ( onLeft: (e: E) => R.Reader ) => (ma: ReaderEither) => R.Reader ``` Added in v2.6.0 ## mapBoth Returns a `ReaderEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. **Signature** ```ts export declare const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (e: E) => G, g: (a: A) => B): ReaderEither } ``` **Example** ```ts import * as ReaderEither from 'fp-ts/ReaderEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) const g = (n: number) => n * 2 assert.deepStrictEqual(ReaderEither.mapBoth(ReaderEither.right(1), f, g)({}), Either.right(2)) assert.deepStrictEqual(ReaderEither.mapBoth(ReaderEither.left('err'), f, g)({}), Either.left(new Error('err'))) ``` Added in v2.16.0 ## mapError Returns a `ReaderEither` with its error channel mapped using the specified function. **Signature** ```ts export declare const mapError: { (f: (e: E) => G): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (e: E) => G): ReaderEither } ``` **Example** ```ts import * as ReaderEither from 'fp-ts/ReaderEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) assert.deepStrictEqual(ReaderEither.mapError(ReaderEither.right(1), f)({}), Either.right(1)) assert.deepStrictEqual(ReaderEither.mapError(ReaderEither.left('err'), f)({}), Either.left(new Error('err'))) ``` Added in v2.16.0 ## orElse **Signature** ```ts export declare const orElse: ( onLeft: (e: E1) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## orElseW Less strict version of [`orElse`](#orelse). The `W` suffix (short for **W**idening) means that the environment types and the return types will be merged. **Signature** ```ts export declare const orElseW: ( onLeft: (e: E1) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.10.0 ## orLeft **Signature** ```ts export declare const orLeft: ( onLeft: (e: E1) => R.Reader ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.11.0 ## orLeftW **Signature** ```ts export declare const orLeftW: ( onLeft: (e: E1) => R.Reader ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.16.6 ## tapError Returns an effect that effectfully "peeks" at the failure of this effect. **Signature** ```ts export declare const tapError: { (onLeft: (e: E1) => ReaderEither): ( self: ReaderEither ) => ReaderEither (self: ReaderEither, onLeft: (e: E1) => ReaderEither): ReaderEither< R1 & R2, E1 | E2, A > } ``` Added in v2.15.0 # filtering ## filterOrElse **Signature** ```ts export declare const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): ( mb: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): (ma: ReaderEither) => ReaderEither } ``` Added in v2.0.0 ## filterOrElseW Less strict version of [`filterOrElse`](#filterorelse). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E2): ( ma: ReaderEither ) => ReaderEither } ``` Added in v2.9.0 ## getCompactable **Signature** ```ts export declare const getCompactable: (M: Monoid) => Compactable3C<'ReaderEither', E> ``` Added in v2.10.0 ## getFilterable **Signature** ```ts export declare function getFilterable(M: Monoid): Filterable3C ``` Added in v2.10.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt3<'ReaderEither'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative3<'ReaderEither'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply3<'ReaderEither'> ``` Added in v2.10.0 ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor3<'ReaderEither'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain3<'ReaderEither'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither3<'ReaderEither'> ``` Added in v2.10.0 ## FromReader **Signature** ```ts export declare const FromReader: FromReader3<'ReaderEither'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor3<'ReaderEither'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad3<'ReaderEither'> ``` Added in v2.7.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow3<'ReaderEither'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed3<'ReaderEither'> ``` Added in v2.10.0 # legacy ## bimap Alias of `mapBoth`. **Signature** ```ts export declare const bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## chainEitherK Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.4.0 ## chainEitherKW Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherKW: ( f: (a: A) => E.Either ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.6.1 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.12.0 ## chainFirstEitherKW Alias of `tapEither`. Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.12.0 ## chainFirstReaderK Alias of `tapReader`. **Signature** ```ts export declare const chainFirstReaderK: ( f: (a: A) => R.Reader ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.11.0 ## chainFirstReaderKW Alias of `tapReader`. Less strict version of [`chainReaderK`](#chainreaderk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.11.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.8.0 ## chainOptionK Use `flatMapOption`. **Signature** ```ts export declare const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderEither) => ReaderEither ``` Added in v2.10.0 ## chainOptionKW Use `flatMapOption`. **Signature** ```ts export declare const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderEither) => ReaderEither ``` Added in v2.13.2 ## chainReaderK Alias of `flatMapReader`. **Signature** ```ts export declare const chainReaderK: ( f: (a: A) => R.Reader ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.11.0 ## chainReaderKW Alias of `flatMapReader`. Less strict version of [`chainReaderK`](#chainreaderk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.11.0 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.6.0 ## fromOptionK Use `liftOption`. **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => ReaderEither ``` Added in v2.10.0 ## mapLeft Alias of `mapError`. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## orElseFirst Alias of `tapError`. **Signature** ```ts export declare const orElseFirst: ( onLeft: (e: E) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.11.0 ## orElseFirstW Alias of `tapError`. **Signature** ```ts export declare const orElseFirstW: ( onLeft: (e: E1) => ReaderEither ) => (ma: ReaderEither) => ReaderEither ``` Added in v2.11.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => E.Either ) => (...a: A) => ReaderEither ``` Added in v2.4.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): (b: B) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => ReaderEither } ``` Added in v2.0.0 ## fromReaderK **Signature** ```ts export declare const fromReaderK: ( f: (...a: A) => R.Reader ) => (...a: A) => ReaderEither ``` Added in v2.11.0 ## liftNullable **Signature** ```ts export declare const liftNullable: ( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => ReaderEither> ``` Added in v2.15.0 ## liftOption **Signature** ```ts export declare const liftOption: ( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => ReaderEither ``` Added in v2.15.0 # mapping ## as Maps the `Right` value of this `ReaderEither` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: ReaderEither) => ReaderEither (self: ReaderEither, a: A): ReaderEither } ``` Added in v2.16.0 ## asUnit Maps the `Right` value of this `ReaderEither` to the void constant value. **Signature** ```ts export declare const asUnit: (self: ReaderEither) => ReaderEither ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: ReaderEither B>) => ReaderEither ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: ReaderEither) => ReaderEither ``` Added in v2.0.0 # model ## ReaderEither (interface) **Signature** ```ts export interface ReaderEither extends Reader> {} ``` Added in v2.0.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: ( onLeft: (e: E) => R.Reader, onRight: (a: A) => R.Reader ) => (ma: ReaderEither) => R.Reader ``` Added in v2.0.0 ## foldW Alias of [`matchEW`](#matchew). **Signature** ```ts export declare const foldW: ( onLeft: (e: E) => R.Reader, onRight: (a: A) => R.Reader ) => (ma: ReaderEither) => R.Reader ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: ( onLeft: (e: E) => B, onRight: (a: A) => B ) => (ma: ReaderEither) => R.Reader ``` Added in v2.10.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Reader`). **Signature** ```ts export declare const matchE: ( onLeft: (e: E) => R.Reader, onRight: (a: A) => R.Reader ) => (ma: ReaderEither) => R.Reader ``` Added in v2.10.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onLeft: (e: E) => R.Reader, onRight: (a: A) => R.Reader ) => (ma: ReaderEither) => R.Reader ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C ) => (ma: R.Reader>) => R.Reader ``` Added in v2.10.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => ReaderEither): ( ma: ReaderEither ) => ReaderEither (ma: ReaderEither, f: (a: A) => ReaderEither): ReaderEither< R1 & R2, E1 | E2, B > } ``` Added in v2.14.0 ## flatMapEither **Signature** ```ts export declare const flatMapEither: { (f: (a: A) => E.Either): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => E.Either): ReaderEither } ``` Added in v2.15.0 ## flatMapNullable **Signature** ```ts export declare const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: ReaderEither ) => ReaderEither> ( self: ReaderEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2 ): ReaderEither> } ``` Added in v2.15.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: ReaderEither ) => ReaderEither (self: ReaderEither, f: (a: A) => Option, onNone: (a: A) => E2): ReaderEither< R, E1 | E2, B > } ``` Added in v2.15.0 ## flatMapReader **Signature** ```ts export declare const flatMapReader: { (f: (a: A) => R.Reader): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => R.Reader): ReaderEither } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: ReaderEither>) => ReaderEither ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const flattenW: ( mma: ReaderEither> ) => ReaderEither ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly ReaderEither[]) => ReaderEither ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => ReaderEither ) => (as: readonly A[]) => ReaderEither ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderEither ) => (as: readonly A[]) => ReaderEither ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => ReaderEither ) => (as: readonly A[]) => ReaderEither ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => ReaderEither ) => (as: ReadonlyNonEmptyArray) => ReaderEither> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReaderEither' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: ReaderEither ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: ( fa: ReaderEither ) => (fab: ReaderEither B>) => ReaderEither ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: ( second: ReaderEither ) => (first: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst) The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apFirstW: ( second: ReaderEither ) => (first: ReaderEither) => ReaderEither ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: ( second: ReaderEither ) => (first: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond) The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apSecondW: ( second: ReaderEither ) => (first: ReaderEither) => ReaderEither ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apW: ( fa: ReaderEither ) => (fab: ReaderEither B>) => ReaderEither ``` Added in v2.8.0 ## local Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s `contramap`). **Signature** ```ts export declare const local: (f: (r2: R2) => R1) => (ma: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## swap **Signature** ```ts export declare const swap: (ma: ReaderEither) => ReaderEither ``` Added in v2.0.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => ReaderEither ``` Added in v2.7.0 # zone of death ## ~~getApplyMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getApplyMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getApplySemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getApplySemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getReaderValidation~~ Use [`getApplicativeReaderValidation`](#getapplicativereadervalidation) and [`getAltReaderValidation`](#getaltreadervalidation) instead. **Signature** ```ts export declare function getReaderValidation( SE: Semigroup ): Monad3C & Bifunctor3 & Alt3C & MonadThrow3C ``` Added in v2.3.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~readerEither~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RE.Functor` instead of `RE.readerEither` (where `R` is from `import R from 'fp-ts/ReaderEither'`) **Signature** ```ts export declare const readerEither: Monad3<'ReaderEither'> & Bifunctor3<'ReaderEither'> & Alt3<'ReaderEither'> & MonadThrow3<'ReaderEither'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/ReaderIO.ts.md ================================================ --- title: ReaderIO.ts nav_order: 79 parent: Modules --- ## ReaderIO overview Added in v2.13.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapIO](#tapio) - [tapReader](#tapreader) - [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [asksReaderIO](#asksreaderio) - [asksReaderIOW](#asksreaderiow) - [of](#of) - [conversions](#conversions) - [fromIO](#fromio) - [fromReader](#fromreader) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [instances](#instances) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [FromIO](#fromio) - [FromReader](#fromreader) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [Pointed](#pointed) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstIOK](#chainfirstiok) - [chainFirstReaderK](#chainfirstreaderk) - [chainFirstReaderKW](#chainfirstreaderkw) - [chainFirstW](#chainfirstw) - [chainIOK](#chainiok) - [chainReaderK](#chainreaderk) - [chainReaderKW](#chainreaderkw) - [chainW](#chainw) - [lifting](#lifting) - [fromIOK](#fromiok) - [fromReaderK](#fromreaderk) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [ReaderIO (interface)](#readerio-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapIO](#flatmapio) - [flatMapReader](#flatmapreader) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [apW](#apw) - [local](#local) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: ReaderIO, f: (a: A) => ReaderIO): ReaderIO (f: (a: A) => ReaderIO): (self: ReaderIO) => ReaderIO } ``` Added in v2.15.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => I.IO<_>): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => I.IO<_>): ReaderIO } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as RIO from 'fp-ts/ReaderIO' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effect = pipe( RIO.ask(), RIO.tapIO((value) => Console.log(`Hello, ${value}`)) ) async function test() { assert.deepStrictEqual(effect('fp-ts')(), 'fp-ts') } test() ``` Added in v2.16.0 ## tapReader Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReader: { (f: (a: A) => R.Reader): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => R.Reader): ReaderIO } ``` Added in v2.16.0 # constructors ## ask Reads the current context. **Signature** ```ts export declare const ask: () => ReaderIO ``` Added in v2.13.0 ## asks Projects a value from the global context in a `ReaderIO`. **Signature** ```ts export declare const asks: (f: (r: R) => A) => ReaderIO ``` Added in v2.13.0 ## asksReaderIO Effectfully accesses the environment. **Signature** ```ts export declare const asksReaderIO: (f: (r: R) => ReaderIO) => ReaderIO ``` Added in v2.13.0 ## asksReaderIOW Less strict version of [`asksReaderIO`](#asksreaderio). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const asksReaderIOW: (f: (r1: R1) => ReaderIO) => ReaderIO ``` Added in v2.13.0 ## of **Signature** ```ts export declare const of: (a: A) => ReaderIO ``` Added in v2.13.0 # conversions ## fromIO **Signature** ```ts export declare const fromIO: (fa: I.IO
) => ReaderIO ``` Added in v2.13.0 ## fromReader **Signature** ```ts export declare const fromReader: (fa: R.Reader) => ReaderIO ``` Added in v2.13.0 # do notation ## Do **Signature** ```ts export declare const Do: ReaderIO ``` Added in v2.13.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: ReaderIO ) => (fa: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: ReaderIO ) => (fa: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => ReaderIO ) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## bindW The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => ReaderIO ) => (fa: ReaderIO) => ReaderIO ``` Added in v2.13.0 # instances ## Applicative **Signature** ```ts export declare const Applicative: Applicative2<'ReaderIO'> ``` Added in v2.13.0 ## Apply **Signature** ```ts export declare const Apply: Apply2<'ReaderIO'> ``` Added in v2.13.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'ReaderIO'> ``` Added in v2.13.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO2<'ReaderIO'> ``` Added in v2.13.0 ## FromReader **Signature** ```ts export declare const FromReader: FromReader2<'ReaderIO'> ``` Added in v2.13.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'ReaderIO'> ``` Added in v2.13.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'ReaderIO'> ``` Added in v2.13.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO2<'ReaderIO'> ``` Added in v2.13.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'ReaderIO'> ``` Added in v2.13.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => ReaderIO) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => ReaderIO) => (first: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => I.IO) => (first: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainFirstReaderK Alias of `tapReader`. **Signature** ```ts export declare const chainFirstReaderK: (f: (a: A) => R.Reader) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainFirstReaderKW Alias of `tapReader`. Less strict version of [`chainFirstReaderK`](#chainfirstreaderk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => ReaderIO ) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => I.IO) => (first: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainReaderK Alias of `flatMapReader`. **Signature** ```ts export declare const chainReaderK: (f: (a: A) => R.Reader) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainReaderKW Alias of `flatMapReader`. Less strict version of [`chainReaderK`](#chainreaderk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => ReaderIO ) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 # lifting ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => I.IO ) => (...a: A) => ReaderIO ``` Added in v2.13.0 ## fromReaderK **Signature** ```ts export declare const fromReaderK: ( f: (...a: A) => R.Reader ) => (...a: A) => ReaderIO ``` Added in v2.13.0 # mapping ## as Maps the value to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: ReaderIO) => ReaderIO (self: ReaderIO, a: A): ReaderIO } ``` Added in v2.16.0 ## asUnit Maps the value to the void constant value. **Signature** ```ts export declare const asUnit: (self: ReaderIO) => ReaderIO ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: ReaderIO B>) => ReaderIO ``` Added in v2.13.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: ReaderIO) => ReaderIO ``` Added in v2.13.0 # model ## ReaderIO (interface) **Signature** ```ts export interface ReaderIO { (r: R): I.IO } ``` Added in v2.13.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => ReaderIO): (ma: ReaderIO) => ReaderIO (ma: ReaderIO, f: (a: A) => ReaderIO): ReaderIO } ``` Added in v2.14.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => I.IO): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => I.IO): ReaderIO } ``` Added in v2.16.0 ## flatMapReader **Signature** ```ts export declare const flatMapReader: { (f: (a: A) => R.Reader): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => R.Reader): ReaderIO } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: ReaderIO>) => ReaderIO ``` Added in v2.13.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const flattenW: (mma: ReaderIO>) => ReaderIO ``` Added in v2.13.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly ReaderIO[]) => ReaderIO ``` Added in v2.13.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => ReaderIO ) => (as: readonly A[]) => ReaderIO ``` Added in v2.13.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderIO ) => (as: readonly A[]) => ReaderIO ``` Added in v2.13.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => ReaderIO ) => (as: readonly A[]) => ReaderIO ``` Added in v2.13.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => ReaderIO ) => (as: ReadonlyNonEmptyArray) => ReaderIO> ``` Added in v2.13.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReaderIO' ``` Added in v2.13.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.13.0 # utils ## ApT **Signature** ```ts export declare const ApT: ReaderIO ``` Added in v2.13.0 ## ap **Signature** ```ts export declare const ap: (fa: ReaderIO) => (fab: ReaderIO B>) => ReaderIO ``` Added in v2.13.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: ReaderIO) => (first: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: ReaderIO) => (first: ReaderIO) => ReaderIO ``` Added in v2.13.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apW: ( fa: ReaderIO ) => (fab: ReaderIO B>) => ReaderIO ``` Added in v2.13.0 ## local Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s `contramap`). **Signature** ```ts export declare const local: (f: (r2: R2) => R1) => (ma: ReaderIO) => ReaderIO ``` Added in v2.13.0 ================================================ FILE: docs/modules/ReaderT.ts.md ================================================ --- title: ReaderT.ts nav_order: 80 parent: Modules --- ## ReaderT overview The reader monad transformer, which adds a read-only environment to the given monad. The `of` function ignores the environment, while `chain` passes the inherited environment to both subcomputations. Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [fromNaturalTransformation](#fromnaturaltransformation) - [utils](#utils) - [ap](#ap) - [chain](#chain) - [fromReader](#fromreader) - [map](#map) - [of](#of) - [zone of death](#zone-of-death) - [~~ReaderM1~~ (interface)](#readerm1-interface) - [~~ReaderM2C~~ (interface)](#readerm2c-interface) - [~~ReaderM2~~ (interface)](#readerm2-interface) - [~~ReaderM3~~ (interface)](#readerm3-interface) - [~~ReaderM~~ (interface)](#readerm-interface) - [~~ReaderT1~~ (interface)](#readert1-interface) - [~~ReaderT2~~ (interface)](#readert2-interface) - [~~ReaderT3~~ (interface)](#readert3-interface) - [~~ReaderT~~ (interface)](#readert-interface) - [~~getReaderM~~](#getreaderm) --- # constructors ## fromNaturalTransformation **Signature** ```ts export declare function fromNaturalTransformation( nt: NaturalTransformation24S ): (f: (r: R) => Kind2) => Reader> export declare function fromNaturalTransformation( nt: NaturalTransformation23R ): (f: (r: R) => Kind2) => Reader> export declare function fromNaturalTransformation( nt: NaturalTransformation22 ): (f: (r: R) => Kind2) => Reader> export declare function fromNaturalTransformation( nt: NaturalTransformation12 ): (f: (r: R) => Kind) => Reader> export declare function fromNaturalTransformation( nt: NaturalTransformation11 ): (f: (r: R) => Kind) => Reader> export declare function fromNaturalTransformation( nt: NaturalTransformation ): (f: (r: R) => HKT) => Reader> ``` Added in v2.11.0 # utils ## ap **Signature** ```ts export declare function ap( F: Apply4 ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export declare function ap( F: Apply3 ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export declare function ap( F: Apply3C ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export declare function ap( F: Apply2 ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export declare function ap( F: Apply2C ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export declare function ap( F: Apply1 ): (fa: Reader>) => (fab: Reader B>>) => Reader> export declare function ap( F: Apply ): (fa: Reader>) => (fab: Reader B>>) => Reader> ``` Added in v2.10.0 ## chain **Signature** ```ts export declare function chain( M: Chain4 ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export declare function chain( M: Chain3 ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export declare function chain( M: Chain3C ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export declare function chain( M: Chain2 ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export declare function chain( M: Chain2C ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> export declare function chain( M: Chain1 ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> export declare function chain( M: Chain ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> ``` Added in v2.10.0 ## fromReader **Signature** ```ts export declare function fromReader( F: Pointed4 ): (ma: Reader) => Reader> export declare function fromReader( F: Pointed3 ): (ma: Reader) => Reader> export declare function fromReader( F: Pointed3C ): (ma: Reader) => Reader> export declare function fromReader( F: Pointed2 ): (ma: Reader) => Reader> export declare function fromReader( F: Pointed2C ): (ma: Reader) => Reader> export declare function fromReader(F: Pointed1): (ma: Reader) => Reader> export declare function fromReader(F: Pointed): (ma: Reader) => Reader> ``` Added in v2.10.0 ## map **Signature** ```ts export declare function map( F: Functor4 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export declare function map( F: Functor3 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export declare function map( F: Functor3C ): (f: (a: A) => B) => (fa: Reader>) => Reader> export declare function map( F: Functor2 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export declare function map( F: Functor2C ): (f: (a: A) => B) => (fa: Reader>) => Reader> export declare function map( F: Functor1 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export declare function map( F: Functor ): (f: (a: A) => B) => (fa: Reader>) => Reader> ``` Added in v2.10.0 ## of **Signature** ```ts export declare function of( F: Pointed4 ): (a: A) => Reader> export declare function of(F: Pointed3): (a: A) => Reader> export declare function of(F: Pointed3C): (a: A) => Reader> export declare function of(F: Pointed2): (a: A) => Reader> export declare function of(F: Pointed2C): (a: A) => Reader> export declare function of(F: Pointed1): (a: A) => Reader> export declare function of(F: Pointed): (a: A) => Reader> ``` Added in v2.10.0 # zone of death ## ~~ReaderM1~~ (interface) **Signature** ```ts export interface ReaderM1 { readonly map: (ma: ReaderT1, f: (a: A) => B) => ReaderT1 readonly of: (a: A) => ReaderT1 readonly ap: (mab: ReaderT1 B>, ma: ReaderT1) => ReaderT1 readonly chain: (ma: ReaderT1, f: (a: A) => ReaderT1) => ReaderT1 readonly ask: () => ReaderT1 readonly asks: (f: (r: R) => A) => ReaderT1 readonly local: (ma: ReaderT1, f: (d: R2) => R1) => ReaderT1 readonly fromReader: (ma: Reader) => ReaderT1 readonly fromM: (ma: Kind) => ReaderT1 } ``` Added in v2.0.0 ## ~~ReaderM2C~~ (interface) **Signature** ```ts export interface ReaderM2C { readonly map: (ma: ReaderT2, f: (a: A) => B) => ReaderT2 readonly of: (a: A) => ReaderT2 readonly ap: (mab: ReaderT2 B>, ma: ReaderT2) => ReaderT2 readonly chain: (ma: ReaderT2, f: (a: A) => ReaderT2) => ReaderT2 readonly ask: () => ReaderT2 readonly asks: (f: (r: R) => A) => ReaderT2 readonly local: (ma: ReaderT2, f: (d: R2) => R1) => ReaderT2 readonly fromReader: (ma: Reader) => ReaderT2 readonly fromM: (ma: Kind2) => ReaderT2 } ``` Added in v2.2.0 ## ~~ReaderM2~~ (interface) **Signature** ```ts export interface ReaderM2 { readonly map: (ma: ReaderT2, f: (a: A) => B) => ReaderT2 readonly of: (a: A) => ReaderT2 readonly ap: (mab: ReaderT2 B>, ma: ReaderT2) => ReaderT2 readonly chain: (ma: ReaderT2, f: (a: A) => ReaderT2) => ReaderT2 readonly ask: () => ReaderT2 readonly asks: (f: (r: R) => A) => ReaderT2 readonly local: (ma: ReaderT2, f: (d: R2) => R1) => ReaderT2 readonly fromReader: (ma: Reader) => ReaderT2 readonly fromM: (ma: Kind2) => ReaderT2 } ``` Added in v2.0.0 ## ~~ReaderM3~~ (interface) **Signature** ```ts export interface ReaderM3 { readonly map: (ma: ReaderT3, f: (a: A) => B) => ReaderT3 readonly of: (a: A) => ReaderT3 readonly ap: ( mab: ReaderT3 B>, ma: ReaderT3 ) => ReaderT3 readonly chain: ( ma: ReaderT3, f: (a: A) => ReaderT3 ) => ReaderT3 readonly ask: () => ReaderT3 readonly asks: (f: (r: R) => A) => ReaderT3 readonly local: (ma: ReaderT3, f: (d: R2) => R1) => ReaderT3 readonly fromReader: (ma: Reader) => ReaderT3 readonly fromM: (ma: Kind3) => ReaderT3 } ``` Added in v2.0.0 ## ~~ReaderM~~ (interface) **Signature** ```ts export interface ReaderM { readonly map: (ma: ReaderT, f: (a: A) => B) => ReaderT readonly of: (a: A) => ReaderT readonly ap: (mab: ReaderT B>, ma: ReaderT) => ReaderT readonly chain: (ma: ReaderT, f: (a: A) => ReaderT) => ReaderT readonly ask: () => ReaderT readonly asks: (f: (r: R) => A) => ReaderT readonly local: (ma: ReaderT, f: (d: R2) => R1) => ReaderT readonly fromReader: (ma: Reader) => ReaderT readonly fromM: (ma: HKT) => ReaderT } ``` Added in v2.0.0 ## ~~ReaderT1~~ (interface) **Signature** ```ts export interface ReaderT1 { (r: R): Kind } ``` Added in v2.0.0 ## ~~ReaderT2~~ (interface) **Signature** ```ts export interface ReaderT2 { (r: R): Kind2 } ``` Added in v2.0.0 ## ~~ReaderT3~~ (interface) **Signature** ```ts export interface ReaderT3 { (r: R): Kind3 } ``` Added in v2.0.0 ## ~~ReaderT~~ (interface) **Signature** ```ts export interface ReaderT { (r: R): HKT } ``` Added in v2.0.0 ## ~~getReaderM~~ **Signature** ```ts export declare function getReaderM(M: Monad3): ReaderM3 export declare function getReaderM(M: Monad2): ReaderM2 export declare function getReaderM(M: Monad2C): ReaderM2C export declare function getReaderM(M: Monad1): ReaderM1 export declare function getReaderM(M: Monad): ReaderM ``` Added in v2.0.0 ================================================ FILE: docs/modules/ReaderTask.ts.md ================================================ --- title: ReaderTask.ts nav_order: 81 parent: Modules --- ## ReaderTask overview Added in v2.3.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapIO](#tapio) - [tapReader](#tapreader) - [tapReaderIO](#tapreaderio) - [tapTask](#taptask) - [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [asksReaderTask](#asksreadertask) - [asksReaderTaskW](#asksreadertaskw) - [of](#of) - [conversions](#conversions) - [fromIO](#fromio) - [fromReader](#fromreader) - [fromReaderIO](#fromreaderio) - [fromTask](#fromtask) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [instances](#instances) - [ApplicativePar](#applicativepar) - [ApplicativeSeq](#applicativeseq) - [ApplyPar](#applypar) - [ApplySeq](#applyseq) - [Chain](#chain) - [FromIO](#fromio) - [FromReader](#fromreader) - [FromTask](#fromtask) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadTask](#monadtask) - [Pointed](#pointed) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstIOK](#chainfirstiok) - [chainFirstReaderIOK](#chainfirstreaderiok) - [chainFirstReaderIOKW](#chainfirstreaderiokw) - [chainFirstReaderK](#chainfirstreaderk) - [chainFirstReaderKW](#chainfirstreaderkw) - [chainFirstTaskK](#chainfirsttaskk) - [chainFirstW](#chainfirstw) - [chainIOK](#chainiok) - [chainReaderIOK](#chainreaderiok) - [chainReaderIOKW](#chainreaderiokw) - [chainReaderK](#chainreaderk) - [chainReaderKW](#chainreaderkw) - [chainTaskK](#chaintaskk) - [chainW](#chainw) - [lifting](#lifting) - [fromIOK](#fromiok) - [fromReaderIOK](#fromreaderiok) - [fromReaderK](#fromreaderk) - [fromTaskK](#fromtaskk) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [ReaderTask (interface)](#readertask-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapIO](#flatmapio) - [flatMapReader](#flatmapreader) - [flatMapReaderIO](#flatmapreaderio) - [flatMapTask](#flatmaptask) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [traverseSeqArray](#traverseseqarray) - [traverseSeqArrayWithIndex](#traverseseqarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [local](#local) - [zone of death](#zone-of-death) - [~~getMonoid~~](#getmonoid) - [~~getSemigroup~~](#getsemigroup) - [~~readerTaskSeq~~](#readertaskseq) - [~~readerTask~~](#readertask) - [~~run~~](#run) - [~~sequenceSeqArray~~](#sequenceseqarray) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: ReaderTask, f: (a: A) => ReaderTask): ReaderTask (f: (a: A) => ReaderTask): (self: ReaderTask) => ReaderTask } ``` Added in v2.15.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => IO<_>): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => IO<_>): ReaderTask } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as RT from 'fp-ts/ReaderTask' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effect = pipe( RT.ask(), RT.tapIO((value) => Console.log(`Hello, ${value}`)) ) async function test() { assert.deepStrictEqual(await effect('fp-ts')(), 'fp-ts') } test() ``` Added in v2.16.0 ## tapReader Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReader: { (f: (a: A) => R.Reader): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => R.Reader): ReaderTask } ``` Added in v2.16.0 ## tapReaderIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReaderIO: { (f: (a: A) => RIO.ReaderIO): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => RIO.ReaderIO): ReaderTask } ``` Added in v2.16.0 ## tapTask Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapTask: { (f: (a: A) => T.Task<_>): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => T.Task<_>): ReaderTask } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as RT from 'fp-ts/ReaderTask' import * as T from 'fp-ts/Task' const effect = pipe( RT.ask(), RT.tapTask((value) => T.of(value + 1)) ) async function test() { assert.deepStrictEqual(await effect(1)(), 1) } test() ``` Added in v2.16.0 # constructors ## ask Reads the current context. **Signature** ```ts export declare const ask: () => ReaderTask ``` Added in v2.3.0 ## asks Projects a value from the global context in a `ReaderTask`. **Signature** ```ts export declare const asks: (f: (r: R) => A) => ReaderTask ``` Added in v2.3.0 ## asksReaderTask Effectfully accesses the environment. **Signature** ```ts export declare const asksReaderTask: (f: (r: R) => ReaderTask) => ReaderTask ``` Added in v2.11.0 ## asksReaderTaskW Less strict version of [`asksReaderTask`](#asksreadertask). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const asksReaderTaskW: (f: (r1: R1) => ReaderTask) => ReaderTask ``` Added in v2.11.0 ## of **Signature** ```ts export declare const of: (a: A) => ReaderTask ``` Added in v2.3.0 # conversions ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO
) => ReaderTask ``` Added in v2.3.0 ## fromReader **Signature** ```ts export declare const fromReader: (fa: R.Reader) => ReaderTask ``` Added in v2.3.0 ## fromReaderIO **Signature** ```ts export declare const fromReaderIO: (fa: RIO.ReaderIO) => ReaderTask ``` Added in v2.13.0 ## fromTask **Signature** ```ts export declare const fromTask: (fa: T.Task) => ReaderTask ``` Added in v2.3.0 # do notation ## Do **Signature** ```ts export declare const Do: ReaderTask ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: ReaderTask ) => (fa: ReaderTask) => ReaderTask ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: ReaderTask ) => (fa: ReaderTask) => ReaderTask ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => ReaderTask ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: ReaderTask) => ReaderTask ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => ReaderTask ) => (fa: ReaderTask) => ReaderTask ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: ReaderTask) => ReaderTask ``` Added in v2.13.0 # instances ## ApplicativePar Runs computations in parallel. **Signature** ```ts export declare const ApplicativePar: Applicative2<'ReaderTask'> ``` Added in v2.7.0 ## ApplicativeSeq Runs computations sequentially. **Signature** ```ts export declare const ApplicativeSeq: Applicative2<'ReaderTask'> ``` Added in v2.7.0 ## ApplyPar Runs computations in parallel. **Signature** ```ts export declare const ApplyPar: Apply2<'ReaderTask'> ``` Added in v2.10.0 ## ApplySeq Runs computations sequentially. **Signature** ```ts export declare const ApplySeq: Apply2<'ReaderTask'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'ReaderTask'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO2<'ReaderTask'> ``` Added in v2.10.0 ## FromReader **Signature** ```ts export declare const FromReader: FromReader2<'ReaderTask'> ``` Added in v2.11.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask2<'ReaderTask'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'ReaderTask'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'ReaderTask'> ``` Added in v2.10.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO2<'ReaderTask'> ``` Added in v2.10.0 ## MonadTask **Signature** ```ts export declare const MonadTask: MonadTask2<'ReaderTask'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'ReaderTask'> ``` Added in v2.10.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => ReaderTask) => (ma: ReaderTask) => ReaderTask ``` Added in v2.3.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: ( f: (a: A) => ReaderTask ) => (first: ReaderTask) => ReaderTask ``` Added in v2.3.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => IO) => (first: ReaderTask) => ReaderTask ``` Added in v2.10.0 ## chainFirstReaderIOK Alias of `tapReaderIO`. **Signature** ```ts export declare const chainFirstReaderIOK: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.13.0 ## chainFirstReaderIOKW Alias of `tapReaderIO`. Less strict version of [`chainFirstReaderIOK`](#chainfirstreaderiok). **Signature** ```ts export declare const chainFirstReaderIOKW: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.13.0 ## chainFirstReaderK Alias of `tapReader`. **Signature** ```ts export declare const chainFirstReaderK: ( f: (a: A) => R.Reader ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.11.0 ## chainFirstReaderKW Alias of `tapReader`. Less strict version of [`chainFirstReaderK`](#chainfirstreaderk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.11.0 ## chainFirstTaskK Alias of `tapTask`. **Signature** ```ts export declare const chainFirstTaskK: (f: (a: A) => T.Task) => (first: ReaderTask) => ReaderTask ``` Added in v2.10.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => ReaderTask ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.11.0 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => IO) => (first: ReaderTask) => ReaderTask ``` Added in v2.4.0 ## chainReaderIOK Alias of `flatMapReaderIO`. **Signature** ```ts export declare const chainReaderIOK: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.13.0 ## chainReaderIOKW Alias of `flatMapReaderIO`. Less strict version of [`chainReaderIOK`](#chainreaderiok). **Signature** ```ts export declare const chainReaderIOKW: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.13.0 ## chainReaderK Alias of `flatMapReader`. **Signature** ```ts export declare const chainReaderK: (f: (a: A) => R.Reader) => (ma: ReaderTask) => ReaderTask ``` Added in v2.11.0 ## chainReaderKW Alias of `flatMapReader`. Less strict version of [`chainReaderK`](#chainreaderk). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.11.0 ## chainTaskK Alias of `flatMapTask`. **Signature** ```ts export declare const chainTaskK: (f: (a: A) => T.Task) => (first: ReaderTask) => ReaderTask ``` Added in v2.4.0 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => ReaderTask ) => (ma: ReaderTask) => ReaderTask ``` Added in v2.6.7 # lifting ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => IO ) => (...a: A) => ReaderTask ``` Added in v2.4.0 ## fromReaderIOK **Signature** ```ts export declare const fromReaderIOK: ( f: (...a: A) => RIO.ReaderIO ) => (...a: A) => ReaderTask ``` Added in v2.13.0 ## fromReaderK **Signature** ```ts export declare const fromReaderK: ( f: (...a: A) => R.Reader ) => (...a: A) => ReaderTask ``` Added in v2.11.0 ## fromTaskK **Signature** ```ts export declare const fromTaskK: ( f: (...a: A) => T.Task ) => (...a: A) => ReaderTask ``` Added in v2.4.0 # mapping ## as Maps the value to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: ReaderTask) => ReaderTask (self: ReaderTask, a: A): ReaderTask } ``` Added in v2.16.0 ## asUnit Maps the value to the void constant value. **Signature** ```ts export declare const asUnit: (self: ReaderTask) => ReaderTask ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: ReaderTask B>) => ReaderTask ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: ReaderTask) => ReaderTask ``` Added in v2.3.0 # model ## ReaderTask (interface) **Signature** ```ts export interface ReaderTask { (r: R): Task } ``` Added in v2.3.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => ReaderTask): (ma: ReaderTask) => ReaderTask (ma: ReaderTask, f: (a: A) => ReaderTask): ReaderTask } ``` Added in v2.14.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => IO): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => IO): ReaderTask } ``` Added in v2.16.0 ## flatMapReader **Signature** ```ts export declare const flatMapReader: { (f: (a: A) => R.Reader): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => R.Reader): ReaderTask } ``` Added in v2.16.0 ## flatMapReaderIO **Signature** ```ts export declare const flatMapReaderIO: { (f: (a: A) => RIO.ReaderIO): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => RIO.ReaderIO): ReaderTask } ``` Added in v2.16.0 ## flatMapTask **Signature** ```ts export declare const flatMapTask: { (f: (a: A) => T.Task): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => T.Task): ReaderTask } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: ReaderTask>) => ReaderTask ``` Added in v2.3.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const flattenW: (mma: ReaderTask>) => ReaderTask ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly ReaderTask[]) => ReaderTask ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => ReaderTask ) => (as: readonly A[]) => ReaderTask ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderTask ) => (as: readonly A[]) => ReaderTask ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => ReaderTask ) => (as: readonly A[]) => ReaderTask ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( f: (index: number, a: A) => ReaderTask ) => (as: readonly A[]) => ReaderTask ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => ReaderTask ) => (as: ReadonlyNonEmptyArray) => ReaderTask> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( f: (index: number, a: A) => ReaderTask ) => (as: ReadonlyNonEmptyArray) => ReaderTask> ``` Added in v2.11.0 ## traverseSeqArray Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArray: ( f: (a: A) => ReaderTask ) => (as: readonly A[]) => ReaderTask ``` Added in v2.10.0 ## traverseSeqArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => ReaderTask ) => (as: readonly A[]) => ReaderTask ``` Added in v2.10.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReaderTask' ``` Added in v2.3.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.3.0 # utils ## ApT **Signature** ```ts export declare const ApT: ReaderTask ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: ReaderTask) => (fab: ReaderTask B>) => ReaderTask ``` Added in v2.3.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: ReaderTask) => (first: ReaderTask) => ReaderTask ``` Added in v2.3.0 ## apFirstW Less strict version of [`apFirst`](#apfirst). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apFirstW: ( second: ReaderTask ) => (first: ReaderTask) => ReaderTask ``` Added in v2.17.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: ReaderTask) => (first: ReaderTask) => ReaderTask ``` Added in v2.3.0 ## apSecondW Less strict version of [`apSecond`](#apsecond). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apSecondW: ( second: ReaderTask ) => (first: ReaderTask) => ReaderTask ``` Added in v2.17.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const apW: ( fa: ReaderTask ) => (fab: ReaderTask B>) => ReaderTask ``` Added in v2.8.0 ## local Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s `contramap`). **Signature** ```ts export declare const local: (f: (r2: R2) => R1) => (ma: ReaderTask) => ReaderTask ``` Added in v2.3.0 # zone of death ## ~~getMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getMonoid: (M: Monoid) => Monoid> ``` Added in v2.3.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.3.0 ## ~~readerTaskSeq~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RT.Functor` instead of `RT.readerTaskSeq` (where `RT` is from `import RT from 'fp-ts/ReaderTask'`) **Signature** ```ts export declare const readerTaskSeq: MonadTask2<'ReaderTask'> ``` Added in v2.3.0 ## ~~readerTask~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RT.Functor` instead of `RT.readerTask` (where `RT` is from `import RT from 'fp-ts/ReaderTask'`) **Signature** ```ts export declare const readerTask: MonadTask2<'ReaderTask'> ``` Added in v2.3.0 ## ~~run~~ **Signature** ```ts export declare function run(ma: ReaderTask, r: R): Promise ``` Added in v2.4.0 ## ~~sequenceSeqArray~~ Use `traverseReadonlyArrayWithIndexSeq` instead. **Signature** ```ts export declare const sequenceSeqArray: (arr: readonly ReaderTask[]) => ReaderTask ``` Added in v2.10.0 ================================================ FILE: docs/modules/ReaderTaskEither.ts.md ================================================ --- title: ReaderTaskEither.ts nav_order: 82 parent: Modules --- ## ReaderTaskEither overview Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapIO](#tapio) - [tapReader](#tapreader) - [tapReaderEither](#tapreadereither) - [tapReaderIO](#tapreaderio) - [tapReaderTask](#tapreadertask) - [tapTask](#taptask) - [tapTaskEither](#taptaskeither) - [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [asksReaderTaskEither](#asksreadertaskeither) - [asksReaderTaskEitherW](#asksreadertaskeitherw) - [left](#left) - [leftIO](#leftio) - [leftReader](#leftreader) - [leftReaderIO](#leftreaderio) - [leftReaderTask](#leftreadertask) - [leftTask](#lefttask) - [of](#of) - [right](#right) - [rightIO](#rightio) - [rightReader](#rightreader) - [rightReaderIO](#rightreaderio) - [rightReaderTask](#rightreadertask) - [rightTask](#righttask) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromIOEither](#fromioeither) - [fromNullable](#fromnullable) - [fromOption](#fromoption) - [fromReader](#fromreader) - [fromReaderEither](#fromreadereither) - [fromTask](#fromtask) - [fromTaskEither](#fromtaskeither) - [toUnion](#tounion) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getAltReaderTaskValidation](#getaltreadertaskvalidation) - [getApplicativeReaderTaskValidation](#getapplicativereadertaskvalidation) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [mapBoth](#mapboth) - [mapError](#maperror) - [orElse](#orelse) - [orElseW](#orelsew) - [orLeft](#orleft) - [orLeftW](#orleftw) - [tapError](#taperror) - [filtering](#filtering) - [filterOrElse](#filterorelse) - [filterOrElseW](#filterorelsew) - [getCompactable](#getcompactable) - [getFilterable](#getfilterable) - [instances](#instances) - [Alt](#alt) - [ApplicativePar](#applicativepar) - [ApplicativeSeq](#applicativeseq) - [ApplyPar](#applypar) - [ApplySeq](#applyseq) - [Bifunctor](#bifunctor) - [Chain](#chain) - [FromEither](#fromeither) - [FromIO](#fromio) - [FromReader](#fromreader) - [FromTask](#fromtask) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadTask](#monadtask) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [~~getReaderTaskValidation~~](#getreadertaskvalidation) - [legacy](#legacy) - [bimap](#bimap) - [chain](#chain) - [chainEitherK](#chaineitherk) - [chainEitherKW](#chaineitherkw) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstEitherKW](#chainfirsteitherkw) - [chainFirstIOK](#chainfirstiok) - [chainFirstReaderEitherK](#chainfirstreadereitherk) - [chainFirstReaderEitherKW](#chainfirstreadereitherkw) - [chainFirstReaderIOK](#chainfirstreaderiok) - [chainFirstReaderIOKW](#chainfirstreaderiokw) - [chainFirstReaderK](#chainfirstreaderk) - [chainFirstReaderKW](#chainfirstreaderkw) - [chainFirstReaderTaskK](#chainfirstreadertaskk) - [chainFirstReaderTaskKW](#chainfirstreadertaskkw) - [chainFirstTaskEitherK](#chainfirsttaskeitherk) - [chainFirstTaskEitherKW](#chainfirsttaskeitherkw) - [chainFirstTaskK](#chainfirsttaskk) - [chainFirstW](#chainfirstw) - [chainIOEitherK](#chainioeitherk) - [chainIOEitherKW](#chainioeitherkw) - [chainIOK](#chainiok) - [chainNullableK](#chainnullablek) - [chainOptionK](#chainoptionk) - [chainOptionKW](#chainoptionkw) - [chainReaderEitherK](#chainreadereitherk) - [chainReaderEitherKW](#chainreadereitherkw) - [chainReaderIOK](#chainreaderiok) - [chainReaderIOKW](#chainreaderiokw) - [chainReaderK](#chainreaderk) - [chainReaderKW](#chainreaderkw) - [chainReaderTaskK](#chainreadertaskk) - [chainReaderTaskKW](#chainreadertaskkw) - [chainTaskEitherK](#chaintaskeitherk) - [chainTaskEitherKW](#chaintaskeitherkw) - [chainTaskK](#chaintaskk) - [chainW](#chainw) - [fromNullableK](#fromnullablek) - [fromOptionK](#fromoptionk) - [mapLeft](#mapleft) - [orElseFirst](#orelsefirst) - [orElseFirstW](#orelsefirstw) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromIOEitherK](#fromioeitherk) - [fromIOK](#fromiok) - [fromPredicate](#frompredicate) - [fromReaderEitherK](#fromreadereitherk) - [fromReaderIOK](#fromreaderiok) - [fromReaderK](#fromreaderk) - [fromReaderTaskK](#fromreadertaskk) - [fromTaskEitherK](#fromtaskeitherk) - [fromTaskK](#fromtaskk) - [liftNullable](#liftnullable) - [liftOption](#liftoption) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [ReaderTaskEither (interface)](#readertaskeither-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapEither](#flatmapeither) - [flatMapIO](#flatmapio) - [flatMapIOEither](#flatmapioeither) - [flatMapNullable](#flatmapnullable) - [flatMapOption](#flatmapoption) - [flatMapReader](#flatmapreader) - [flatMapReaderEither](#flatmapreadereither) - [flatMapReaderIO](#flatmapreaderio) - [flatMapReaderTask](#flatmapreadertask) - [flatMapTask](#flatmaptask) - [flatMapTaskEither](#flatmaptaskeither) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [sequenceSeqArray](#sequenceseqarray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [traverseSeqArray](#traverseseqarray) - [traverseSeqArrayWithIndex](#traverseseqarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [bracket](#bracket) - [bracketW](#bracketw) - [local](#local) - [swap](#swap) - [throwError](#throwerror) - [zone of death](#zone-of-death) - [~~getApplyMonoid~~](#getapplymonoid) - [~~getApplySemigroup~~](#getapplysemigroup) - [~~getSemigroup~~](#getsemigroup) - [~~readerTaskEitherSeq~~](#readertaskeitherseq) - [~~readerTaskEither~~](#readertaskeither) - [~~run~~](#run) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: ReaderTaskEither, f: (a: A) => ReaderTaskEither): ReaderTaskEither< R1 & R2, E1 | E2, A > (f: (a: A) => ReaderTaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => E.Either): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => E.Either): ReaderTaskEither } ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as RTE from 'fp-ts/ReaderTaskEither' const checkString = (value: string) => pipe( RTE.ask(), RTE.tapEither((minLength) => (value.length > minLength ? E.right('ok') : E.left('error'))) ) async function test() { assert.deepStrictEqual(await checkString('')(2)(), E.left('error')) assert.deepStrictEqual(await checkString('fp-ts')(2)(), E.right(2)) } test() ``` Added in v2.16.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => IO<_>): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => IO<_>): ReaderTaskEither } ``` **Example** ```ts import * as RTE from 'fp-ts/ReaderTaskEither' import * as E from 'fp-ts/Either' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effect = RTE.tapIO(RTE.ask(), (value) => Console.log(`Hello, ${value}`)) async function test() { assert.deepStrictEqual(await effect('fp-ts')(), E.of('fp-ts')) } test() ``` Added in v2.16.0 ## tapReader Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReader: { (f: (a: A) => R.Reader): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => R.Reader): ReaderTaskEither } ``` Added in v2.16.0 ## tapReaderEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReaderEither: { (f: (a: A) => ReaderEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderEither): ReaderTaskEither< R1 & R2, E1 | E2, A > } ``` Added in v2.16.0 ## tapReaderIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReaderIO: { (f: (a: A) => RIO.ReaderIO): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => RIO.ReaderIO): ReaderTaskEither } ``` Added in v2.16.0 ## tapReaderTask Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReaderTask: { (f: (a: A) => RT.ReaderTask): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => RT.ReaderTask): ReaderTaskEither< R1 & R2, E, A > } ``` Added in v2.16.0 ## tapTask Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapTask: { (f: (a: A) => T.Task<_>): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => T.Task<_>): ReaderTaskEither } ``` **Example** ```ts import * as RTE from 'fp-ts/ReaderTaskEither' import * as E from 'fp-ts/Either' import * as T from 'fp-ts/Task' const effect = RTE.tapTask(RTE.ask(), (value) => T.of(value + 1)) async function test() { assert.deepStrictEqual(await effect(1)(), E.of(1)) } test() ``` Added in v2.16.0 ## tapTaskEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapTaskEither: { (f: (a: A) => TE.TaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => TE.TaskEither): ReaderTaskEither< R, E1 | E2, A > } ``` Added in v2.16.0 # constructors ## ask Reads the current context. **Signature** ```ts export declare const ask: () => ReaderTaskEither ``` Added in v2.0.0 ## asks Projects a value from the global context in a `ReaderEither`. **Signature** ```ts export declare const asks: (f: (r: R) => A) => ReaderTaskEither ``` Added in v2.0.0 ## asksReaderTaskEither Effectfully accesses the environment. **Signature** ```ts export declare const asksReaderTaskEither: ( f: (r: R) => ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.11.0 ## asksReaderTaskEitherW Less strict version of [`asksReaderTaskEither`](#asksreadertaskeither). The `W` suffix (short for **W**idening) means that the environment types will be merged. **Signature** ```ts export declare const asksReaderTaskEitherW: ( f: (r1: R1) => ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.11.0 ## left **Signature** ```ts export declare const left: (e: E) => ReaderTaskEither ``` Added in v2.0.0 ## leftIO **Signature** ```ts export declare const leftIO: (me: IO) => ReaderTaskEither ``` Added in v2.0.0 ## leftReader **Signature** ```ts export declare const leftReader: (me: R.Reader) => ReaderTaskEither ``` Added in v2.0.0 ## leftReaderIO **Signature** ```ts export declare const leftReaderIO: (me: RIO.ReaderIO) => ReaderTaskEither ``` Added in v2.13.0 ## leftReaderTask **Signature** ```ts export declare const leftReaderTask: (me: RT.ReaderTask) => ReaderTaskEither ``` Added in v2.5.0 ## leftTask **Signature** ```ts export declare const leftTask: (me: T.Task) => ReaderTaskEither ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => ReaderTaskEither ``` Added in v2.7.0 ## right **Signature** ```ts export declare const right: (a: A) => ReaderTaskEither ``` Added in v2.0.0 ## rightIO **Signature** ```ts export declare const rightIO: (ma: IO
) => ReaderTaskEither ``` Added in v2.0.0 ## rightReader **Signature** ```ts export declare const rightReader: (ma: R.Reader) => ReaderTaskEither ``` Added in v2.0.0 ## rightReaderIO **Signature** ```ts export declare const rightReaderIO: (ma: RIO.ReaderIO) => ReaderTaskEither ``` Added in v2.13.0 ## rightReaderTask **Signature** ```ts export declare const rightReaderTask: (ma: RT.ReaderTask) => ReaderTaskEither ``` Added in v2.5.0 ## rightTask **Signature** ```ts export declare const rightTask: (ma: T.Task) => ReaderTaskEither ``` Added in v2.0.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: E.Either) => ReaderTaskEither ``` Added in v2.0.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO) => ReaderTaskEither ``` Added in v2.0.0 ## fromIOEither **Signature** ```ts export declare const fromIOEither: (fa: IOEither) => ReaderTaskEither ``` Added in v2.0.0 ## fromNullable **Signature** ```ts export declare const fromNullable: (e: E) => (a: A) => ReaderTaskEither> ``` Added in v2.12.0 ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option) => ReaderTaskEither ``` Added in v2.0.0 ## fromReader **Signature** ```ts export declare const fromReader: (fa: R.Reader) => ReaderTaskEither ``` Added in v2.11.0 ## fromReaderEither **Signature** ```ts export declare const fromReaderEither: (fa: ReaderEither) => ReaderTaskEither ``` Added in v2.0.0 ## fromTask **Signature** ```ts export declare const fromTask: (fa: T.Task) => ReaderTaskEither ``` Added in v2.0.0 ## fromTaskEither **Signature** ```ts export declare const fromTaskEither: (fa: TE.TaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## toUnion **Signature** ```ts export declare const toUnion: (fa: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.10.0 # do notation ## Do **Signature** ```ts export declare const Do: ReaderTaskEither ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: ReaderTaskEither ) => ( fa: ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: ReaderTaskEither ) => ( fa: ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => ReaderTaskEither ) => ( ma: ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: ( name: N ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => ReaderTaskEither ) => ( fa: ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => ( fa: ReaderTaskEither ) => ReaderTaskEither ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. **Signature** ```ts export declare const alt: ( that: () => ReaderTaskEither ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the environment, the error and the return types will be merged. **Signature** ```ts export declare const altW: ( that: () => ReaderTaskEither ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.9.0 ## getAltReaderTaskValidation The default [`Alt`](#alt) instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getAltValidation`](./Either.ts.html#getaltvalidation). **Signature** ```ts export declare function getAltReaderTaskValidation(S: Semigroup): Alt3C ``` Added in v2.7.0 ## getApplicativeReaderTaskValidation The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getApplicativeValidation`](./Either.ts.html#getapplicativevalidation). **Signature** ```ts export declare function getApplicativeReaderTaskValidation(A: Apply1, S: Semigroup): Applicative3C ``` Added in v2.7.0 ## getOrElse **Signature** ```ts export declare const getOrElse: ( onLeft: (e: E) => RT.ReaderTask ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.0.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: ( onLeft: (e: E) => RT.ReaderTask ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.6.0 ## mapBoth Returns a `ReaderTaskEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. **Signature** ```ts export declare const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (e: E) => G, g: (a: A) => B): ReaderTaskEither } ``` **Example** ```ts import * as ReaderTaskEither from 'fp-ts/ReaderTaskEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) const g = (n: number) => n * 2 async function test() { assert.deepStrictEqual(await ReaderTaskEither.mapBoth(ReaderTaskEither.right(1), f, g)({})(), Either.right(2)) assert.deepStrictEqual( await ReaderTaskEither.mapBoth(ReaderTaskEither.left('err'), f, g)({})(), Either.left(new Error('err')) ) } test() ``` Added in v2.16.0 ## mapError Returns a `ReaderTaskEither` with its error channel mapped using the specified function. **Signature** ```ts export declare const mapError: { (f: (e: E) => G): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (e: E) => G): ReaderTaskEither } ``` **Example** ```ts import * as ReaderTaskEither from 'fp-ts/ReaderTaskEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) async function test() { assert.deepStrictEqual(await ReaderTaskEither.mapError(ReaderTaskEither.right(1), f)({})(), Either.right(1)) assert.deepStrictEqual( await ReaderTaskEither.mapError(ReaderTaskEither.left('err'), f)({})(), Either.left(new Error('err')) ) } test() ``` Added in v2.16.0 ## orElse **Signature** ```ts export declare const orElse: ( onLeft: (e: E1) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## orElseW Less strict version of [`orElse`](#orelse). The `W` suffix (short for **W**idening) means that the environment types and the return types will be merged. **Signature** ```ts export declare const orElseW: ( onLeft: (e: E1) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.10.0 ## orLeft **Signature** ```ts export declare const orLeft: ( onLeft: (e: E1) => RT.ReaderTask ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## orLeftW **Signature** ```ts export declare const orLeftW: ( onLeft: (e: E1) => RT.ReaderTask ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.16.6 ## tapError Returns an effect that effectfully "peeks" at the failure of this effect. **Signature** ```ts export declare const tapError: { (onLeft: (e: E1) => ReaderTaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither ( self: ReaderTaskEither, onLeft: (e: E1) => ReaderTaskEither ): ReaderTaskEither } ``` Added in v2.15.0 # filtering ## filterOrElse **Signature** ```ts export declare const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( mb: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): (ma: ReaderTaskEither) => ReaderTaskEither } ``` Added in v2.0.0 ## filterOrElseW Less strict version of [`filterOrElse`](#filterorelse). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( ma: ReaderTaskEither ) => ReaderTaskEither } ``` Added in v2.9.0 ## getCompactable **Signature** ```ts export declare const getCompactable: (M: Monoid) => Compactable3C<'ReaderTaskEither', E> ``` Added in v2.10.0 ## getFilterable **Signature** ```ts export declare function getFilterable(M: Monoid): Filterable3C ``` Added in v2.10.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt3<'ReaderTaskEither'> ``` Added in v2.7.0 ## ApplicativePar Runs computations in parallel. **Signature** ```ts export declare const ApplicativePar: Applicative3<'ReaderTaskEither'> ``` Added in v2.7.0 ## ApplicativeSeq Runs computations sequentially. **Signature** ```ts export declare const ApplicativeSeq: Applicative3<'ReaderTaskEither'> ``` Added in v2.7.0 ## ApplyPar Runs computations in parallel. **Signature** ```ts export declare const ApplyPar: Apply3<'ReaderTaskEither'> ``` Added in v2.10.0 ## ApplySeq Runs computations sequentially. **Signature** ```ts export declare const ApplySeq: Apply3<'ReaderTaskEither'> ``` Added in v2.10.0 ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor3<'ReaderTaskEither'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain3<'ReaderTaskEither'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither3<'ReaderTaskEither'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO3<'ReaderTaskEither'> ``` Added in v2.10.0 ## FromReader **Signature** ```ts export declare const FromReader: FromReader3<'ReaderTaskEither'> ``` Added in v2.11.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask3<'ReaderTaskEither'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor3<'ReaderTaskEither'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad3<'ReaderTaskEither'> ``` Added in v2.10.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO3<'ReaderTaskEither'> ``` Added in v2.10.0 ## MonadTask **Signature** ```ts export declare const MonadTask: MonadTask3<'ReaderTaskEither'> ``` Added in v2.10.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow3<'ReaderTaskEither'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed3<'ReaderTaskEither'> ``` Added in v2.10.0 ## ~~getReaderTaskValidation~~ Use [`getApplicativeReaderTaskValidation`](#getapplicativereadertaskvalidation) and [`getAltReaderTaskValidation`](#getaltreadertaskvalidation) instead. **Signature** ```ts export declare function getReaderTaskValidation( SE: Semigroup ): Monad3C & Bifunctor3 & Alt3C & MonadTask3C & MonadThrow3C ``` Added in v2.3.0 # legacy ## bimap Alias of `mapBoth`. **Signature** ```ts export declare const bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## chainEitherK Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.4.0 ## chainEitherKW Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherKW: ( f: (a: A) => E.Either ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.6.1 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.12.0 ## chainFirstEitherKW Alias of `tapEither`. Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.12.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: ( f: (a: A) => IO ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.10.0 ## chainFirstReaderEitherK Alias of `tapReaderEither`. **Signature** ```ts export declare const chainFirstReaderEitherK: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstReaderEitherKW Alias of `tapReaderEither`. Less strict version of [`chainFirstReaderEitherK`](#chainfirstreadereitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstReaderEitherKW: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstReaderIOK Alias of `tapReaderIO`. **Signature** ```ts export declare const chainFirstReaderIOK: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.13.0 ## chainFirstReaderIOKW Alias of `tapReaderIO`. Less strict version of [`chainFirstReaderIOK`](#chainfirstreaderiok). **Signature** ```ts export declare const chainFirstReaderIOKW: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.13.0 ## chainFirstReaderK Alias of `tapReader`. **Signature** ```ts export declare const chainFirstReaderK: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstReaderKW Alias of `tapReader`. Less strict version of [`chainFirstReaderK`](#chainfirstreaderk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstReaderTaskK Alias of `tapReaderTask`. **Signature** ```ts export declare const chainFirstReaderTaskK: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstReaderTaskKW Alias of `tapReaderTask`. Less strict version of [`chainFirstReaderTaskK`](#chainfirstreadertaskk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstReaderTaskKW: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstTaskEitherK Alias of `tapTaskEither`. **Signature** ```ts export declare const chainFirstTaskEitherK: ( f: (a: A) => TE.TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstTaskEitherKW Alias of `tapTaskEither`. Less strict version of [`chainFirstTaskEitherK`](#chainfirsttaskeitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstTaskEitherKW: ( f: (a: A) => TE.TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainFirstTaskK Alias of `tapTask`. **Signature** ```ts export declare const chainFirstTaskK: ( f: (a: A) => T.Task ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.10.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.8.0 ## chainIOEitherK Alias of `flatMapIOEither`. **Signature** ```ts export declare const chainIOEitherK: ( f: (a: A) => IOEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.4.0 ## chainIOEitherKW Alias of `flatMapIOEither`. Less strict version of [`chainIOEitherK`](#chainioeitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainIOEitherKW: ( f: (a: A) => IOEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.6.1 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: ( f: (a: A) => IO ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.10.0 ## chainNullableK Use `flatMapNullable`. **Signature** ```ts export declare const chainNullableK: ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: ReaderTaskEither) => ReaderTaskEither> ``` Added in v2.12.0 ## chainOptionK Use `flatMapOption`. **Signature** ```ts export declare const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.10.0 ## chainOptionKW Use `flatMapOption`. **Signature** ```ts export declare const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.13.2 ## chainReaderEitherK Alias of `flatMapReaderEither`. **Signature** ```ts export declare const chainReaderEitherK: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainReaderEitherKW Alias of `flatMapReaderEither`. Less strict version of [`chainReaderEitherK`](#chainreadereitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainReaderEitherKW: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainReaderIOK Alias of `flatMapReaderIO`. **Signature** ```ts export declare const chainReaderIOK: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.13.0 ## chainReaderIOKW Alias of `flatMapReaderIO`. Less strict version of [`chainReaderIOK`](#chainreaderiok). **Signature** ```ts export declare const chainReaderIOKW: ( f: (a: A) => RIO.ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.13.0 ## chainReaderK Alias of `flatMapReader`. **Signature** ```ts export declare const chainReaderK: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainReaderKW Alias of `flatMapReader`. Less strict version of [`chainReaderK`](#chainreaderk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainReaderTaskK Alias of `flatMapReaderTask`. **Signature** ```ts export declare const chainReaderTaskK: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainReaderTaskKW Alias of `flatMapReaderTask`. Less strict version of [`chainReaderTaskK`](#chainreadertaskk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainReaderTaskKW: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## chainTaskEitherK Alias of `flatMapTaskEither`. **Signature** ```ts export declare const chainTaskEitherK: ( f: (a: A) => TE.TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.4.0 ## chainTaskEitherKW Alias of `flatMapTaskEither`. Less strict version of [`chainTaskEitherK`](#chaintaskeitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainTaskEitherKW: ( f: (a: A) => TE.TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.6.1 ## chainTaskK Alias of `flatMapTask`. **Signature** ```ts export declare const chainTaskK: ( f: (a: A) => T.Task ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.10.0 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.6.0 ## fromNullableK Use `liftNullable`. **Signature** ```ts export declare const fromNullableK: ( e: E ) => ( f: (...a: A) => B | null | undefined ) => (...a: A) => ReaderTaskEither> ``` Added in v2.12.0 ## fromOptionK Use `liftOption`. **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => ReaderTaskEither ``` Added in v2.10.0 ## mapLeft Alias of `mapError`. **Signature** ```ts export declare const mapLeft: ( f: (e: E) => G ) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## orElseFirst Alias of `tapError`. **Signature** ```ts export declare const orElseFirst: ( onLeft: (e: E) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 ## orElseFirstW Alias of `tapError`. **Signature** ```ts export declare const orElseFirstW: ( onLeft: (e: E1) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.11.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => E.Either ) => (...a: A) => ReaderTaskEither ``` Added in v2.4.0 ## fromIOEitherK **Signature** ```ts export declare const fromIOEitherK: ( f: (...a: A) => IOEither ) => (...a: A) => ReaderTaskEither ``` Added in v2.4.0 ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => IO ) => (...a: A) => ReaderTaskEither ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): ( a: A ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( b: B ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => ReaderTaskEither } ``` Added in v2.0.0 ## fromReaderEitherK **Signature** ```ts export declare const fromReaderEitherK: ( f: (...a: A) => ReaderEither ) => (...a: A) => ReaderTaskEither ``` Added in v2.11.0 ## fromReaderIOK **Signature** ```ts export declare const fromReaderIOK: ( f: (...a: A) => RIO.ReaderIO ) => (...a: A) => ReaderTaskEither ``` Added in v2.13.0 ## fromReaderK **Signature** ```ts export declare const fromReaderK: ( f: (...a: A) => R.Reader ) => (...a: A) => ReaderTaskEither ``` Added in v2.11.0 ## fromReaderTaskK **Signature** ```ts export declare const fromReaderTaskK: ( f: (...a: A) => RT.ReaderTask ) => (...a: A) => ReaderTaskEither ``` Added in v2.11.0 ## fromTaskEitherK **Signature** ```ts export declare const fromTaskEitherK: ( f: (...a: A) => TE.TaskEither ) => (...a: A) => ReaderTaskEither ``` Added in v2.4.0 ## fromTaskK **Signature** ```ts export declare const fromTaskK: ( f: (...a: A) => T.Task ) => (...a: A) => ReaderTaskEither ``` Added in v2.10.0 ## liftNullable **Signature** ```ts export declare const liftNullable: ( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => ReaderTaskEither> ``` Added in v2.15.0 ## liftOption **Signature** ```ts export declare const liftOption: ( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => ReaderTaskEither ``` Added in v2.15.0 # mapping ## as Maps the `Right` value of this `ReaderTaskEither` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, a: A): ReaderTaskEither } ``` Added in v2.16.0 ## asUnit Maps the `Right` value of this `ReaderTaskEither` to the void constant value. **Signature** ```ts export declare const asUnit: (self: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: ReaderTaskEither B>) => ReaderTaskEither ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 # model ## ReaderTaskEither (interface) **Signature** ```ts export interface ReaderTaskEither { (r: R): TaskEither } ``` Added in v2.0.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: ( onLeft: (e: E) => RT.ReaderTask, onRight: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.0.0 ## foldW Alias of [`matchEW`](#matchew). **Signature** ```ts export declare const foldW: ( onLeft: (e: E) => RT.ReaderTask, onRight: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: ( onLeft: (e: E) => B, onRight: (a: A) => B ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.10.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`ReaderTask`). **Signature** ```ts export declare const matchE: ( onLeft: (e: E) => RT.ReaderTask, onRight: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.10.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onLeft: (e: E) => RT.ReaderTask, onRight: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C ) => (ma: ReaderTaskEither) => RT.ReaderTask ``` Added in v2.10.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => ReaderTaskEither): ( ma: ReaderTaskEither ) => ReaderTaskEither (ma: ReaderTaskEither, f: (a: A) => ReaderTaskEither): ReaderTaskEither< R1 & R2, E1 | E2, B > } ``` Added in v2.14.0 ## flatMapEither **Signature** ```ts export declare const flatMapEither: { (f: (a: A) => E.Either): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => E.Either): ReaderTaskEither } ``` Added in v2.15.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => IO): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => IO): ReaderTaskEither } ``` Added in v2.16.0 ## flatMapIOEither **Signature** ```ts export declare const flatMapIOEither: { (f: (a: A) => IOEither): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => IOEither): ReaderTaskEither } ``` Added in v2.16.0 ## flatMapNullable **Signature** ```ts export declare const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: ReaderTaskEither ) => ReaderTaskEither> ( self: ReaderTaskEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2 ): ReaderTaskEither> } ``` Added in v2.15.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Option, onNone: (a: A) => E2): ReaderTaskEither< R, E1 | E2, B > } ``` Added in v2.15.0 ## flatMapReader **Signature** ```ts export declare const flatMapReader: { (f: (a: A) => R.Reader): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => R.Reader): ReaderTaskEither } ``` Added in v2.16.0 ## flatMapReaderEither **Signature** ```ts export declare const flatMapReaderEither: { (f: (a: A) => ReaderEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderEither): ReaderTaskEither< R1 & R2, E1 | E2, B > } ``` Added in v2.16.0 ## flatMapReaderIO **Signature** ```ts export declare const flatMapReaderIO: { (f: (a: A) => RIO.ReaderIO): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => RIO.ReaderIO): ReaderTaskEither } ``` Added in v2.16.0 ## flatMapReaderTask **Signature** ```ts export declare const flatMapReaderTask: { (f: (a: A) => RT.ReaderTask): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => RT.ReaderTask): ReaderTaskEither< R1 & R2, E, B > } ``` Added in v2.16.0 ## flatMapTask **Signature** ```ts export declare const flatMapTask: { (f: (a: A) => T.Task): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => T.Task): ReaderTaskEither } ``` Added in v2.16.0 ## flatMapTaskEither **Signature** ```ts export declare const flatMapTaskEither: { (f: (a: A) => TE.TaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => TE.TaskEither): ReaderTaskEither< R, E1 | E2, B > } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: ( mma: ReaderTaskEither> ) => ReaderTaskEither ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const flattenW: ( mma: ReaderTaskEither> ) => ReaderTaskEither ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: ( arr: readonly ReaderTaskEither[] ) => ReaderTaskEither ``` Added in v2.9.0 ## sequenceSeqArray Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. **Signature** ```ts export declare const sequenceSeqArray: ( arr: readonly ReaderTaskEither[] ) => ReaderTaskEither ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => ReaderTaskEither ) => (as: readonly A[]) => ReaderTaskEither ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: readonly A[]) => ReaderTaskEither ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: readonly A[]) => ReaderTaskEither ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: readonly A[]) => ReaderTaskEither ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: ReadonlyNonEmptyArray) => ReaderTaskEither> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: ReadonlyNonEmptyArray) => ReaderTaskEither> ``` Added in v2.11.0 ## traverseSeqArray Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArray: ( f: (a: A) => ReaderTaskEither ) => (as: readonly A[]) => ReaderTaskEither ``` Added in v2.9.0 ## traverseSeqArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: readonly A[]) => ReaderTaskEither ``` Added in v2.9.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReaderTaskEither' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: ReaderTaskEither ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: ( fa: ReaderTaskEither ) => (fab: ReaderTaskEither B>) => ReaderTaskEither ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: ( second: ReaderTaskEither ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apFirstW: ( second: ReaderTaskEither ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: ( second: ReaderTaskEither ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apSecondW: ( second: ReaderTaskEither ) => (first: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apW: ( fa: ReaderTaskEither ) => (fab: ReaderTaskEither B>) => ReaderTaskEither ``` Added in v2.8.0 ## bracket Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of whether the body action throws (\*) or returns. (\*) i.e. returns a `Left` **Signature** ```ts export declare function bracket( acquire: ReaderTaskEither, use: (a: A) => ReaderTaskEither, release: (a: A, e: Either) => ReaderTaskEither ): ReaderTaskEither ``` Added in v2.0.4 ## bracketW Less strict version of [`bracket`](#bracket). **Signature** ```ts export declare function bracketW( acquire: ReaderTaskEither, use: (a: A) => ReaderTaskEither, release: (a: A, e: Either) => ReaderTaskEither ): ReaderTaskEither ``` Added in v2.12.0 ## local Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s `contramap`). **Signature** ```ts export declare const local: ( f: (r2: R2) => R1 ) => (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## swap **Signature** ```ts export declare const swap: (ma: ReaderTaskEither) => ReaderTaskEither ``` Added in v2.0.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => ReaderTaskEither ``` Added in v2.0.0 # zone of death ## ~~getApplyMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getApplyMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getApplySemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values are concatenated using the provided `Semigroup` **Signature** ```ts export declare const getApplySemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~readerTaskEitherSeq~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RTE.Functor` instead of `RTE.readerTaskEitherSeq` (where `RTE` is from `import RTE from 'fp-ts/ReaderTaskEither'`) **Signature** ```ts export declare const readerTaskEitherSeq: Monad3<'ReaderTaskEither'> & Bifunctor3<'ReaderTaskEither'> & Alt3<'ReaderTaskEither'> & MonadTask3<'ReaderTaskEither'> & MonadThrow3<'ReaderTaskEither'> ``` Added in v2.0.0 ## ~~readerTaskEither~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RTE.Functor` instead of `RTE.readerTaskEither` (where `RTE` is from `import RTE from 'fp-ts/ReaderTaskEither'`) **Signature** ```ts export declare const readerTaskEither: Monad3<'ReaderTaskEither'> & Bifunctor3<'ReaderTaskEither'> & Alt3<'ReaderTaskEither'> & MonadTask3<'ReaderTaskEither'> & MonadThrow3<'ReaderTaskEither'> ``` Added in v2.0.0 ## ~~run~~ **Signature** ```ts export declare function run(ma: ReaderTaskEither, r: R): Promise> ``` Added in v2.0.0 ================================================ FILE: docs/modules/ReadonlyArray.ts.md ================================================ --- title: ReadonlyArray.ts nav_order: 83 parent: Modules --- ## ReadonlyArray overview Added in v2.5.0 ---

Table of contents

- [constructors](#constructors) - [makeBy](#makeby) - [of](#of) - [replicate](#replicate) - [conversions](#conversions) - [fromArray](#fromarray) - [fromEither](#fromeither) - [fromOption](#fromoption) - [toArray](#toarray) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [guard](#guard) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [partition](#partition) - [partitionMap](#partitionmap) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [separate](#separate) - [wilt](#wilt) - [wither](#wither) - [folding](#folding) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [instances](#instances) - [Alt](#alt) - [Alternative](#alternative) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [ChainRecBreadthFirst](#chainrecbreadthfirst) - [ChainRecDepthFirst](#chainrecdepthfirst) - [Compactable](#compactable) - [Extend](#extend) - [Filterable](#filterable) - [FilterableWithIndex](#filterablewithindex) - [Foldable](#foldable) - [FoldableWithIndex](#foldablewithindex) - [FromEither](#fromeither) - [Functor](#functor) - [FunctorWithIndex](#functorwithindex) - [Monad](#monad) - [Pointed](#pointed) - [Traversable](#traversable) - [TraversableWithIndex](#traversablewithindex) - [Unfoldable](#unfoldable) - [Witherable](#witherable) - [Zero](#zero) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getMonoid](#getmonoid) - [getOrd](#getord) - [getSemigroup](#getsemigroup) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [legacy](#legacy) - [chain](#chain) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [mapWithIndex](#mapwithindex) - [pattern matching](#pattern-matching) - [foldLeft](#foldleft) - [foldRight](#foldright) - [match](#match) - [matchLeft](#matchleft) - [matchLeftW](#matchleftw) - [matchRight](#matchright) - [matchRightW](#matchrightw) - [matchW](#matchw) - [refinements](#refinements) - [isEmpty](#isempty) - [isNonEmpty](#isnonempty) - [sequencing](#sequencing) - [chainFirst](#chainfirst) - [chainRecBreadthFirst](#chainrecbreadthfirst) - [chainRecDepthFirst](#chainrecdepthfirst) - [chainWithIndex](#chainwithindex) - [flatMap](#flatmap) - [flatten](#flatten) - [traverseWithIndex](#traversewithindex) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [unsafe](#unsafe) - [unsafeDeleteAt](#unsafedeleteat) - [unsafeInsertAt](#unsafeinsertat) - [unsafeUpdateAt](#unsafeupdateat) - [utils](#utils) - [Spanned (interface)](#spanned-interface) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [append](#append) - [appendW](#appendw) - [chop](#chop) - [chunksOf](#chunksof) - [comprehension](#comprehension) - [concat](#concat) - [concatW](#concatw) - [deleteAt](#deleteat) - [difference](#difference) - [dropLeft](#dropleft) - [dropLeftWhile](#dropleftwhile) - [dropRight](#dropright) - [duplicate](#duplicate) - [elem](#elem) - [empty](#empty) - [every](#every) - [exists](#exists) - [extend](#extend) - [filterE](#filtere) - [findFirst](#findfirst) - [findFirstMap](#findfirstmap) - [findIndex](#findindex) - [findLast](#findlast) - [findLastIndex](#findlastindex) - [findLastMap](#findlastmap) - [head](#head) - [init](#init) - [insertAt](#insertat) - [intercalate](#intercalate) - [intersection](#intersection) - [intersperse](#intersperse) - [isOutOfBound](#isoutofbound) - [last](#last) - [lefts](#lefts) - [lookup](#lookup) - [modifyAt](#modifyat) - [prepend](#prepend) - [prependAll](#prependall) - [prependW](#prependw) - [reverse](#reverse) - [rights](#rights) - [rotate](#rotate) - [scanLeft](#scanleft) - [scanRight](#scanright) - [size](#size) - [some](#some) - [sort](#sort) - [sortBy](#sortby) - [spanLeft](#spanleft) - [splitAt](#splitat) - [tail](#tail) - [takeLeft](#takeleft) - [takeLeftWhile](#takeleftwhile) - [takeRight](#takeright) - [unfold](#unfold) - [union](#union) - [uniq](#uniq) - [unzip](#unzip) - [updateAt](#updateat) - [zero](#zero) - [zip](#zip) - [zipWith](#zipwith) - [zone of death](#zone-of-death) - [~~cons~~](#cons) - [~~prependToAll~~](#prependtoall) - [~~range~~](#range) - [~~readonlyArray~~](#readonlyarray) - [~~snoc~~](#snoc) --- # constructors ## makeBy Return a `ReadonlyArray` of length `n` with element `i` initialized with `f(i)`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const makeBy:
(n: number, f: (i: number) => A) => readonly A[] ``` **Example** ```ts import { makeBy } from 'fp-ts/ReadonlyArray' const double = (n: number): number => n * 2 assert.deepStrictEqual(makeBy(5, double), [0, 2, 4, 6, 8]) ``` Added in v2.5.0 ## of **Signature** ```ts export declare const of: (a: A) => readonly A[] ``` Added in v2.5.0 ## replicate Create a `ReadonlyArray` containing a value repeated the specified number of times. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const replicate: (n: number, a: A) => readonly A[] ``` **Example** ```ts import { replicate } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(replicate(3, 'a'), ['a', 'a', 'a']) ``` Added in v2.5.0 # conversions ## fromArray **Signature** ```ts export declare const fromArray: (as: A[]) => readonly A[] ``` Added in v2.5.0 ## fromEither Transforms an `Either` to a `ReadonlyArray`. **Signature** ```ts export declare const fromEither: (fa: Either) => readonly A[] ``` Added in v2.11.0 ## fromOption **Signature** ```ts export declare const fromOption: (fa: Option) => readonly A[] ``` Added in v2.11.0 ## toArray **Signature** ```ts export declare const toArray: (as: readonly A[]) => A[] ``` Added in v2.5.0 # do notation ## Do **Signature** ```ts export declare const Do: readonly {}[] ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: readonly B[] ) => (fa: readonly A[]) => readonly { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[] ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => readonly B[] ) => (ma: readonly A[]) => readonly { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[] ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: readonly A[]) => readonly { readonly [K in N]: A }[] ``` Added in v2.8.0 ## guard **Signature** ```ts export declare const guard: (b: boolean) => readonly void[] ``` Added in v2.11.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: readonly A[]) => readonly { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[] ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. In case of `ReadonlyArray` concatenates the inputs into a single array. **Signature** ```ts export declare const alt: (that: LazyArg) => (fa: readonly A[]) => readonly A[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RA.alt(() => [4, 5]) ), [1, 2, 3, 4, 5] ) ``` Added in v2.5.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (that: LazyArg) => (fa: readonly A[]) => readonly (B | A)[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RA.altW(() => ['a', 'b']) ), [1, 2, 3, 'a', 'b'] ) ``` Added in v2.9.0 # filtering ## compact **Signature** ```ts export declare const compact: (fa: readonly Option[]) => readonly A[] ``` Added in v2.5.0 ## filter **Signature** ```ts export declare const filter: { (refinement: Refinement): (as: readonly A[]) => readonly B[] (predicate: Predicate): (bs: readonly B[]) => readonly B[] (predicate: Predicate): (as: readonly A[]) => readonly A[] } ``` Added in v2.5.0 ## filterMap **Signature** ```ts export declare const filterMap: (f: (a: A) => Option) => (fa: readonly A[]) => readonly B[] ``` Added in v2.5.0 ## filterMapWithIndex **Signature** ```ts export declare const filterMapWithIndex: (f: (i: number, a: A) => Option) => (fa: readonly A[]) => readonly B[] ``` Added in v2.5.0 ## filterWithIndex **Signature** ```ts export declare const filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (as: readonly A[]) => readonly B[] (predicateWithIndex: PredicateWithIndex): (bs: readonly B[]) => readonly B[] (predicateWithIndex: PredicateWithIndex): (as: readonly A[]) => readonly A[] } ``` Added in v2.5.0 ## partition **Signature** ```ts export declare const partition: { (refinement: Refinement): (as: readonly A[]) => Separated (predicate: Predicate): (bs: readonly B[]) => Separated (predicate: Predicate): (as: readonly A[]) => Separated } ``` Added in v2.5.0 ## partitionMap **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: readonly A[]) => Separated ``` Added in v2.5.0 ## partitionMapWithIndex **Signature** ```ts export declare const partitionMapWithIndex: ( f: (i: number, a: A) => Either ) => (fa: readonly A[]) => Separated ``` Added in v2.5.0 ## partitionWithIndex **Signature** ```ts export declare const partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( as: readonly A[] ) => Separated (predicateWithIndex: PredicateWithIndex): ( bs: readonly B[] ) => Separated (predicateWithIndex: PredicateWithIndex): (as: readonly A[]) => Separated } ``` Added in v2.5.0 ## separate **Signature** ```ts export declare const separate: (fa: readonly Either[]) => Separated ``` Added in v2.5.0 ## wilt **Signature** ```ts export declare const wilt: PipeableWilt1<'ReadonlyArray'> ``` Added in v2.6.5 ## wither **Signature** ```ts export declare const wither: PipeableWither1<'ReadonlyArray'> ``` Added in v2.6.5 # folding ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: readonly A[]) => M ``` Added in v2.5.0 ## foldMapWithIndex **Signature** ```ts export declare const foldMapWithIndex: (M: Monoid) => (f: (i: number, a: A) => M) => (fa: readonly A[]) => M ``` Added in v2.5.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: readonly A[]) => B ``` Added in v2.5.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: readonly A[]) => B ``` Added in v2.5.0 ## reduceRightWithIndex **Signature** ```ts export declare const reduceRightWithIndex: (b: B, f: (i: number, a: A, b: B) => B) => (fa: readonly A[]) => B ``` Added in v2.5.0 ## reduceWithIndex **Signature** ```ts export declare const reduceWithIndex: (b: B, f: (i: number, b: B, a: A) => B) => (fa: readonly A[]) => B ``` Added in v2.5.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'ReadonlyArray'> ``` Added in v2.7.0 ## Alternative **Signature** ```ts export declare const Alternative: Alternative1<'ReadonlyArray'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'ReadonlyArray'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'ReadonlyArray'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: Chain1<'ReadonlyArray'> ``` Added in v2.10.0 ## ChainRecBreadthFirst **Signature** ```ts export declare const ChainRecBreadthFirst: ChainRec1<'ReadonlyArray'> ``` Added in v2.11.0 ## ChainRecDepthFirst **Signature** ```ts export declare const ChainRecDepthFirst: ChainRec1<'ReadonlyArray'> ``` Added in v2.11.0 ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'ReadonlyArray'> ``` Added in v2.7.0 ## Extend **Signature** ```ts export declare const Extend: Extend1<'ReadonlyArray'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'ReadonlyArray'> ``` Added in v2.7.0 ## FilterableWithIndex **Signature** ```ts export declare const FilterableWithIndex: FilterableWithIndex1<'ReadonlyArray', number> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'ReadonlyArray'> ``` Added in v2.7.0 ## FoldableWithIndex **Signature** ```ts export declare const FoldableWithIndex: FoldableWithIndex1<'ReadonlyArray', number> ``` Added in v2.7.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither1<'ReadonlyArray'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'ReadonlyArray'> ``` Added in v2.7.0 ## FunctorWithIndex **Signature** ```ts export declare const FunctorWithIndex: FunctorWithIndex1<'ReadonlyArray', number> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'ReadonlyArray'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'ReadonlyArray'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'ReadonlyArray'> ``` Added in v2.7.0 ## TraversableWithIndex **Signature** ```ts export declare const TraversableWithIndex: TraversableWithIndex1<'ReadonlyArray', number> ``` Added in v2.7.0 ## Unfoldable **Signature** ```ts export declare const Unfoldable: Unfoldable1<'ReadonlyArray'> ``` Added in v2.7.0 ## Witherable **Signature** ```ts export declare const Witherable: Witherable1<'ReadonlyArray'> ``` Added in v2.7.0 ## Zero **Signature** ```ts export declare const Zero: Zero1<'ReadonlyArray'> ``` Added in v2.11.0 ## getDifferenceMagma **Signature** ```ts export declare const getDifferenceMagma: (E: Eq) => Magma ``` Added in v2.11.0 ## getEq Derives an `Eq` over the `ReadonlyArray` of a given element type from the `Eq` of that type. The derived `Eq` defines two arrays as equal if all elements of both arrays are compared equal pairwise with the given `E`. In case of arrays of different lengths, the result is non equality. **Signature** ```ts export declare const getEq: (E: Eq) => Eq ``` **Example** ```ts import * as S from 'fp-ts/string' import { getEq } from 'fp-ts/ReadonlyArray' const E = getEq(S.Eq) assert.strictEqual(E.equals(['a', 'b'], ['a', 'b']), true) assert.strictEqual(E.equals(['a'], []), false) ``` Added in v2.5.0 ## getIntersectionSemigroup **Signature** ```ts export declare const getIntersectionSemigroup: (E: Eq) => Semigroup ``` Added in v2.11.0 ## getMonoid Returns a `Monoid` for `ReadonlyArray`. **Signature** ```ts export declare const getMonoid: () => Monoid ``` **Example** ```ts import { getMonoid } from 'fp-ts/ReadonlyArray' const M = getMonoid() assert.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4]) ``` Added in v2.5.0 ## getOrd Derives an `Ord` over the `ReadonlyArray` of a given element type from the `Ord` of that type. The ordering between two such arrays is equal to: the first non equal comparison of each arrays elements taken pairwise in increasing order, in case of equality over all the pairwise elements; the longest array is considered the greatest, if both arrays have the same length, the result is equality. **Signature** ```ts export declare const getOrd: (O: Ord) => Ord ``` **Example** ```ts import { getOrd } from 'fp-ts/ReadonlyArray' import * as S from 'fp-ts/string' const O = getOrd(S.Ord) assert.strictEqual(O.compare(['b'], ['a']), 1) assert.strictEqual(O.compare(['a'], ['a']), 0) assert.strictEqual(O.compare(['a'], ['b']), -1) ``` Added in v2.5.0 ## getSemigroup **Signature** ```ts export declare const getSemigroup: () => Semigroup ``` Added in v2.5.0 ## getShow **Signature** ```ts export declare const getShow: (S: Show) => Show ``` Added in v2.5.0 ## getUnionMonoid **Signature** ```ts export declare const getUnionMonoid: (E: Eq) => Monoid ``` Added in v2.11.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq) => Semigroup ``` Added in v2.11.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => readonly B[]) => (ma: readonly A[]) => readonly B[] ``` Added in v2.5.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => Either ) => (...a: A) => readonly B[] ``` Added in v2.11.0 ## fromOptionK **Signature** ```ts export declare const fromOptionK: ( f: (...a: A) => Option ) => (...a: A) => readonly B[] ``` Added in v2.11.0 ## fromPredicate **Signature** ```ts export declare function fromPredicate(refinement: Refinement): (a: A) => ReadonlyArray export declare function fromPredicate(predicate: Predicate): (b: B) => ReadonlyArray export declare function fromPredicate(predicate: Predicate): (a: A) => ReadonlyArray ``` Added in v2.11.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: readonly ((a: A) => B)[]) => readonly B[] ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: readonly A[]) => readonly B[] ``` Added in v2.5.0 ## mapWithIndex **Signature** ```ts export declare const mapWithIndex: (f: (i: number, a: A) => B) => (fa: readonly A[]) => readonly B[] ``` Added in v2.5.0 # pattern matching ## foldLeft Alias of [`matchLeft`](#matchleft). **Signature** ```ts export declare const foldLeft: ( onEmpty: LazyArg, onNonEmpty: (head: A, tail: readonly A[]) => B ) => (as: readonly A[]) => B ``` Added in v2.5.0 ## foldRight Alias of [`matchRight`](#matchright). **Signature** ```ts export declare const foldRight: ( onEmpty: LazyArg, onNonEmpty: (init: readonly A[], last: A) => B ) => (as: readonly A[]) => B ``` Added in v2.5.0 ## match **Signature** ```ts export declare const match: ( onEmpty: LazyArg, onNonEmpty: (as: RNEA.ReadonlyNonEmptyArray) => B ) => (as: readonly A[]) => B ``` Added in v2.11.0 ## matchLeft Break a `ReadonlyArray` into its first element and remaining elements. **Signature** ```ts export declare const matchLeft: ( onEmpty: LazyArg, onNonEmpty: (head: A, tail: readonly A[]) => B ) => (as: readonly A[]) => B ``` **Example** ```ts import { matchLeft } from 'fp-ts/ReadonlyArray' const len: (as: ReadonlyArray) => number = matchLeft( () => 0, (_, tail) => 1 + len(tail) ) assert.strictEqual(len([1, 2, 3]), 3) ``` Added in v2.10.0 ## matchLeftW Less strict version of [`matchLeft`](#matchleft). **Signature** ```ts export declare const matchLeftW: ( onEmpty: LazyArg, onNonEmpty: (head: A, tail: readonly A[]) => C ) => (as: readonly A[]) => B | C ``` Added in v2.11.0 ## matchRight Break a `ReadonlyArray` into its initial elements and the last element. **Signature** ```ts export declare const matchRight: ( onEmpty: LazyArg, onNonEmpty: (init: readonly A[], last: A) => B ) => (as: readonly A[]) => B ``` Added in v2.10.0 ## matchRightW Less strict version of [`matchRight`](#matchright). **Signature** ```ts export declare const matchRightW: ( onEmpty: LazyArg, onNonEmpty: (init: readonly A[], last: A) => C ) => (as: readonly A[]) => B | C ``` Added in v2.11.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onEmpty: LazyArg, onNonEmpty: (as: RNEA.ReadonlyNonEmptyArray) => C ) => (as: readonly A[]) => B | C ``` Added in v2.11.0 # refinements ## isEmpty Test whether a `ReadonlyArray` is empty. **Signature** ```ts export declare const isEmpty: (as: readonly A[]) => as is readonly [] ``` **Example** ```ts import { isEmpty } from 'fp-ts/ReadonlyArray' assert.strictEqual(isEmpty([]), true) ``` Added in v2.5.0 ## isNonEmpty Test whether a `ReadonlyArray` is non empty. **Signature** ```ts export declare const isNonEmpty: (as: readonly A[]) => as is RNEA.ReadonlyNonEmptyArray ``` Added in v2.5.0 # sequencing ## chainFirst Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const chainFirst: (f: (a: A) => readonly B[]) => (first: readonly A[]) => readonly A[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RA.chainFirst(() => ['a', 'b']) ), [1, 1, 2, 2, 3, 3] ) assert.deepStrictEqual( pipe( [1, 2, 3], RA.chainFirst(() => []) ), [] ) ``` Added in v2.5.0 ## chainRecBreadthFirst **Signature** ```ts export declare const chainRecBreadthFirst: (f: (a: A) => readonly Either[]) => (a: A) => readonly B[] ``` Added in v2.11.0 ## chainRecDepthFirst **Signature** ```ts export declare const chainRecDepthFirst: (f: (a: A) => readonly Either[]) => (a: A) => readonly B[] ``` Added in v2.11.0 ## chainWithIndex **Signature** ```ts export declare const chainWithIndex: (f: (i: number, a: A) => readonly B[]) => (as: readonly A[]) => readonly B[] ``` Added in v2.7.0 ## flatMap Composes computations in sequence, using the return value of one computation to determine the next computation. **Signature** ```ts export declare const flatMap: { (f: (a: A, i: number) => readonly B[]): (ma: readonly A[]) => readonly B[] (ma: readonly A[], f: (a: A, i: number) => readonly B[]): readonly B[] } ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RA.flatMap((n) => [`a${n}`, `b${n}`]) ), ['a1', 'b1', 'a2', 'b2', 'a3', 'b3'] ) assert.deepStrictEqual( pipe( [1, 2, 3], RA.flatMap(() => []) ), [] ) ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: readonly (readonly A[])[]) => readonly A[] ``` Added in v2.5.0 ## traverseWithIndex **Signature** ```ts export declare const traverseWithIndex: PipeableTraverseWithIndex1<'ReadonlyArray', number> ``` Added in v2.6.3 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence1<'ReadonlyArray'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse1<'ReadonlyArray'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReadonlyArray' ``` Added in v2.5.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.5.0 # unsafe ## unsafeDeleteAt **Signature** ```ts export declare const unsafeDeleteAt: (i: number, as: readonly A[]) => readonly A[] ``` Added in v2.5.0 ## unsafeInsertAt **Signature** ```ts export declare const unsafeInsertAt: (i: number, a: A, as: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` Added in v2.5.0 ## unsafeUpdateAt **Signature** ```ts export declare const unsafeUpdateAt: (i: number, a: A, as: readonly A[]) => readonly A[] ``` Added in v2.5.0 # utils ## Spanned (interface) **Signature** ```ts export interface Spanned { readonly init: ReadonlyArray readonly rest: ReadonlyArray } ``` Added in v2.5.0 ## ap **Signature** ```ts export declare const ap: (fa: readonly A[]) => (fab: readonly ((a: A) => B)[]) => readonly B[] ``` Added in v2.5.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: readonly B[]) => (first: readonly A[]) => readonly A[] ``` Added in v2.5.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: readonly B[]) => (first: readonly A[]) => readonly B[] ``` Added in v2.5.0 ## append Append an element to the end of a `ReadonlyArray`, creating a new `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const append: (end: A) => (init: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` **Example** ```ts import { append } from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], append(4)), [1, 2, 3, 4]) ``` Added in v2.10.0 ## appendW Less strict version of [`append`](#append). **Signature** ```ts export declare const appendW: (end: B) => (init: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` Added in v2.11.0 ## chop A useful recursion pattern for processing a `ReadonlyArray` to produce a new `ReadonlyArray`, often used for "chopping" up the input `ReadonlyArray`. Typically `chop` is called with some function that will consume an initial prefix of the `ReadonlyArray` and produce a value and the tail of the `ReadonlyArray`. **Signature** ```ts export declare const chop: ( f: (as: RNEA.ReadonlyNonEmptyArray) => readonly [B, readonly A[]] ) => (as: readonly A[]) => readonly B[] ``` **Example** ```ts import { Eq } from 'fp-ts/Eq' import * as RA from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' const group = (S: Eq): ((as: ReadonlyArray) => ReadonlyArray>) => { return RA.chop((as) => { const { init, rest } = pipe( as, RA.spanLeft((a: A) => S.equals(a, as[0])) ) return [init, rest] }) } assert.deepStrictEqual(group(N.Eq)([1, 1, 2, 3, 3, 4]), [[1, 1], [2], [3, 3], [4]]) ``` Added in v2.5.0 ## chunksOf Splits a `ReadonlyArray` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of the `ReadonlyArray`. Note that `chunksOf(n)([])` is `[]`, not `[[]]`. This is intentional, and is consistent with a recursive definition of `chunksOf`; it satisfies the property that: ```ts chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys))) ``` whenever `n` evenly divides the length of `as`. **Signature** ```ts export declare const chunksOf: (n: number) => (as: readonly A[]) => readonly RNEA.ReadonlyNonEmptyArray[] ``` **Example** ```ts import { chunksOf } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) ``` Added in v2.5.0 ## comprehension `ReadonlyArray` comprehension. ``` [ f(x, y, ...) | x ← xs, y ← ys, ..., g(x, y, ...) ] ``` **Signature** ```ts export declare function comprehension( input: readonly [ReadonlyArray, ReadonlyArray, ReadonlyArray, ReadonlyArray], f: (a: A, b: B, c: C, d: D) => R, g?: (a: A, b: B, c: C, d: D) => boolean ): ReadonlyArray export declare function comprehension( input: readonly [ReadonlyArray, ReadonlyArray, ReadonlyArray], f: (a: A, b: B, c: C) => R, g?: (a: A, b: B, c: C) => boolean ): ReadonlyArray export declare function comprehension( input: readonly [ReadonlyArray, ReadonlyArray], f: (a: A, b: B) => R, g?: (a: A, b: B) => boolean ): ReadonlyArray export declare function comprehension( input: readonly [ReadonlyArray], f: (a: A) => R, g?: (a: A) => boolean ): ReadonlyArray ``` **Example** ```ts import { comprehension } from 'fp-ts/ReadonlyArray' import { tuple } from 'fp-ts/function' assert.deepStrictEqual( comprehension( [ [1, 2, 3], ['a', 'b'], ], tuple, (a, b) => (a + b.length) % 2 === 0 ), [ [1, 'a'], [1, 'b'], [3, 'a'], [3, 'b'], ] ) ``` Added in v2.5.0 ## concat **Signature** ```ts export declare const concat: (second: readonly A[]) => (first: readonly A[]) => readonly A[] ``` Added in v2.11.0 ## concatW **Signature** ```ts export declare const concatW: (second: readonly B[]) => (first: readonly A[]) => readonly (B | A)[] ``` Added in v2.11.0 ## deleteAt Delete the element at the specified index, creating a new array, or returning `None` if the index is out of bounds **Signature** ```ts export declare const deleteAt: (i: number) => (as: readonly A[]) => Option ``` **Example** ```ts import { deleteAt } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(deleteAt(0)([1, 2, 3]), some([2, 3])) assert.deepStrictEqual(deleteAt(1)([]), none) ``` Added in v2.5.0 ## difference Creates an array of array values not included in the other given array using a `Eq` for equality comparisons. The order and references of result values are determined by the first array. **Signature** ```ts export declare function difference(E: Eq): { (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray } ``` **Example** ```ts import { difference } from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2], difference(N.Eq)([2, 3])), [1]) ``` Added in v2.5.0 ## dropLeft Drop a max number of elements from the start of an `ReadonlyArray`, creating a new `ReadonlyArray`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const dropLeft: (n: number) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' const input: ReadonlyArray = [1, 2, 3] assert.deepStrictEqual(pipe(input, RA.dropLeft(2)), [3]) assert.strictEqual(pipe(input, RA.dropLeft(0)), input) assert.strictEqual(pipe(input, RA.dropLeft(-1)), input) ``` Added in v2.5.0 ## dropLeftWhile Remove the longest initial subarray for which all element satisfy the specified predicate, creating a new array **Signature** ```ts export declare function dropLeftWhile( refinement: Refinement ): (as: ReadonlyArray) => ReadonlyArray export declare function dropLeftWhile( predicate: Predicate ): (bs: ReadonlyArray) => ReadonlyArray export declare function dropLeftWhile(predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray ``` **Example** ```ts import { dropLeftWhile } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(dropLeftWhile((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), [2, 4, 5]) ``` Added in v2.5.0 ## dropRight Drop a max number of elements from the end of an `ReadonlyArray`, creating a new `ReadonlyArray`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const dropRight: (n: number) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' const input: ReadonlyArray = [1, 2, 3] assert.deepStrictEqual(pipe(input, RA.dropRight(2)), [1]) assert.strictEqual(pipe(input, RA.dropRight(0)), input) assert.strictEqual(pipe(input, RA.dropRight(-1)), input) ``` Added in v2.5.0 ## duplicate **Signature** ```ts export declare const duplicate: (wa: readonly A[]) => readonly (readonly A[])[] ``` Added in v2.5.0 ## elem Test if a value is a member of an array. Takes a `Eq` as a single argument which returns the function to use to search for a value of type `A` in an array of type `ReadonlyArray`. **Signature** ```ts export declare function elem(E: Eq): { (a: A): (as: ReadonlyArray) => boolean (a: A, as: ReadonlyArray): boolean } ``` **Example** ```ts import { elem } from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(2)), true) assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(0)), false) ``` Added in v2.5.0 ## empty An empty array **Signature** ```ts export declare const empty: readonly never[] ``` Added in v2.5.0 ## every Check if a predicate holds true for every array member. **Signature** ```ts export declare function every( refinement: Refinement ): Refinement, ReadonlyArray> export declare function every(predicate: Predicate): Predicate> ``` **Example** ```ts import { every } from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' const isPositive = (n: number): boolean => n > 0 assert.deepStrictEqual(pipe([1, 2, 3], every(isPositive)), true) assert.deepStrictEqual(pipe([1, 2, -3], every(isPositive)), false) ``` Added in v2.9.0 ## exists Alias of [`some`](#some) **Signature** ```ts export declare const exists: (predicate: Predicate) => (as: readonly A[]) => as is RNEA.ReadonlyNonEmptyArray ``` Added in v2.11.0 ## extend **Signature** ```ts export declare const extend: (f: (fa: readonly A[]) => B) => (wa: readonly A[]) => readonly B[] ``` Added in v2.5.0 ## filterE Filter values inside a context. **Signature** ```ts export declare const filterE: FilterE1<'ReadonlyArray'> ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as RA from 'fp-ts/ReadonlyArray' import * as T from 'fp-ts/Task' const filterE = RA.filterE(T.ApplicativePar) async function test() { assert.deepStrictEqual( await pipe( [-1, 2, 3], filterE((n) => T.of(n > 0)) )(), [2, 3] ) } test() ``` Added in v2.11.0 ## findFirst Find the first element which satisfies a predicate (or a refinement) function **Signature** ```ts export declare function findFirst(refinement: Refinement): (as: ReadonlyArray) => Option export declare function findFirst(predicate: Predicate): (bs: ReadonlyArray) => Option export declare function findFirst(predicate: Predicate): (as: ReadonlyArray) => Option ``` **Example** ```ts import { findFirst } from 'fp-ts/ReadonlyArray' import { some } from 'fp-ts/Option' type X = { readonly a: number readonly b: number } assert.deepStrictEqual( findFirst((x: X) => x.a === 1)([ { a: 1, b: 1 }, { a: 1, b: 2 }, ]), some({ a: 1, b: 1 }) ) ``` Added in v2.5.0 ## findFirstMap Find the first element returned by an option based selector function **Signature** ```ts export declare const findFirstMap: (f: (a: A) => Option) => (as: readonly A[]) => Option ``` **Example** ```ts import { findFirstMap } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' interface Person { readonly name: string readonly age?: number } const persons: ReadonlyArray = [{ name: 'John' }, { name: 'Mary', age: 45 }, { name: 'Joey', age: 28 }] // returns the name of the first person that has an age assert.deepStrictEqual(findFirstMap((p: Person) => (p.age === undefined ? none : some(p.name)))(persons), some('Mary')) ``` Added in v2.5.0 ## findIndex Find the first index for which a predicate holds **Signature** ```ts export declare const findIndex: (predicate: Predicate) => (as: readonly A[]) => Option ``` **Example** ```ts import { findIndex } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(findIndex((n: number) => n === 2)([1, 2, 3]), some(1)) assert.deepStrictEqual(findIndex((n: number) => n === 2)([]), none) ``` Added in v2.5.0 ## findLast Find the last element which satisfies a predicate function **Signature** ```ts export declare function findLast(refinement: Refinement): (as: ReadonlyArray) => Option export declare function findLast(predicate: Predicate): (bs: ReadonlyArray) => Option export declare function findLast(predicate: Predicate): (as: ReadonlyArray) => Option ``` **Example** ```ts import { findLast } from 'fp-ts/ReadonlyArray' import { some } from 'fp-ts/Option' type X = { readonly a: number readonly b: number } assert.deepStrictEqual( findLast((x: X) => x.a === 1)([ { a: 1, b: 1 }, { a: 1, b: 2 }, ]), some({ a: 1, b: 2 }) ) ``` Added in v2.5.0 ## findLastIndex Returns the index of the last element of the list which matches the predicate **Signature** ```ts export declare const findLastIndex: (predicate: Predicate) => (as: readonly A[]) => Option ``` **Example** ```ts import { findLastIndex } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' interface X { readonly a: number readonly b: number } const xs: ReadonlyArray = [ { a: 1, b: 0 }, { a: 1, b: 1 }, ] assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 1)(xs), some(1)) assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 4)(xs), none) ``` Added in v2.5.0 ## findLastMap Find the last element returned by an option based selector function **Signature** ```ts export declare const findLastMap: (f: (a: A) => Option) => (as: readonly A[]) => Option ``` **Example** ```ts import { findLastMap } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' interface Person { readonly name: string readonly age?: number } const persons: ReadonlyArray = [{ name: 'John' }, { name: 'Mary', age: 45 }, { name: 'Joey', age: 28 }] // returns the name of the last person that has an age assert.deepStrictEqual(findLastMap((p: Person) => (p.age === undefined ? none : some(p.name)))(persons), some('Joey')) ``` Added in v2.5.0 ## head Get the first element in an array, or `None` if the array is empty **Signature** ```ts export declare const head: (as: readonly A[]) => Option ``` **Example** ```ts import { head } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(head([1, 2, 3]), some(1)) assert.deepStrictEqual(head([]), none) ``` Added in v2.5.0 ## init Get all but the last element of an array, creating a new array, or `None` if the array is empty **Signature** ```ts export declare const init: (as: readonly A[]) => Option ``` **Example** ```ts import { init } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(init([1, 2, 3]), some([1, 2])) assert.deepStrictEqual(init([]), none) ``` Added in v2.5.0 ## insertAt Insert an element at the specified index, creating a new array, or returning `None` if the index is out of bounds **Signature** ```ts export declare const insertAt: (i: number, a: A) => (as: readonly A[]) => Option> ``` **Example** ```ts import { insertAt } from 'fp-ts/ReadonlyArray' import { some } from 'fp-ts/Option' assert.deepStrictEqual(insertAt(2, 5)([1, 2, 3, 4]), some([1, 2, 5, 3, 4])) ``` Added in v2.5.0 ## intercalate Places an element in between members of a `ReadonlyArray`, then folds the results using the provided `Monoid`. **Signature** ```ts export declare const intercalate: (M: Monoid) => (middle: A) => (as: readonly A[]) => A ``` **Example** ```ts import * as S from 'fp-ts/string' import { intercalate } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c') ``` Added in v2.12.0 ## intersection Creates an array of unique values that are included in all given arrays using a `Eq` for equality comparisons. The order and references of result values are determined by the first array. **Signature** ```ts export declare function intersection(E: Eq): { (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray } ``` **Example** ```ts import { intersection } from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2], intersection(N.Eq)([2, 3])), [2]) ``` Added in v2.5.0 ## intersperse Places an element in between members of an array **Signature** ```ts export declare const intersperse: (middle: A) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { intersperse } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.9.0 ## isOutOfBound Test whether an array contains a particular index **Signature** ```ts export declare const isOutOfBound: (i: number, as: readonly A[]) => boolean ``` Added in v2.5.0 ## last Get the last element in an array, or `None` if the array is empty **Signature** ```ts export declare const last: (as: readonly A[]) => Option ``` **Example** ```ts import { last } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(last([1, 2, 3]), some(3)) assert.deepStrictEqual(last([]), none) ``` Added in v2.5.0 ## lefts Extracts from an array of `Either` all the `Left` elements. All the `Left` elements are extracted in order **Signature** ```ts export declare const lefts: (as: readonly Either[]) => readonly E[] ``` **Example** ```ts import { lefts } from 'fp-ts/ReadonlyArray' import { left, right } from 'fp-ts/Either' assert.deepStrictEqual(lefts([right(1), left('foo'), right(2)]), ['foo']) ``` Added in v2.5.0 ## lookup This function provides a safe way to read a value at a particular index from an array **Signature** ```ts export declare function lookup(i: number): (as: ReadonlyArray) => Option export declare function lookup(i: number, as: ReadonlyArray): Option ``` **Example** ```ts import { lookup } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], lookup(1)), some(2)) assert.deepStrictEqual(pipe([1, 2, 3], lookup(3)), none) ``` Added in v2.5.0 ## modifyAt Apply a function to the element at the specified index, creating a new array, or returning `None` if the index is out of bounds **Signature** ```ts export declare const modifyAt: (i: number, f: (a: A) => A) => (as: readonly A[]) => Option ``` **Example** ```ts import { modifyAt } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' const double = (x: number): number => x * 2 assert.deepStrictEqual(modifyAt(1, double)([1, 2, 3]), some([1, 4, 3])) assert.deepStrictEqual(modifyAt(1, double)([]), none) ``` Added in v2.5.0 ## prepend Prepend an element to the front of a `ReadonlyArray`, creating a new `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const prepend: (head: A) => (tail: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` **Example** ```ts import { prepend } from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([2, 3, 4], prepend(1)), [1, 2, 3, 4]) ``` Added in v2.10.0 ## prependAll Prepend an element to every member of an array **Signature** ```ts export declare const prependAll: (middle: A) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { prependAll } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.10.0 ## prependW Less strict version of [`prepend`](#prepend). **Signature** ```ts export declare const prependW: (head: B) => (tail: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` Added in v2.11.0 ## reverse Reverse an array, creating a new array **Signature** ```ts export declare const reverse: (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { reverse } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(reverse([1, 2, 3]), [3, 2, 1]) ``` Added in v2.5.0 ## rights Extracts from an array of `Either` all the `Right` elements. All the `Right` elements are extracted in order **Signature** ```ts export declare const rights: (as: readonly Either[]) => readonly A[] ``` **Example** ```ts import { rights } from 'fp-ts/ReadonlyArray' import { right, left } from 'fp-ts/Either' assert.deepStrictEqual(rights([right(1), left('foo'), right(2)]), [1, 2]) ``` Added in v2.5.0 ## rotate Rotate a `ReadonlyArray` by `n` steps. **Signature** ```ts export declare const rotate: (n: number) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { rotate } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) ``` Added in v2.5.0 ## scanLeft Same as `reduce` but it carries over the intermediate steps. **Signature** ```ts export declare const scanLeft: (b: B, f: (b: B, a: A) => B) => (as: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` **Example** ```ts import { scanLeft } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(scanLeft(10, (b, a: number) => b - a)([1, 2, 3]), [10, 9, 7, 4]) ``` Added in v2.5.0 ## scanRight Fold an array from the right, keeping all intermediate results instead of only the final result **Signature** ```ts export declare const scanRight: ( b: B, f: (a: A, b: B) => B ) => (as: readonly A[]) => RNEA.ReadonlyNonEmptyArray ``` **Example** ```ts import { scanRight } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(scanRight(10, (a: number, b) => b - a)([1, 2, 3]), [4, 5, 7, 10]) ``` Added in v2.5.0 ## size Calculate the number of elements in a `ReadonlyArray`. **Signature** ```ts export declare const size: (as: readonly A[]) => number ``` Added in v2.10.0 ## some Check if a predicate holds true for any array member. **Signature** ```ts export declare const some: (predicate: Predicate) => (as: readonly A[]) => as is RNEA.ReadonlyNonEmptyArray ``` **Example** ```ts import { some } from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' const isPositive = (n: number): boolean => n > 0 assert.deepStrictEqual(pipe([-1, -2, 3], some(isPositive)), true) assert.deepStrictEqual(pipe([-1, -2, -3], some(isPositive)), false) ``` Added in v2.9.0 ## sort Sort the elements of an array in increasing order, creating a new array **Signature** ```ts export declare const sort: (O: Ord) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { sort } from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' assert.deepStrictEqual(sort(N.Ord)([3, 2, 1]), [1, 2, 3]) ``` Added in v2.5.0 ## sortBy Sort the elements of an array in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, etc... **Signature** ```ts export declare const sortBy: (ords: readonly Ord[]) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { sortBy } from 'fp-ts/ReadonlyArray' import { contramap } from 'fp-ts/Ord' import * as S from 'fp-ts/string' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' interface Person { readonly name: string readonly age: number } const byName = pipe( S.Ord, contramap((p: Person) => p.name) ) const byAge = pipe( N.Ord, contramap((p: Person) => p.age) ) const sortByNameByAge = sortBy([byName, byAge]) const persons = [ { name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 }, ] assert.deepStrictEqual(sortByNameByAge(persons), [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, ]) ``` Added in v2.5.0 ## spanLeft Split an array into two parts: 1. the longest initial subarray for which all elements satisfy the specified predicate 2. the remaining elements **Signature** ```ts export declare function spanLeft(refinement: Refinement): (as: ReadonlyArray) => Spanned export declare function spanLeft(predicate: Predicate): (bs: ReadonlyArray) => Spanned export declare function spanLeft(predicate: Predicate): (as: ReadonlyArray) => Spanned ``` **Example** ```ts import { spanLeft } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(spanLeft((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] }) ``` Added in v2.5.0 ## splitAt Splits a `ReadonlyArray` into two pieces, the first piece has max `n` elements. **Signature** ```ts export declare const splitAt: (n: number) => (as: readonly A[]) => readonly [readonly A[], readonly A[]] ``` **Example** ```ts import { splitAt } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(splitAt(2)([1, 2, 3, 4, 5]), [ [1, 2], [3, 4, 5], ]) ``` Added in v2.5.0 ## tail Get all but the first element of an array, creating a new array, or `None` if the array is empty **Signature** ```ts export declare const tail: (as: readonly A[]) => Option ``` **Example** ```ts import { tail } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(tail([1, 2, 3]), some([2, 3])) assert.deepStrictEqual(tail([]), none) ``` Added in v2.5.0 ## takeLeft Keep only a max number of elements from the start of an `ReadonlyArray`, creating a new `ReadonlyArray`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const takeLeft: (n: number) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' const input: ReadonlyArray = [1, 2, 3] assert.deepStrictEqual(pipe(input, RA.takeLeft(2)), [1, 2]) // out of bounds assert.strictEqual(pipe(input, RA.takeLeft(4)), input) assert.strictEqual(pipe(input, RA.takeLeft(-1)), input) ``` Added in v2.5.0 ## takeLeftWhile Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new array **Signature** ```ts export declare function takeLeftWhile( refinement: Refinement ): (as: ReadonlyArray) => ReadonlyArray export declare function takeLeftWhile( predicate: Predicate ): (bs: ReadonlyArray) => ReadonlyArray export declare function takeLeftWhile(predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray ``` **Example** ```ts import { takeLeftWhile } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual(takeLeftWhile((n: number) => n % 2 === 0)([2, 4, 3, 6]), [2, 4]) ``` Added in v2.5.0 ## takeRight Keep only a max number of elements from the end of an `ReadonlyArray`, creating a new `ReadonlyArray`. **Note**. `n` is normalized to a non negative integer. **Signature** ```ts export declare const takeRight: (n: number) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' const input: ReadonlyArray = [1, 2, 3] assert.deepStrictEqual(pipe(input, RA.takeRight(2)), [2, 3]) // out of bounds assert.strictEqual(pipe(input, RA.takeRight(4)), input) assert.strictEqual(pipe(input, RA.takeRight(-1)), input) ``` Added in v2.5.0 ## unfold **Signature** ```ts export declare const unfold: (b: B, f: (b: B) => Option) => readonly A[] ``` Added in v2.6.6 ## union Creates an array of unique values, in order, from all given arrays using a `Eq` for equality comparisons **Signature** ```ts export declare function union(E: Eq): { (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray } ``` **Example** ```ts import { union } from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2], union(N.Eq)([2, 3])), [1, 2, 3]) ``` Added in v2.5.0 ## uniq Remove duplicates from an array, keeping the first occurrence of an element. **Signature** ```ts export declare const uniq: (E: Eq) => (as: readonly A[]) => readonly A[] ``` **Example** ```ts import { uniq } from 'fp-ts/ReadonlyArray' import * as N from 'fp-ts/number' assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) ``` Added in v2.5.0 ## unzip The function is reverse of `zip`. Takes an array of pairs and return two corresponding arrays **Signature** ```ts export declare const unzip: (as: readonly (readonly [A, B])[]) => readonly [readonly A[], readonly B[]] ``` **Example** ```ts import { unzip } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual( unzip([ [1, 'a'], [2, 'b'], [3, 'c'], ]), [ [1, 2, 3], ['a', 'b', 'c'], ] ) ``` Added in v2.5.0 ## updateAt Change the element at the specified index, creating a new array, or returning `None` if the index is out of bounds **Signature** ```ts export declare const updateAt: (i: number, a: A) => (as: readonly A[]) => Option ``` **Example** ```ts import { updateAt } from 'fp-ts/ReadonlyArray' import { some, none } from 'fp-ts/Option' assert.deepStrictEqual(updateAt(1, 1)([1, 2, 3]), some([1, 1, 3])) assert.deepStrictEqual(updateAt(1, 1)([]), none) ``` Added in v2.5.0 ## zero **Signature** ```ts export declare const zero: () => readonly A[] ``` Added in v2.7.0 ## zip Takes two arrays and returns an array of corresponding pairs. If one input array is short, excess elements of the longer array are discarded **Signature** ```ts export declare function zip(bs: ReadonlyArray): (as: ReadonlyArray) => ReadonlyArray export declare function zip(as: ReadonlyArray, bs: ReadonlyArray): ReadonlyArray ``` **Example** ```ts import { zip } from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe([1, 2, 3], zip(['a', 'b', 'c', 'd'])), [ [1, 'a'], [2, 'b'], [3, 'c'], ]) ``` Added in v2.5.0 ## zipWith Apply a function to pairs of elements at the same index in two arrays, collecting the results in a new array. If one input array is short, excess elements of the longer array are discarded. **Signature** ```ts export declare const zipWith: (fa: readonly A[], fb: readonly B[], f: (a: A, b: B) => C) => readonly C[] ``` **Example** ```ts import { zipWith } from 'fp-ts/ReadonlyArray' assert.deepStrictEqual( zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3'] ) ``` Added in v2.5.0 # zone of death ## ~~cons~~ Use [`prepend`](#prepend) instead. **Signature** ```ts export declare const cons: typeof RNEA.cons ``` Added in v2.5.0 ## ~~prependToAll~~ Use [`prependAll`](#prependall) instead. **Signature** ```ts export declare const prependToAll: (middle: A) => (as: readonly A[]) => readonly A[] ``` Added in v2.9.0 ## ~~range~~ Use `ReadonlyNonEmptyArray` module instead. **Signature** ```ts export declare const range: (start: number, end: number) => RNEA.ReadonlyNonEmptyArray ``` Added in v2.5.0 ## ~~readonlyArray~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RA.Functor` instead of `RA.readonlyArray` (where `RA` is from `import RA from 'fp-ts/ReadonlyArray'`) **Signature** ```ts export declare const readonlyArray: FunctorWithIndex1<'ReadonlyArray', number> & Monad1<'ReadonlyArray'> & Unfoldable1<'ReadonlyArray'> & Alternative1<'ReadonlyArray'> & Extend1<'ReadonlyArray'> & FilterableWithIndex1<'ReadonlyArray', number> & FoldableWithIndex1<'ReadonlyArray', number> & TraversableWithIndex1<'ReadonlyArray', number> & Witherable1<'ReadonlyArray'> ``` Added in v2.5.0 ## ~~snoc~~ Use [`append`](#append) instead. **Signature** ```ts export declare const snoc: (init: readonly A[], end: A) => RNEA.ReadonlyNonEmptyArray ``` Added in v2.5.0 ================================================ FILE: docs/modules/ReadonlyMap.ts.md ================================================ --- title: ReadonlyMap.ts nav_order: 84 parent: Modules --- ## ReadonlyMap overview Added in v2.5.0 ---

Table of contents

- [constructors](#constructors) - [fromFoldable](#fromfoldable) - [singleton](#singleton) - [conversions](#conversions) - [fromMap](#frommap) - [toMap](#tomap) - [toReadonlyArray](#toreadonlyarray) - [toUnfoldable](#tounfoldable) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [getFilterableWithIndex](#getfilterablewithindex) - [getWitherable](#getwitherable) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [folding](#folding) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [getFoldable](#getfoldable) - [getFoldableWithIndex](#getfoldablewithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [instances](#instances) - [Compactable](#compactable) - [Filterable](#filterable) - [Functor](#functor) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getFunctorWithIndex](#getfunctorwithindex) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getMonoid](#getmonoid) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [mapWithIndex](#mapwithindex) - [traversing](#traversing) - [getTraversable](#gettraversable) - [getTraversableWithIndex](#gettraversablewithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [collect](#collect) - [deleteAt](#deleteat) - [difference](#difference) - [elem](#elem) - [empty](#empty) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [intersection](#intersection) - [isEmpty](#isempty) - [isSubmap](#issubmap) - [keys](#keys) - [lookup](#lookup) - [lookupWithKey](#lookupwithkey) - [member](#member) - [modifyAt](#modifyat) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [pop](#pop) - [size](#size) - [union](#union) - [updateAt](#updateat) - [upsertAt](#upsertat) - [values](#values) - [zone of death](#zone-of-death) - [~~insertAt~~](#insertat) - [~~readonlyMap~~](#readonlymap) --- # constructors ## fromFoldable Create a map from a foldable collection of key/value pairs, using the specified `Magma` to combine values for duplicate keys. **Signature** ```ts export declare function fromFoldable( E: Eq, M: Magma
, F: Foldable3 ): (fka: Kind3) => ReadonlyMap export declare function fromFoldable( E: Eq, M: Magma, F: Foldable2 ): (fka: Kind2) => ReadonlyMap export declare function fromFoldable( E: Eq, M: Magma, F: Foldable1 ): (fka: Kind) => ReadonlyMap export declare function fromFoldable( E: Eq, M: Magma, F: Foldable ): (fka: HKT) => ReadonlyMap ``` Added in v2.5.0 ## singleton Create a map with one key/value pair **Signature** ```ts export declare const singleton: (k: K, a: A) => ReadonlyMap ``` Added in v2.5.0 # conversions ## fromMap **Signature** ```ts export declare const fromMap: (m: Map) => ReadonlyMap ``` Added in v2.5.0 ## toMap **Signature** ```ts export declare function toMap(m: ReadonlyMap): Map ``` Added in v2.5.0 ## toReadonlyArray Get a sorted `ReadonlyArray` of the key/value pairs contained in a `ReadonlyMap`. **Signature** ```ts export declare const toReadonlyArray: (O: Ord) => (m: ReadonlyMap) => readonly (readonly [K, A])[] ``` Added in v2.5.0 ## toUnfoldable Unfolds a map into a list of key/value pairs **Signature** ```ts export declare function toUnfoldable( ord: Ord, U: Unfoldable1 ): (d: ReadonlyMap) => Kind export declare function toUnfoldable( ord: Ord, U: Unfoldable ): (d: ReadonlyMap) => HKT ``` Added in v2.5.0 # filtering ## compact **Signature** ```ts export declare const compact: (fa: ReadonlyMap>) => ReadonlyMap ``` Added in v2.5.0 ## filter **Signature** ```ts export declare const filter: { (refinement: Refinement): (fa: ReadonlyMap) => ReadonlyMap (predicate: Predicate): (fb: ReadonlyMap) => ReadonlyMap (predicate: Predicate): (fa: ReadonlyMap) => ReadonlyMap } ``` Added in v2.5.0 ## filterMap **Signature** ```ts export declare const filterMap: (f: (a: A) => O.Option) => (fa: ReadonlyMap) => ReadonlyMap ``` Added in v2.5.0 ## getFilterableWithIndex **Signature** ```ts export declare function getFilterableWithIndex(): FilterableWithIndex2C ``` Added in v2.5.0 ## getWitherable **Signature** ```ts export declare function getWitherable(O: Ord): Witherable2C & TraversableWithIndex2C ``` Added in v2.5.0 ## partition **Signature** ```ts export declare const partition: { (refinement: Refinement): ( fa: ReadonlyMap ) => Separated, ReadonlyMap> (predicate: Predicate): ( fb: ReadonlyMap ) => Separated, ReadonlyMap> (predicate: Predicate): (fa: ReadonlyMap) => Separated, ReadonlyMap> } ``` Added in v2.5.0 ## partitionMap **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: ReadonlyMap) => Separated, ReadonlyMap> ``` Added in v2.5.0 ## separate **Signature** ```ts export declare const separate: ( fa: ReadonlyMap> ) => Separated, ReadonlyMap> ``` Added in v2.5.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (O: Ord) => (M: Monoid) => (f: (a: A) => M) => (m: ReadonlyMap) => M ``` Added in v2.11.0 ## foldMapWithIndex **Signature** ```ts export declare const foldMapWithIndex: ( O: Ord ) => (M: Monoid) => (f: (k: K, a: A) => M) => (m: ReadonlyMap) => M ``` Added in v2.11.0 ## getFoldable **Signature** ```ts export declare const getFoldable: (O: Ord) => Foldable2C<'ReadonlyMap', K> ``` Added in v2.10.0 ## getFoldableWithIndex **Signature** ```ts export declare const getFoldableWithIndex: (O: Ord) => FoldableWithIndex2C<'ReadonlyMap', K, K> ``` Added in v2.10.0 ## reduce **Signature** ```ts export declare const reduce: (O: Ord) => (b: B, f: (b: B, a: A) => B) => (m: ReadonlyMap) => B ``` Added in v2.11.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (O: Ord) => (b: B, f: (a: A, b: B) => B) => (m: ReadonlyMap) => B ``` Added in v2.11.0 ## reduceRightWithIndex **Signature** ```ts export declare const reduceRightWithIndex: ( O: Ord ) => (b: B, f: (k: K, a: A, b: B) => B) => (m: ReadonlyMap) => B ``` Added in v2.11.0 ## reduceWithIndex **Signature** ```ts export declare const reduceWithIndex: ( O: Ord ) => (b: B, f: (k: K, b: B, a: A) => B) => (m: ReadonlyMap) => B ``` Added in v2.11.0 # instances ## Compactable **Signature** ```ts export declare const Compactable: Compactable2<'ReadonlyMap'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable2<'ReadonlyMap'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'ReadonlyMap'> ``` Added in v2.7.0 ## getDifferenceMagma **Signature** ```ts export declare const getDifferenceMagma: (E: Eq) => () => Magma> ``` Added in v2.11.0 ## getEq **Signature** ```ts export declare function getEq(SK: Eq, SA: Eq): Eq> ``` Added in v2.5.0 ## getFunctorWithIndex **Signature** ```ts export declare const getFunctorWithIndex: () => FunctorWithIndex2C<'ReadonlyMap', K, K> ``` Added in v2.10.0 ## getIntersectionSemigroup **Signature** ```ts export declare const getIntersectionSemigroup: (E: Eq, S: Semigroup) => Semigroup> ``` Added in v2.11.0 ## getMonoid Gets `Monoid` instance for Maps given `Semigroup` instance for their values **Signature** ```ts export declare function getMonoid(SK: Eq, SA: Semigroup): Monoid> ``` Added in v2.5.0 ## getShow **Signature** ```ts export declare function getShow(SK: Show, SA: Show): Show> ``` Added in v2.5.0 ## getUnionMonoid **Signature** ```ts export declare const getUnionMonoid: (E: Eq, S: Semigroup) => Monoid> ``` Added in v2.11.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq, S: Semigroup) => Semigroup> ``` Added in v2.11.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: ReadonlyMap B>) => ReadonlyMap ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: ReadonlyMap) => ReadonlyMap ``` Added in v2.5.0 ## mapWithIndex **Signature** ```ts export declare const mapWithIndex: (f: (k: K, a: A) => B) => (fa: ReadonlyMap) => ReadonlyMap ``` Added in v2.7.1 # traversing ## getTraversable **Signature** ```ts export declare const getTraversable: (O: Ord) => Traversable2C<'ReadonlyMap', K> ``` Added in v2.10.0 ## getTraversableWithIndex **Signature** ```ts export declare const getTraversableWithIndex: (O: Ord) => TraversableWithIndex2C<'ReadonlyMap', K, K> ``` Added in v2.10.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReadonlyMap' ``` Added in v2.5.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.5.0 # utils ## collect **Signature** ```ts export declare function collect( O: Ord ): (f: (k: K, a: A) => B) => (m: ReadonlyMap) => ReadonlyArray ``` Added in v2.5.0 ## deleteAt Delete a key and value from a map **Signature** ```ts export declare const deleteAt: (E: Eq) => (k: K) => (m: ReadonlyMap) => ReadonlyMap ``` Added in v2.5.0 ## difference **Signature** ```ts export declare const difference: ( E: Eq ) => (_second: ReadonlyMap) => (first: ReadonlyMap) => ReadonlyMap ``` Added in v2.11.0 ## elem Test whether or not a value is a member of a map **Signature** ```ts export declare function elem(E: Eq): { (a: A): (m: ReadonlyMap) => boolean (a: A, m: ReadonlyMap): boolean } ``` Added in v2.5.0 ## empty **Signature** ```ts export declare const empty: ReadonlyMap ``` Added in v2.5.0 ## filterMapWithIndex **Signature** ```ts export declare const filterMapWithIndex: ( f: (k: K, a: A) => O.Option ) => (fa: ReadonlyMap) => ReadonlyMap ``` Added in v2.10.0 ## filterWithIndex **Signature** ```ts export declare function filterWithIndex( predicateWithIndex: (k: K, a: A) => a is B ): (m: ReadonlyMap) => ReadonlyMap export declare function filterWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => ReadonlyMap export declare function filterWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => ReadonlyMap ``` Added in v2.10.0 ## intersection **Signature** ```ts export declare const intersection: ( E: Eq, M: Magma ) => (second: ReadonlyMap) => (first: ReadonlyMap) => ReadonlyMap ``` Added in v2.11.0 ## isEmpty Test whether or not a map is empty **Signature** ```ts export declare const isEmpty: (m: ReadonlyMap) => boolean ``` Added in v2.5.0 ## isSubmap Test whether or not one `Map` contains all of the keys and values contained in another `Map` **Signature** ```ts export declare function isSubmap( SK: Eq, SA: Eq ): { (that: ReadonlyMap): (me: ReadonlyMap) => boolean (me: ReadonlyMap, that: ReadonlyMap): boolean } ``` Added in v2.5.0 ## keys Get a sorted `ReadonlyArray` of the keys contained in a `ReadonlyMap`. **Signature** ```ts export declare const keys: (O: Ord) => (m: ReadonlyMap) => readonly K[] ``` Added in v2.5.0 ## lookup Lookup the value for a key in a `Map`. **Signature** ```ts export declare function lookup(E: Eq): { (k: K): (m: ReadonlyMap) => Option (k: K, m: ReadonlyMap): Option } ``` Added in v2.5.0 ## lookupWithKey Lookup the value for a key in a `Map`. If the result is a `Some`, the existing key is also returned. **Signature** ```ts export declare function lookupWithKey(E: Eq): { (k: K): (m: ReadonlyMap) => Option (k: K, m: ReadonlyMap): Option } ``` Added in v2.5.0 ## member Test whether or not a key exists in a map **Signature** ```ts export declare function member(E: Eq): { (k: K): (m: ReadonlyMap) => boolean (k: K, m: ReadonlyMap): boolean } ``` Added in v2.5.0 ## modifyAt **Signature** ```ts export declare const modifyAt: ( E: Eq ) => (k: K, f: (a: A) => A) => (m: ReadonlyMap) => O.Option> ``` Added in v2.5.0 ## partitionMapWithIndex **Signature** ```ts export declare const partitionMapWithIndex: ( f: (k: K, a: A) => Either ) => (fa: ReadonlyMap) => Separated, ReadonlyMap> ``` Added in v2.10.0 ## partitionWithIndex **Signature** ```ts export declare function partitionWithIndex( predicateWithIndex: (k: K, a: A) => a is B ): (m: ReadonlyMap) => Separated, ReadonlyMap> export declare function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => Separated, ReadonlyMap> export declare function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => Separated, ReadonlyMap> ``` Added in v2.10.0 ## pop Delete a key and value from a map, returning the value as well as the subsequent map **Signature** ```ts export declare function pop(E: Eq): (k: K) => (m: ReadonlyMap) => Option]> ``` Added in v2.5.0 ## size Calculate the number of key/value pairs in a map **Signature** ```ts export declare const size: (m: ReadonlyMap) => number ``` Added in v2.5.0 ## union **Signature** ```ts export declare const union: ( E: Eq, M: Magma ) => (second: ReadonlyMap) => (first: ReadonlyMap) => ReadonlyMap ``` Added in v2.11.0 ## updateAt **Signature** ```ts export declare const updateAt: (E: Eq) => (k: K, a: A) => (m: ReadonlyMap) => O.Option> ``` Added in v2.5.0 ## upsertAt Insert or replace a key/value pair in a `ReadonlyMap`. **Signature** ```ts export declare const upsertAt: (E: Eq) => (k: K, a: A) => (m: ReadonlyMap) => ReadonlyMap ``` Added in v2.10.0 ## values Get a sorted `ReadonlyArray` of the values contained in a `ReadonlyMap`. **Signature** ```ts export declare const values: (O: Ord) => (m: ReadonlyMap) => readonly A[] ``` Added in v2.5.0 # zone of death ## ~~insertAt~~ Use [`upsertAt`](#upsertat) instead. **Signature** ```ts export declare const insertAt: (E: Eq) => (k: K, a: A) => (m: ReadonlyMap) => ReadonlyMap ``` Added in v2.5.0 ## ~~readonlyMap~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RM.Functor` instead of `RM.readonlyMap` (where `RM` is from `import RM from 'fp-ts/ReadonlyMap'`) **Signature** ```ts export declare const readonlyMap: Filterable2<'ReadonlyMap'> ``` Added in v2.5.0 ================================================ FILE: docs/modules/ReadonlyNonEmptyArray.ts.md ================================================ --- title: ReadonlyNonEmptyArray.ts nav_order: 85 parent: Modules --- ## ReadonlyNonEmptyArray overview Data structure which represents non-empty readonly arrays. ```ts export type ReadonlyNonEmptyArray = ReadonlyArray & { readonly 0: A } ``` Note that you don't need any conversion, a `ReadonlyNonEmptyArray` is a `ReadonlyArray`, so all `ReadonlyArray`'s APIs can be used with a `ReadonlyNonEmptyArray` without further ado. Added in v2.5.0 ---

Table of contents

- [Comonad](#comonad) - [extract](#extract) - [constructors](#constructors) - [makeBy](#makeby) - [of](#of) - [range](#range) - [replicate](#replicate) - [conversions](#conversions) - [fromArray](#fromarray) - [fromReadonlyArray](#fromreadonlyarray) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [folding](#folding) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [instances](#instances) - [Alt](#alt) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [Comonad](#comonad-1) - [Foldable](#foldable) - [FoldableWithIndex](#foldablewithindex) - [Functor](#functor) - [FunctorWithIndex](#functorwithindex) - [Monad](#monad) - [Pointed](#pointed) - [Traversable](#traversable) - [TraversableWithIndex](#traversablewithindex) - [getEq](#geteq) - [getSemigroup](#getsemigroup) - [getShow](#getshow) - [legacy](#legacy) - [chain](#chain) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [mapWithIndex](#mapwithindex) - [model](#model) - [ReadonlyNonEmptyArray (type alias)](#readonlynonemptyarray-type-alias) - [pattern matching](#pattern-matching) - [matchLeft](#matchleft) - [matchRight](#matchright) - [sequencing](#sequencing) - [chainFirst](#chainfirst) - [chainWithIndex](#chainwithindex) - [flatMap](#flatmap) - [flatten](#flatten) - [traverseWithIndex](#traversewithindex) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [chop](#chop) - [chunksOf](#chunksof) - [concat](#concat) - [concatAll](#concatall) - [concatW](#concatw) - [duplicate](#duplicate) - [extend](#extend) - [getUnionSemigroup](#getunionsemigroup) - [group](#group) - [groupBy](#groupby) - [head](#head) - [init](#init) - [intercalate](#intercalate) - [intersperse](#intersperse) - [last](#last) - [max](#max) - [min](#min) - [modifyAt](#modifyat) - [modifyHead](#modifyhead) - [modifyLast](#modifylast) - [prependAll](#prependall) - [reverse](#reverse) - [rotate](#rotate) - [sort](#sort) - [sortBy](#sortby) - [splitAt](#splitat) - [tail](#tail) - [unappend](#unappend) - [union](#union) - [uniq](#uniq) - [unprepend](#unprepend) - [unzip](#unzip) - [updateAt](#updateat) - [updateHead](#updatehead) - [updateLast](#updatelast) - [zip](#zip) - [zipWith](#zipwith) - [zone of death](#zone-of-death) - [~~cons~~](#cons) - [~~filterWithIndex~~](#filterwithindex) - [~~filter~~](#filter) - [~~fold~~](#fold) - [~~groupSort~~](#groupsort) - [~~insertAt~~](#insertat) - [~~prependToAll~~](#prependtoall) - [~~readonlyNonEmptyArray~~](#readonlynonemptyarray) - [~~snoc~~](#snoc) - [~~uncons~~](#uncons) - [~~unsnoc~~](#unsnoc) --- # Comonad ## extract **Signature** ```ts export declare const extract:
(wa: ReadonlyNonEmptyArray) => A ``` Added in v2.6.3 # constructors ## makeBy Return a `ReadonlyNonEmptyArray` of length `n` with element `i` initialized with `f(i)`. **Note**. `n` is normalized to a natural number. **Signature** ```ts export declare const makeBy: (f: (i: number) => A) => (n: number) => ReadonlyNonEmptyArray ``` **Example** ```ts import { makeBy } from 'fp-ts/ReadonlyNonEmptyArray' import { pipe } from 'fp-ts/function' const double = (n: number): number => n * 2 assert.deepStrictEqual(pipe(5, makeBy(double)), [0, 2, 4, 6, 8]) ``` Added in v2.11.0 ## of **Signature** ```ts export declare const of: (a: A) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## range Create a `ReadonlyNonEmptyArray` containing a range of integers, including both endpoints. **Signature** ```ts export declare const range: (start: number, end: number) => ReadonlyNonEmptyArray ``` **Example** ```ts import { range } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(range(1, 5), [1, 2, 3, 4, 5]) ``` Added in v2.11.0 ## replicate Create a `ReadonlyNonEmptyArray` containing a value repeated the specified number of times. **Note**. `n` is normalized to a natural number. **Signature** ```ts export declare const replicate: (a: A) => (n: number) => ReadonlyNonEmptyArray ``` **Example** ```ts import { replicate } from 'fp-ts/ReadonlyNonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(3, replicate('a')), ['a', 'a', 'a']) ``` Added in v2.11.0 # conversions ## fromArray **Signature** ```ts export declare const fromArray: (as: A[]) => Option> ``` Added in v2.5.0 ## fromReadonlyArray Return a `ReadonlyNonEmptyArray` from a `ReadonlyArray` returning `none` if the input is empty. **Signature** ```ts export declare const fromReadonlyArray: (as: readonly A[]) => Option> ``` Added in v2.5.0 # do notation ## Do **Signature** ```ts export declare const Do: ReadonlyNonEmptyArray<{}> ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: ReadonlyNonEmptyArray ) => ( fa: ReadonlyNonEmptyArray ) => ReadonlyNonEmptyArray<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => ReadonlyNonEmptyArray ) => ( ma: ReadonlyNonEmptyArray ) => ReadonlyNonEmptyArray<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: ( name: N ) => (fa: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray<{ readonly [K in N]: A }> ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => ( fa: ReadonlyNonEmptyArray ) => ReadonlyNonEmptyArray<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. In case of `ReadonlyNonEmptyArray` concatenates the inputs into a single array. **Signature** ```ts export declare const alt: ( that: LazyArg> ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RNEA.alt(() => [4, 5]) ), [1, 2, 3, 4, 5] ) ``` Added in v2.6.2 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: ( that: LazyArg> ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3] as RNEA.ReadonlyNonEmptyArray, RNEA.altW(() => ['a', 'b']) ), [1, 2, 3, 'a', 'b'] ) ``` Added in v2.9.0 # folding ## foldMap **Note**. The constraint is relaxed: a `Semigroup` instead of a `Monoid`. **Signature** ```ts export declare const foldMap: (S: Se.Semigroup) => (f: (a: A) => S) => (as: ReadonlyNonEmptyArray) => S ``` Added in v2.5.0 ## foldMapWithIndex **Note**. The constraint is relaxed: a `Semigroup` instead of a `Monoid`. **Signature** ```ts export declare const foldMapWithIndex: ( S: Se.Semigroup ) => (f: (i: number, a: A) => S) => (as: ReadonlyNonEmptyArray) => S ``` Added in v2.5.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (as: ReadonlyNonEmptyArray) => B ``` Added in v2.5.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (as: ReadonlyNonEmptyArray) => B ``` Added in v2.5.0 ## reduceRightWithIndex **Signature** ```ts export declare const reduceRightWithIndex: ( b: B, f: (i: number, a: A, b: B) => B ) => (as: ReadonlyNonEmptyArray) => B ``` Added in v2.5.0 ## reduceWithIndex **Signature** ```ts export declare const reduceWithIndex: ( b: B, f: (i: number, b: B, a: A) => B ) => (as: ReadonlyNonEmptyArray) => B ``` Added in v2.5.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'ReadonlyNonEmptyArray'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: Chain1<'ReadonlyNonEmptyArray'> ``` Added in v2.10.0 ## Comonad **Signature** ```ts export declare const Comonad: Comonad1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## FoldableWithIndex **Signature** ```ts export declare const FoldableWithIndex: FoldableWithIndex1<'ReadonlyNonEmptyArray', number> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## FunctorWithIndex **Signature** ```ts export declare const FunctorWithIndex: FunctorWithIndex1<'ReadonlyNonEmptyArray', number> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'ReadonlyNonEmptyArray'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'ReadonlyNonEmptyArray'> ``` Added in v2.7.0 ## TraversableWithIndex **Signature** ```ts export declare const TraversableWithIndex: TraversableWithIndex1<'ReadonlyNonEmptyArray', number> ``` Added in v2.7.0 ## getEq **Signature** ```ts export declare const getEq: (E: Eq) => Eq> ``` **Example** ```ts import { getEq } from 'fp-ts/ReadonlyNonEmptyArray' import * as N from 'fp-ts/number' const E = getEq(N.Eq) assert.strictEqual(E.equals([1, 2], [1, 2]), true) assert.strictEqual(E.equals([1, 2], [1, 3]), false) ``` Added in v2.5.0 ## getSemigroup Builds a `Semigroup` instance for `ReadonlyNonEmptyArray` **Signature** ```ts export declare const getSemigroup: () => Se.Semigroup> ``` Added in v2.5.0 ## getShow **Signature** ```ts export declare const getShow: (S: Show) => Show> ``` Added in v2.5.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: ( f: (a: A) => ReadonlyNonEmptyArray ) => (ma: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: ReadonlyNonEmptyArray<(a: A) => B>) => ReadonlyNonEmptyArray ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## mapWithIndex **Signature** ```ts export declare const mapWithIndex: ( f: (i: number, a: A) => B ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 # model ## ReadonlyNonEmptyArray (type alias) **Signature** ```ts export type ReadonlyNonEmptyArray = ReadonlyArray & { readonly 0: A } ``` Added in v2.5.0 # pattern matching ## matchLeft Break a `ReadonlyArray` into its first element and remaining elements. **Signature** ```ts export declare const matchLeft: (f: (head: A, tail: readonly A[]) => B) => (as: ReadonlyNonEmptyArray) => B ``` Added in v2.11.0 ## matchRight Break a `ReadonlyArray` into its initial elements and the last element. **Signature** ```ts export declare const matchRight: (f: (init: readonly A[], last: A) => B) => (as: ReadonlyNonEmptyArray) => B ``` Added in v2.11.0 # sequencing ## chainFirst Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const chainFirst: ( f: (a: A) => ReadonlyNonEmptyArray ) => (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import * as RA from 'fp-ts/ReadonlyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RA.chainFirst(() => ['a', 'b']) ), [1, 1, 2, 2, 3, 3] ) ``` Added in v2.5.0 ## chainWithIndex **Signature** ```ts export declare const chainWithIndex: ( f: (i: number, a: A) => ReadonlyNonEmptyArray ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.10.0 ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A, i: number) => ReadonlyNonEmptyArray): (ma: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray (ma: ReadonlyNonEmptyArray, f: (a: A, i: number) => ReadonlyNonEmptyArray): ReadonlyNonEmptyArray } ``` **Example** ```ts import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' import { pipe } from 'fp-ts/function' assert.deepStrictEqual( pipe( [1, 2, 3], RNEA.flatMap((n) => [`a${n}`, `b${n}`]) ), ['a1', 'b1', 'a2', 'b2', 'a3', 'b3'] ) ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: ReadonlyNonEmptyArray>) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## traverseWithIndex **Signature** ```ts export declare const traverseWithIndex: PipeableTraverseWithIndex1<'ReadonlyNonEmptyArray', number> ``` Added in v2.6.3 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence1<'ReadonlyNonEmptyArray'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse1<'ReadonlyNonEmptyArray'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReadonlyNonEmptyArray' ``` Added in v2.5.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.5.0 # utils ## ap **Signature** ```ts export declare const ap: ( as: ReadonlyNonEmptyArray ) => (fab: ReadonlyNonEmptyArray<(a: A) => B>) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: ( second: ReadonlyNonEmptyArray ) => (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: ( second: ReadonlyNonEmptyArray ) => (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## chop A useful recursion pattern for processing a `ReadonlyNonEmptyArray` to produce a new `ReadonlyNonEmptyArray`, often used for "chopping" up the input `ReadonlyNonEmptyArray`. Typically `chop` is called with some function that will consume an initial prefix of the `ReadonlyNonEmptyArray` and produce a value and the tail of the `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const chop: ( f: (as: ReadonlyNonEmptyArray) => readonly [B, readonly A[]] ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.10.0 ## chunksOf Splits a `ReadonlyNonEmptyArray` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of the `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const chunksOf: ( n: number ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray> ``` Added in v2.10.0 ## concat **Signature** ```ts export declare function concat( second: ReadonlyNonEmptyArray ): (first: ReadonlyArray) => ReadonlyNonEmptyArray export declare function concat( second: ReadonlyArray ): (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray export declare function concat(first: ReadonlyArray, second: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray export declare function concat(first: ReadonlyNonEmptyArray, second: ReadonlyArray): ReadonlyNonEmptyArray ``` Added in v2.5.0 ## concatAll **Signature** ```ts export declare const concatAll: (S: Se.Semigroup) => (as: ReadonlyNonEmptyArray) => A ``` Added in v2.10.0 ## concatW **Signature** ```ts export declare function concatW( second: ReadonlyNonEmptyArray ): (first: ReadonlyArray) => ReadonlyNonEmptyArray export declare function concatW( second: ReadonlyArray ): (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.11.0 ## duplicate **Signature** ```ts export declare const duplicate: (ma: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray> ``` Added in v2.5.0 ## extend **Signature** ```ts export declare const extend: ( f: (as: ReadonlyNonEmptyArray) => B ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq) => Se.Semigroup> ``` Added in v2.11.0 ## group Group equal, consecutive elements of a `ReadonlyArray` into `ReadonlyNonEmptyArray`s. **Signature** ```ts export declare function group(E: Eq): { (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray> (as: ReadonlyArray): ReadonlyArray> } ``` **Example** ```ts import { group } from 'fp-ts/ReadonlyNonEmptyArray' import * as N from 'fp-ts/number' assert.deepStrictEqual(group(N.Eq)([1, 2, 1, 1]), [[1], [2], [1, 1]]) ``` Added in v2.5.0 ## groupBy Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning function on each element, and grouping the results according to values returned **Signature** ```ts export declare const groupBy: ( f: (a: A) => string ) => (as: readonly A[]) => Readonly>> ``` **Example** ```ts import { groupBy } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(groupBy((s: string) => String(s.length))(['a', 'b', 'ab']), { '1': ['a', 'b'], '2': ['ab'], }) ``` Added in v2.5.0 ## head **Signature** ```ts export declare const head: (as: ReadonlyNonEmptyArray) => A ``` Added in v2.5.0 ## init Get all but the last element of a non empty array, creating a new array. **Signature** ```ts export declare const init: (as: ReadonlyNonEmptyArray) => readonly A[] ``` **Example** ```ts import { init } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(init([1, 2, 3]), [1, 2]) assert.deepStrictEqual(init([1]), []) ``` Added in v2.5.0 ## intercalate Places an element in between members of a `ReadonlyNonEmptyArray`, then folds the results using the provided `Semigroup`. **Signature** ```ts export declare const intercalate: (S: Se.Semigroup) => (middle: A) => (as: ReadonlyNonEmptyArray) => A ``` **Example** ```ts import * as S from 'fp-ts/string' import { intercalate } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(intercalate(S.Semigroup)('-')(['a', 'b', 'c']), 'a-b-c') ``` Added in v2.12.0 ## intersperse Places an element in between members of a `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const intersperse: (middle: A) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import { intersperse } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.9.0 ## last **Signature** ```ts export declare const last: (as: ReadonlyNonEmptyArray) => A ``` Added in v2.5.0 ## max **Signature** ```ts export declare const max: (O: Ord) => (as: ReadonlyNonEmptyArray) => A ``` Added in v2.5.0 ## min **Signature** ```ts export declare const min: (O: Ord) => (as: ReadonlyNonEmptyArray) => A ``` Added in v2.5.0 ## modifyAt **Signature** ```ts export declare const modifyAt: ( i: number, f: (a: A) => A ) => (as: ReadonlyNonEmptyArray) => Option> ``` Added in v2.5.0 ## modifyHead Apply a function to the head, creating a new `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const modifyHead: (f: Endomorphism) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.11.0 ## modifyLast Apply a function to the last element, creating a new `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const modifyLast: (f: Endomorphism) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.11.0 ## prependAll Prepend an element to every member of a `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const prependAll: (middle: A) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import { prependAll } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) ``` Added in v2.10.0 ## reverse **Signature** ```ts export declare const reverse: (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## rotate Rotate a `ReadonlyNonEmptyArray` by `n` steps. **Signature** ```ts export declare const rotate: (n: number) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import { rotate } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) assert.deepStrictEqual(rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) ``` Added in v2.11.0 ## sort **Signature** ```ts export declare const sort: (O: Ord) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## sortBy Sort the elements of a `ReadonlyNonEmptyArray` in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, etc... **Signature** ```ts export declare const sortBy: ( ords: readonly Ord[] ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' import { contramap } from 'fp-ts/Ord' import * as S from 'fp-ts/string' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' interface Person { name: string age: number } const byName = pipe( S.Ord, contramap((p: Person) => p.name) ) const byAge = pipe( N.Ord, contramap((p: Person) => p.age) ) const sortByNameByAge = RNEA.sortBy([byName, byAge]) const persons: RNEA.ReadonlyNonEmptyArray = [ { name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 }, ] assert.deepStrictEqual(sortByNameByAge(persons), [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, ]) ``` Added in v2.11.0 ## splitAt Splits a `ReadonlyNonEmptyArray` into two pieces, the first piece has max `n` elements. **Signature** ```ts export declare const splitAt: ( n: number ) => (as: ReadonlyNonEmptyArray) => readonly [ReadonlyNonEmptyArray, readonly A[]] ``` Added in v2.10.0 ## tail **Signature** ```ts export declare const tail: (as: ReadonlyNonEmptyArray) => readonly A[] ``` Added in v2.5.0 ## unappend Return the tuple of the `init` and the `last`. **Signature** ```ts export declare const unappend: (as: ReadonlyNonEmptyArray) => readonly [readonly A[], A] ``` **Example** ```ts import { unappend } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) ``` Added in v2.9.0 ## union **Signature** ```ts export declare const union: ( E: Eq ) => (second: ReadonlyNonEmptyArray) => (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.11.0 ## uniq Remove duplicates from a `ReadonlyNonEmptyArray`, keeping the first occurrence of an element. **Signature** ```ts export declare const uniq: (E: Eq) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` **Example** ```ts import { uniq } from 'fp-ts/ReadonlyNonEmptyArray' import * as N from 'fp-ts/number' assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) ``` Added in v2.11.0 ## unprepend Return the tuple of the `head` and the `tail`. **Signature** ```ts export declare const unprepend: (as: ReadonlyNonEmptyArray) => readonly [A, readonly A[]] ``` **Example** ```ts import { unprepend } from 'fp-ts/ReadonlyNonEmptyArray' assert.deepStrictEqual(unprepend([1, 2, 3, 4]), [1, [2, 3, 4]]) ``` Added in v2.9.0 ## unzip **Signature** ```ts export declare const unzip: ( abs: ReadonlyNonEmptyArray ) => readonly [ReadonlyNonEmptyArray, ReadonlyNonEmptyArray] ``` Added in v2.5.1 ## updateAt **Signature** ```ts export declare const updateAt: ( i: number, a: A ) => (as: ReadonlyNonEmptyArray) => Option> ``` Added in v2.5.0 ## updateHead Change the head, creating a new `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const updateHead: (a: A) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.11.0 ## updateLast Change the last element, creating a new `ReadonlyNonEmptyArray`. **Signature** ```ts export declare const updateLast: (a: A) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.11.0 ## zip **Signature** ```ts export declare function zip( bs: ReadonlyNonEmptyArray ): (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray export declare function zip( as: ReadonlyNonEmptyArray, bs: ReadonlyNonEmptyArray ): ReadonlyNonEmptyArray ``` Added in v2.5.1 ## zipWith **Signature** ```ts export declare const zipWith: ( as: ReadonlyNonEmptyArray, bs: ReadonlyNonEmptyArray, f: (a: A, b: B) => C ) => ReadonlyNonEmptyArray ``` Added in v2.5.1 # zone of death ## ~~cons~~ Use [`prepend`](./ReadonlyArray.ts.html#prepend) instead. **Signature** ```ts export declare function cons(head: A): (tail: ReadonlyArray) => ReadonlyNonEmptyArray export declare function cons(head: A, tail: ReadonlyArray): ReadonlyNonEmptyArray ``` Added in v2.5.0 ## ~~filterWithIndex~~ Use [`filterWithIndex`](./ReadonlyArray.ts.html#filterwithindex) instead. **Signature** ```ts export declare const filterWithIndex: ( predicate: (i: number, a: A) => boolean ) => (as: ReadonlyNonEmptyArray) => Option> ``` Added in v2.5.0 ## ~~filter~~ Use [`filter`](./ReadonlyArray.ts.html#filter) instead. **Signature** ```ts export declare function filter( refinement: Refinement ): (as: ReadonlyNonEmptyArray) => Option> export declare function filter( predicate: Predicate ): (bs: ReadonlyNonEmptyArray) => Option> export declare function filter( predicate: Predicate ): (as: ReadonlyNonEmptyArray) => Option> ``` Added in v2.5.0 ## ~~fold~~ Use [`concatAll`](#concatall) instead. **Signature** ```ts export declare const fold: (S: Se.Semigroup) => (as: ReadonlyNonEmptyArray) => A ``` Added in v2.5.0 ## ~~groupSort~~ This is just `sort` followed by `group`. **Signature** ```ts export declare function groupSort(O: Ord): { (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray> (as: ReadonlyArray): ReadonlyArray> } ``` Added in v2.5.0 ## ~~insertAt~~ Use [`insertAt`](./ReadonlyArray.ts.html#insertat) instead. **Signature** ```ts export declare const insertAt: (i: number, a: A) => (as: readonly A[]) => Option> ``` Added in v2.5.0 ## ~~prependToAll~~ Use [`prependAll`](#prependall) instead. **Signature** ```ts export declare const prependToAll: (middle: A) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray ``` Added in v2.9.0 ## ~~readonlyNonEmptyArray~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RNEA.Functor` instead of `RNEA.readonlyNonEmptyArray` (where `RNEA` is from `import RNEA from 'fp-ts/ReadonlyNonEmptyArray'`) **Signature** ```ts export declare const readonlyNonEmptyArray: Monad1<'ReadonlyNonEmptyArray'> & Comonad1<'ReadonlyNonEmptyArray'> & TraversableWithIndex1<'ReadonlyNonEmptyArray', number> & FunctorWithIndex1<'ReadonlyNonEmptyArray', number> & FoldableWithIndex1<'ReadonlyNonEmptyArray', number> & Alt1<'ReadonlyNonEmptyArray'> ``` Added in v2.5.0 ## ~~snoc~~ Use [`append`](./ReadonlyArray.ts.html#append) instead. **Signature** ```ts export declare const snoc: (init: readonly A[], end: A) => ReadonlyNonEmptyArray ``` Added in v2.5.0 ## ~~uncons~~ Use [`unprepend`](#unprepend) instead. **Signature** ```ts export declare const uncons: (as: ReadonlyNonEmptyArray) => readonly [A, readonly A[]] ``` Added in v2.10.0 ## ~~unsnoc~~ Use [`unappend`](#unappend) instead. **Signature** ```ts export declare const unsnoc: (as: ReadonlyNonEmptyArray) => readonly [readonly A[], A] ``` Added in v2.10.0 ================================================ FILE: docs/modules/ReadonlyRecord.ts.md ================================================ --- title: ReadonlyRecord.ts nav_order: 86 parent: Modules --- ## ReadonlyRecord overview The `ReadonlyRecord.ts` module enables dealing in a functional way with Typescript's `Readonly>` type. That is similar to the `Record.ts` module, but for a record with all properties declared as `readonly`. Added in v2.5.0 ---

Table of contents

- [constructors](#constructors) - [singleton](#singleton) - [conversions](#conversions) - [fromEntries](#fromentries) - [fromRecord](#fromrecord) - [toEntries](#toentries) - [toReadonlyArray](#toreadonlyarray) - [toRecord](#torecord) - [toUnfoldable](#tounfoldable) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [getWitherable](#getwitherable) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [wilt](#wilt) - [wither](#wither) - [folding](#folding) - [foldMap](#foldmap) - [getFoldable](#getfoldable) - [getFoldableWithIndex](#getfoldablewithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Compactable](#compactable) - [Filterable](#filterable) - [FilterableWithIndex](#filterablewithindex) - [Functor](#functor) - [FunctorWithIndex](#functorwithindex) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getMonoid](#getmonoid) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [mapping](#mapping) - [flap](#flap) - [model](#model) - [ReadonlyRecord (type alias)](#readonlyrecord-type-alias) - [traversing](#traversing) - [getTraversable](#gettraversable) - [getTraversableWithIndex](#gettraversablewithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [collect](#collect) - [deleteAt](#deleteat) - [difference](#difference) - [elem](#elem) - [empty](#empty) - [every](#every) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [foldMapWithIndex](#foldmapwithindex) - [fromFoldable](#fromfoldable) - [fromFoldableMap](#fromfoldablemap) - [has](#has) - [intersection](#intersection) - [isEmpty](#isempty) - [isSubrecord](#issubrecord) - [keys](#keys) - [lookup](#lookup) - [map](#map) - [mapWithIndex](#mapwithindex) - [modifyAt](#modifyat) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [pop](#pop) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [sequence](#sequence) - [size](#size) - [some](#some) - [traverse](#traverse) - [traverseWithIndex](#traversewithindex) - [union](#union) - [updateAt](#updateat) - [upsertAt](#upsertat) - [zone of death](#zone-of-death) - [~~FoldableWithIndex~~](#foldablewithindex) - [~~Foldable~~](#foldable) - [~~TraversableWithIndex~~](#traversablewithindex) - [~~Traversable~~](#traversable) - [~~Witherable~~](#witherable) - [~~hasOwnProperty (function)~~](#hasownproperty-function) - [~~insertAt~~](#insertat) - [~~readonlyRecord~~](#readonlyrecord) --- # constructors ## singleton Create a `ReadonlyRecord` with one key/value pair. **Signature** ```ts export declare const singleton:
(k: string, a: A) => Readonly> ``` **Example** ```ts import { singleton } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(singleton('a', 1), { a: 1 }) ``` Added in v2.5.0 # conversions ## fromEntries Converts a `ReadonlyArray` of `[key, value]` tuples into a `ReadonlyRecord`. **Signature** ```ts export declare const fromEntries: (fa: readonly (readonly [string, A])[]) => Readonly> ``` **Example** ```ts import { fromEntries } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual( fromEntries([ ['a', 1], ['b', 2], ['a', 3], ]), { b: 2, a: 3 } ) ``` Added in v2.12.0 ## fromRecord Builds a `ReadonlyRecord` by copying a `Record`. **Signature** ```ts export declare const fromRecord: (r: Record) => Readonly> ``` **Example** ```ts import { ReadonlyRecord, fromRecord } from 'fp-ts/ReadonlyRecord' const x: Record = { a: 1, b: 2 } const y: ReadonlyRecord = fromRecord(x) assert.deepStrictEqual(x, y) // `y.a = 5` gives compiler error ``` Added in v2.5.0 ## toEntries Alias of [`toReadonlyArray`](#toreadonlyarray). **Signature** ```ts export declare const toEntries: (r: Readonly>) => readonly (readonly [K, A])[] ``` **Example** ```ts import { toEntries } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(toEntries({ b: 2, a: 1 }), [ ['a', 1], ['b', 2], ]) ``` Added in v2.12.0 ## toReadonlyArray Get a sorted `ReadonlyArray` of the key/value pairs contained in a `ReadonlyRecord`. **Signature** ```ts export declare const toReadonlyArray: (r: Readonly>) => readonly (readonly [K, A])[] ``` **Example** ```ts import { toReadonlyArray } from 'fp-ts/ReadonlyRecord' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(toReadonlyArray(x), [ ['a', 'foo'], ['b', false], ['c', 3], ]) ``` Added in v2.5.0 ## toRecord Builds a mutable `Record` from a `ReadonlyRecord`. **Signature** ```ts export declare const toRecord: (r: Readonly>) => Record ``` **Example** ```ts import { ReadonlyRecord, toRecord } from 'fp-ts/ReadonlyRecord' const x: ReadonlyRecord = { a: 1, b: 2 } const y: Record = toRecord(x) assert.deepStrictEqual(x, y) y.a = 5 // it's ok, y is mutable ``` Added in v2.5.0 ## toUnfoldable Unfolds a `ReadonlyRecord` into a list of key/value pairs. Given an `Unfoldable` class type `U` such as `array` or `readonlyArray`, it uses the `unfold` function to create an instance of `U`, providing an iterating function that iterates over each key/value pair in the record sorted alphabetically by key. **Signature** ```ts export declare function toUnfoldable( U: Unfoldable1 ): (r: ReadonlyRecord) => Kind export declare function toUnfoldable( U: Unfoldable ): (r: ReadonlyRecord) => HKT ``` **Example** ```ts import { array, readonlyArray } from 'fp-ts' import { toUnfoldable } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(toUnfoldable(array)({ b: 2, a: 1 }), [ ['a', 1], ['b', 2], ]) assert.deepStrictEqual(toUnfoldable(readonlyArray)({ b: 2, a: 1 }), [ ['a', 1], ['b', 2], ]) ``` Added in v2.5.0 # filtering ## compact Compact a `ReadonlyRecord` of `Option`s discarding the `None` values and keeping the `Some` values. **Signature** ```ts export declare const compact: (r: Readonly>>) => Readonly> ``` **Example** ```ts import { compact } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' assert.deepStrictEqual(compact({ a: option.some('foo'), b: option.none, c: option.some('bar') }), { a: 'foo', c: 'bar', }) ``` Added in v2.5.0 ## filter Given a `Predicate`, it produces a new `ReadonlyRecord` keeping only the entries with a value that satisfies the provided predicate. **Signature** ```ts export declare const filter: { (refinement: Refinement): (fa: Readonly>) => Readonly> (predicate: Predicate): (fb: Readonly>) => Readonly> (predicate: Predicate): (fa: Readonly>) => Readonly> } ``` **Example** ```ts import { filter } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(filter((s: string) => s.length < 4)({ a: 'foo', b: 'bar', c: 'verylong' }), { a: 'foo', b: 'bar', }) ``` Added in v2.5.0 ## filterMap Maps a `ReadonlyRecord` with an iterating function that returns an `Option` and it keeps only the `Some` values discarding the `None`s. **Signature** ```ts export declare const filterMap: ( f: (a: A) => Option ) => (fa: Readonly>) => Readonly> ``` **Example** ```ts import { filterMap } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' const f = (s: string) => (s.length < 4 ? option.some(`${s} is short`) : option.none) assert.deepStrictEqual(filterMap(f)({ a: 'foo', b: 'bar', c: 'verylong' }), { a: 'foo is short', b: 'bar is short', }) ``` Added in v2.5.0 ## getWitherable **Signature** ```ts export declare const getWitherable: (O: Ord) => Witherable1 ``` Added in v2.11.0 ## partition Partition a `ReadonlyRecord` into two parts according to a `Predicate`. **Signature** ```ts export declare const partition: { (refinement: Refinement): ( fa: Readonly> ) => Separated>, Readonly>> (predicate: Predicate): ( fb: Readonly> ) => Separated>, Readonly>> (predicate: Predicate): ( fa: Readonly> ) => Separated>, Readonly>> } ``` **Example** ```ts import { partition } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(partition((s: string) => s.length < 4)({ a: 'foo', b: 'bar', c: 'verylong' }), { left: { c: 'verylong', }, right: { a: 'foo', b: 'bar', }, }) ``` Added in v2.5.0 ## partitionMap Maps a `ReadonlyRecord` with a function returning an `Either` and partitions the resulting `ReadonlyRecord` into `Left`s and `Right`s. **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: Readonly>) => Separated>, Readonly>> ``` **Example** ```ts import { partitionMap } from 'fp-ts/ReadonlyRecord' import { either } from 'fp-ts' const f = (s: string) => (s.length < 4 ? either.right(`${s} is short`) : either.left(`${s} is not short`)) assert.deepStrictEqual(partitionMap(f)({ a: 'foo', b: 'bar', c: 'verylong' }), { left: { c: 'verylong is not short', }, right: { a: 'foo is short', b: 'bar is short', }, }) ``` Added in v2.5.0 ## separate Separate a `ReadonlyRecord` of `Either`s into `Left`s and `Right`s. **Signature** ```ts export declare const separate: ( r: Readonly>> ) => Separated>, Readonly>> ``` **Example** ```ts import { separate } from 'fp-ts/ReadonlyRecord' import { either } from 'fp-ts' assert.deepStrictEqual(separate({ a: either.right('foo'), b: either.left('bar'), c: either.right('baz') }), { right: { a: 'foo', c: 'baz', }, left: { b: 'bar', }, }) ``` Added in v2.5.0 ## wilt **Signature** ```ts export declare const wilt: PipeableWilt1<'ReadonlyRecord'> ``` Added in v2.6.5 ## wither **Signature** ```ts export declare const wither: PipeableWither1<'ReadonlyRecord'> ``` Added in v2.6.5 # folding ## foldMap Map and fold a `ReadonlyRecord`. Map the `ReadonlyRecord` passing each value to the iterating function. Then fold the results using the provided `Monoid`. **Signature** ```ts export declare function foldMap( O: Ord ): (M: Monoid) => (f: (a: A) => M) => (fa: ReadonlyRecord) => M export declare function foldMap(M: Monoid): (f: (a: A) => M) => (fa: ReadonlyRecord) => M ``` **Example** ```ts import { foldMap } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' import { Monoid } from 'fp-ts/Monoid' const m: Monoid = { empty: '', concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) } const f = (a: number) => `-${a}-` const x = { c: 3, a: 1, b: 2 } assert.deepStrictEqual(foldMap(Ord)(m)(f)(x), '-1- -> -2- -> -3-') ``` Added in v2.5.0 ## getFoldable Produces a `Foldable` instance for a `ReadonlyRecord`, using the provided `Ord` to sort the `ReadonlyRecord`'s entries by key. **Signature** ```ts export declare const getFoldable: (O: Ord) => Foldable1 ``` Added in v2.11.0 ## getFoldableWithIndex Produces a `FoldableWithIndex1` instance for a `ReadonlyRecord`, using the provided `Ord` to sort the `ReadonlyRecord`'s entries by key. **Signature** ```ts export declare const getFoldableWithIndex: (O: Ord) => FoldableWithIndex1 ``` Added in v2.11.0 ## reduce Reduces a `ReadonlyRecord` passing each value to the iterating function. Entries are processed in order, sorted by key according to the given `Ord`. **Signature** ```ts export declare function reduce( O: Ord ): (b: B, f: (b: B, a: A) => B) => (fa: ReadonlyRecord) => B export declare function reduce(b: B, f: (b: B, a: A) => B): (fa: ReadonlyRecord) => B ``` **Example** ```ts import { reduce } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduce(Ord)([] as string[], (b, a) => [...b, `-${a}-`])(x), ['-foo-', '-false-', '-3-']) ``` Added in v2.5.0 ## reduceRight Same as `reduce` but entries are processed _from the right_, i.e. in reverse order, from the last to the first entry, according to the given `Ord`. **Signature** ```ts export declare function reduceRight( O: Ord ): (b: B, f: (a: A, b: B) => B) => (fa: ReadonlyRecord) => B export declare function reduceRight(b: B, f: (a: A, b: B) => B): (fa: ReadonlyRecord) => B ``` **Example** ```ts import { reduceRight } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduceRight(Ord)([] as string[], (a, b) => [...b, `-${a}-`])(x), ['-3-', '-false-', '-foo-']) ``` Added in v2.5.0 # instances ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'ReadonlyRecord'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'ReadonlyRecord'> ``` Added in v2.7.0 ## FilterableWithIndex **Signature** ```ts export declare const FilterableWithIndex: FilterableWithIndex1<'ReadonlyRecord', string> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'ReadonlyRecord'> ``` Added in v2.7.0 ## FunctorWithIndex **Signature** ```ts export declare const FunctorWithIndex: FunctorWithIndex1<'ReadonlyRecord', string> ``` Added in v2.7.0 ## getDifferenceMagma Produces a `Magma` with a `concat` function that combines two `ReadonlyRecord`s by making the `difference`. **Signature** ```ts export declare const getDifferenceMagma: () => Magma>> ``` **Example** ```ts import { getDifferenceMagma, difference, ReadonlyRecord } from 'fp-ts/ReadonlyRecord' import { Magma } from 'fp-ts/Magma' const r1 = { a: 3, c: 3 } const r2 = { a: 1, b: 2 } const m: Magma> = getDifferenceMagma() assert.deepStrictEqual(m.concat(r1, r2), difference(r2)(r1)) assert.deepStrictEqual(m.concat(r1, r2), { c: 3, b: 2 }) ``` Added in v2.11.0 ## getEq Given an `Eq` for the base type, it produces an `Eq` for a `ReadonlyRecord` of that base type. **Signature** ```ts export declare function getEq(E: Eq): Eq> ``` **Example** ```ts import { getEq, ReadonlyRecord } from 'fp-ts/ReadonlyRecord' import { string } from 'fp-ts' import { Eq } from 'fp-ts/Eq' const eq: Eq> = getEq(string.Eq) assert.deepStrictEqual(eq.equals({ a: 'foo' }, { b: 'bar' }), false) assert.deepStrictEqual(eq.equals({ a: 'foo' }, { a: 'foo' }), true) ``` Added in v2.5.0 ## getIntersectionSemigroup Given a `Semigroup` in the base type, it produces a `Semigroup` in the `ReadonlyRecord` of the base type. The resulting `Semigroup` concatenates two `ReadonlyRecord`s by `intersection`. **Signature** ```ts export declare const getIntersectionSemigroup: (S: Se.Semigroup) => Se.Semigroup>> ``` **Example** ```ts import { getIntersectionSemigroup, ReadonlyRecord } from 'fp-ts/ReadonlyRecord' import { Semigroup } from 'fp-ts/Semigroup' const sNumber: Semigroup = { concat: (x, y) => x - y } const sReadonlyRecord: Semigroup> = getIntersectionSemigroup(sNumber) assert.deepStrictEqual(sReadonlyRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { b: -1 }) ``` Added in v2.11.0 ## getMonoid Returns a `Monoid` instance for `ReadonlyRecord`s, given a `Semigroup` instance for the base type. The `Monoid` makes the union of two `ReadonlyRecord`s comining the overlapping entries with the provided `Semigroup`. **Signature** ```ts export declare function getMonoid(S: Semigroup): Monoid> ``` **Example** ```ts import { SemigroupSum } from 'fp-ts/number' import { getMonoid } from 'fp-ts/ReadonlyRecord' const M = getMonoid(SemigroupSum) assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579, bar: 234, baz: 567 }) ``` Added in v2.5.0 ## getShow Produces a `Show` for a `ReadonlyRecord`, given a `Show` for the base type (a `Show` produces a human-readable representation of an instance). `ReadonlyRecord` entries are sorted by key with the provided `Ord`. **Signature** ```ts export declare function getShow(O: Ord): (S: Show) => Show> export declare function getShow(S: Show): Show> ``` **Example** ```ts import { getShow, ReadonlyRecord } from 'fp-ts/ReadonlyRecord' import { Show } from 'fp-ts/Show' import { Ord } from 'fp-ts/string' const sNumber: Show = { show: (n: number) => `${n}` } const sRecord: Show> = getShow(Ord)(sNumber) assert.deepStrictEqual(sRecord.show({ b: 2, a: 1 }), '{ "a": 1, "b": 2 }') ``` Added in v2.5.0 ## getUnionMonoid Same as `getMonoid`. Returns a `Monoid` instance for `ReadonlyRecord`s given a `Semigroup` instance for the base type. The `Monoid` makes the union of two `ReadonlyRecord`s combining the entries that have the same key with the provided `Semigroup`. **Signature** ```ts export declare const getUnionMonoid: (S: Se.Semigroup) => Monoid>> ``` **Example** ```ts import { SemigroupSum } from 'fp-ts/number' import { getUnionMonoid } from 'fp-ts/ReadonlyRecord' const M = getUnionMonoid(SemigroupSum) assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579, bar: 234, baz: 567 }) ``` Added in v2.11.0 ## getUnionSemigroup Given a `Semigroup` in the base type, it produces a `Semigroup` in the `ReadonlyRecord` of the base type. The resulting `Semigroup` concatenates two `ReadonlyRecord`s by `union`. **Signature** ```ts export declare const getUnionSemigroup: (S: Se.Semigroup) => Se.Semigroup>> ``` **Example** ```ts import { getUnionSemigroup, ReadonlyRecord } from 'fp-ts/ReadonlyRecord' import { Semigroup } from 'fp-ts/Semigroup' const sNumber: Semigroup = { concat: (x, y) => x - y } const sReadonlyRecord: Semigroup> = getUnionSemigroup(sNumber) assert.deepStrictEqual(sReadonlyRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { a: 1, b: -1, c: 4 }) ``` Added in v2.11.0 # mapping ## flap Takes a value and a `ReadonlyRecord` of functions and returns a `ReadonlyRecord` by applying each function to the input value. **Signature** ```ts export declare const flap: (a: A) => (fab: Readonly B>>) => Readonly> ``` **Example** ```ts import { flap } from 'fp-ts/ReadonlyRecord' const fab = { x: (n: number) => `${n} times 2`, y: (n: number) => `${n * 2}` } assert.deepStrictEqual(flap(3)(fab), { x: '3 times 2', y: '6', }) ``` Added in v2.10.0 # model ## ReadonlyRecord (type alias) **Signature** ```ts export type ReadonlyRecord = Readonly> ``` Added in v2.5.0 # traversing ## getTraversable Produces a `Traversable` instance for a `ReadonlyRecord`, using the provided `Ord` to sort the `ReadonlyRecord`'s entries by key. **Signature** ```ts export declare const getTraversable: (O: Ord) => Traversable1 ``` Added in v2.11.0 ## getTraversableWithIndex Produces a `TraversableWithIndex` instance for a `ReadonlyRecord`, using the provided `Ord` to sort the `ReadonlyRecord`'s entries by key. **Signature** ```ts export declare const getTraversableWithIndex: (O: Ord) => TraversableWithIndex1 ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReadonlyRecord' ``` Added in v2.5.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.5.0 # utils ## collect Map a `ReadonlyRecord` into an `ReadonlyArray`. **Signature** ```ts export declare function collect( O: Ord ): (f: (k: K, a: A) => B) => (r: ReadonlyRecord) => ReadonlyArray export declare function collect( f: (k: K, a: A) => B ): (r: ReadonlyRecord) => ReadonlyArray ``` **Example** ```ts import { collect } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' const f = (k: string, a: A) => `${k.toUpperCase()}-${a}` const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(collect(Ord)(f)(x), ['A-foo', 'B-false', 'C-3']) ``` Added in v2.5.0 ## deleteAt Delete a key and value from a `ReadonlyRecord`. **Signature** ```ts export declare function deleteAt( k: K ): (r: ReadonlyRecord) => ReadonlyRecord, A> ``` **Example** ```ts import { deleteAt } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(deleteAt('a')({ a: 1, b: 2 }), { b: 2 }) assert.deepStrictEqual(deleteAt('c')({ a: 1, b: 2 }), { a: 1, b: 2 }) ``` Added in v2.5.0 ## difference Difference between two `ReadonlyRecord`s. Takes two `ReadonlyRecord`s and produces a `ReadonlyRecord` composed by the entries of the two inputs, removing the entries with the same key in both inputs. **Signature** ```ts export declare const difference: ( second: Readonly> ) => (first: Readonly>) => Readonly> ``` **Example** ```ts import { difference } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(difference({ a: 1 })({ a: 1, b: 2 }), { b: 2 }) assert.deepStrictEqual(difference({ a: 3 })({ a: 1, b: 2 }), { b: 2 }) assert.deepStrictEqual(difference({ a: 3, c: 3 })({ a: 1, b: 2 }), { b: 2, c: 3 }) ``` Added in v2.11.0 ## elem Given an `Eq` checks if a `ReadonlyRecord` contains an entry with value equal to a provided value. **Signature** ```ts export declare function elem(E: Eq): { (a: A): (fa: ReadonlyRecord) => boolean (a: A, fa: ReadonlyRecord): boolean } ``` **Example** ```ts import { elem } from 'fp-ts/ReadonlyRecord' import { number } from 'fp-ts' assert.deepStrictEqual(elem(number.Eq)(123, { foo: 123, bar: 234 }), true) assert.deepStrictEqual(elem(number.Eq)(-7, { foo: 123, bar: 234 }), false) ``` Added in v2.5.0 ## empty **Signature** ```ts export declare const empty: Readonly> ``` Added in v2.5.0 ## every Test if every value in a `ReadonlyRecord` satisfies the predicate. **Signature** ```ts export declare function every( refinement: Refinement ): Refinement, ReadonlyRecord> export declare function every(predicate: Predicate): Predicate> ``` **Example** ```ts import { every } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: 2 }), true) assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: -1 }), false) ``` Added in v2.5.0 ## filterMapWithIndex Maps a `ReadonlyRecord` with an iterating function that takes key and value and returns an `Option`, keeping only the `Some` values and discarding `None`s. **Signature** ```ts export declare function filterMapWithIndex( f: (key: K, a: A) => Option ): (fa: ReadonlyRecord) => ReadonlyRecord ``` **Example** ```ts import { filterMapWithIndex } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' const f = (key: string, a: number) => (a >= 0 ? option.some(`${key}${a}`) : option.none) assert.deepStrictEqual(filterMapWithIndex(f)({ a: -1, b: 2, c: 3 }), { b: 'b2', c: 'c3', }) ``` Added in v2.5.0 ## filterWithIndex Produce a new `ReadonlyRecord` keeping only the entries that satisfy a predicate taking key and value as input. **Signature** ```ts export declare function filterWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: ReadonlyRecord) => ReadonlyRecord export declare function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: ReadonlyRecord) => ReadonlyRecord export declare function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: ReadonlyRecord) => ReadonlyRecord ``` **Example** ```ts import { filterWithIndex } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(filterWithIndex((s: string, v: number) => s.length <= 1 && v > 0)({ a: 1, b: -2, ccc: 3 }), { a: 1, }) ``` Added in v2.5.0 ## foldMapWithIndex Map and fold a `ReadonlyRecord`. Map the `ReadonlyRecord` passing each key/value pair to the iterating function. Then fold the results using the provided `Monoid`. **Signature** ```ts export declare function foldMapWithIndex( O: Ord ): (M: Monoid) => (f: (k: K, a: A) => M) => (fa: ReadonlyRecord) => M export declare function foldMapWithIndex( M: Monoid ): (f: (k: K, a: A) => M) => (fa: ReadonlyRecord) => M ``` **Example** ```ts import { foldMapWithIndex } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' import { Monoid } from 'fp-ts/Monoid' const m: Monoid = { empty: '', concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) } const f = (k: string, a: number) => `${k}-${a}` const x = { c: 3, a: 1, b: 2 } assert.deepStrictEqual(foldMapWithIndex(Ord)(m)(f)(x), 'a-1 -> b-2 -> c-3') ``` Added in v2.5.0 ## fromFoldable Create a `ReadonlyRecord` from a foldable collection of key/value pairs, using the specified `Magma` to combine values for duplicate keys. **Signature** ```ts export declare function fromFoldable( M: Magma, F: Foldable3 ): (fka: Kind3) => ReadonlyRecord export declare function fromFoldable( M: Magma, F: Foldable2 ): (fka: Kind2) => ReadonlyRecord export declare function fromFoldable( M: Magma, F: Foldable1 ): (fka: Kind) => ReadonlyRecord export declare function fromFoldable( M: Magma, F: FoldableHKT ): (fka: HKT) => ReadonlyRecord ``` Added in v2.5.0 ## fromFoldableMap Create a `ReadonlyRecord` from a foldable collection using the specified functions to: - map to key/value pairs - combine values for duplicate keys. **Signature** ```ts export declare function fromFoldableMap( M: Magma, F: Foldable3 ): (fa: Kind3, f: (a: A) => readonly [string, B]) => ReadonlyRecord export declare function fromFoldableMap( M: Magma, F: Foldable2 ): (fa: Kind2, f: (a: A) => readonly [string, B]) => ReadonlyRecord export declare function fromFoldableMap( M: Magma, F: Foldable1 ): (fa: Kind, f: (a: A) => readonly [string, B]) => ReadonlyRecord export declare function fromFoldableMap( M: Magma, F: FoldableHKT ): (fa: HKT, f: (a: A) => readonly [string, B]) => ReadonlyRecord ``` **Example** ```ts import { last } from 'fp-ts/Semigroup' import { Foldable, zip } from 'fp-ts/ReadonlyArray' import { identity } from 'fp-ts/function' import { ReadonlyRecord, fromFoldableMap } from 'fp-ts/ReadonlyRecord' export const zipObject = ( keys: ReadonlyArray, values: ReadonlyArray ): ReadonlyRecord => fromFoldableMap(last(), Foldable)(zip(keys, values), identity) assert.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 }) interface User { readonly id: string readonly name: string } const users: ReadonlyArray = [ { id: 'id1', name: 'name1' }, { id: 'id2', name: 'name2' }, { id: 'id1', name: 'name3' }, ] assert.deepStrictEqual( fromFoldableMap(last(), Foldable)(users, (user) => [user.id, user]), { id1: { id: 'id1', name: 'name3' }, id2: { id: 'id2', name: 'name2' }, } ) ``` Added in v2.5.0 ## has Test whether or not a key exists in a `ReadonlyRecord`. Note. This function is not pipeable because is a `Refinement`. **Signature** ```ts export declare const has: (k: string, r: Readonly>) => k is K ``` **Example** ```ts import { has } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(has('a', { a: 1, b: 2 }), true) assert.deepStrictEqual(has('c', { a: 1, b: 2 }), false) ``` Added in v2.10.0 ## intersection Intersection of two `ReadonlyRecord`s. Takes two `ReadonlyRecord`s and produces a `ReadonlyRecord` combining only the entries of the two inputswith the same key. It uses the `concat` function of the provided `Magma` to combine the elements. **Signature** ```ts export declare const intersection: ( M: Magma ) => (second: Readonly>) => (first: Readonly>) => Readonly> ``` **Example** ```ts import { intersection } from 'fp-ts/ReadonlyRecord' import { Magma } from 'fp-ts/Magma' const m1: Magma = { concat: (x: number, y: number) => x + y } assert.deepStrictEqual(intersection(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4 }) const m2: Magma = { concat: (x: number) => x } assert.deepStrictEqual(intersection(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1 }) ``` Added in v2.11.0 ## isEmpty Test whether a `ReadonlyRecord` is empty. **Signature** ```ts export declare const isEmpty: (r: Readonly>) => boolean ``` **Example** ```ts import { isEmpty } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(isEmpty({}), true) assert.deepStrictEqual(isEmpty({ a: 3 }), false) ``` Added in v2.5.0 ## isSubrecord Test whether one `ReadonlyRecord` contains all of the keys and values contained in another `ReadonlyRecord`. **Signature** ```ts export declare function isSubrecord(E: Eq): { (that: ReadonlyRecord): (me: ReadonlyRecord) => boolean (me: ReadonlyRecord, that: ReadonlyRecord): boolean } ``` **Example** ```ts import { isSubrecord } from 'fp-ts/ReadonlyRecord' import { string } from 'fp-ts' assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', b: 'bar', c: 'baz' }), true) assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', c: 'baz' }), true) assert.deepStrictEqual( isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', b: 'not-bar', c: 'baz' }), false ) assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar' })({ a: 'foo', b: 'bar', c: 'baz' }), false) ``` Added in v2.5.0 ## keys **Signature** ```ts export declare const keys: (r: Readonly>) => readonly K[] ``` Added in v2.5.0 ## lookup Lookup the value for a key in a `ReadonlyRecord`. **Signature** ```ts export declare function lookup(k: string): (r: ReadonlyRecord) => Option export declare function lookup(k: string, r: ReadonlyRecord): Option ``` **Example** ```ts import { lookup } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' assert.deepStrictEqual(lookup('b')({ a: 'foo', b: 'bar' }), option.some('bar')) assert.deepStrictEqual(lookup('c')({ a: 'foo', b: 'bar' }), option.none) ``` Added in v2.5.0 ## map Map a `ReadonlyRecord` passing the values to the iterating function. **Signature** ```ts export declare function map(f: (a: A) => B): (fa: ReadonlyRecord) => ReadonlyRecord ``` **Example** ```ts import { map } from 'fp-ts/ReadonlyRecord' const f = (n: number) => `-${n}-` assert.deepStrictEqual(map(f)({ a: 3, b: 5 }), { a: '-3-', b: '-5-' }) ``` Added in v2.5.0 ## mapWithIndex Map a `ReadonlyRecord` passing the keys to the iterating function. **Signature** ```ts export declare function mapWithIndex( f: (k: K, a: A) => B ): (fa: ReadonlyRecord) => ReadonlyRecord ``` **Example** ```ts import { mapWithIndex } from 'fp-ts/ReadonlyRecord' const f = (k: string, n: number) => `${k.toUpperCase()}-${n}` assert.deepStrictEqual(mapWithIndex(f)({ a: 3, b: 5 }), { a: 'A-3', b: 'B-5' }) ``` Added in v2.5.0 ## modifyAt Applies a mapping function to one specific key/value pair in a `ReadonlyRecord`. **Signature** ```ts export declare const modifyAt: ( k: string, f: (a: A) => A ) => (r: Readonly>) => Option>> ``` **Example** ```ts import { modifyAt } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' assert.deepStrictEqual(modifyAt('a', (x: number) => x * 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })) assert.deepStrictEqual(modifyAt('c', (x: number) => x * 3)({ a: 1, b: 2 }), option.none) ``` Added in v2.5.0 ## partitionMapWithIndex Maps a `ReadonlyRecord` with a function returning an `Either` and partitions the resulting `ReadonlyRecord` into `Left`s and `Right`s. **Signature** ```ts export declare function partitionMapWithIndex( f: (key: K, a: A) => Either ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> ``` **Example** ```ts import { partitionMapWithIndex } from 'fp-ts/ReadonlyRecord' import { either } from 'fp-ts' const f = (key: string, a: number) => a >= 0 ? either.right(`${key} is >= 0 (${a})`) : either.left(`${key} is < 0 (${a})`) assert.deepStrictEqual(partitionMapWithIndex(f)({ a: -1, b: 2, c: 123 }), { left: { a: 'a is < 0 (-1)', }, right: { b: 'b is >= 0 (2)', c: 'c is >= 0 (123)', }, }) ``` Added in v2.5.0 ## partitionWithIndex Partition a `ReadonlyRecord` into two parts according to a predicate that takes a key and a value. **Signature** ```ts export declare function partitionWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> export declare function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: ReadonlyRecord) => Separated, ReadonlyRecord> export declare function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> ``` **Example** ```ts import { partitionWithIndex } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual( partitionWithIndex((key: string, a: number) => key.length <= 1 && a > 0)({ a: -1, b: 2, ccc: 7 }), { left: { a: -1, ccc: 7, }, right: { b: 2, }, } ) ``` Added in v2.5.0 ## pop Delete a key and value from a `ReadonlyRecord`, returning the value as well as the subsequent `ReadonlyRecord`. **Signature** ```ts export declare function pop( k: K ): ( r: ReadonlyRecord ) => Option, A>]> ``` **Example** ```ts import { pop } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' assert.deepStrictEqual(pop('a')({ a: 1, b: 2, c: 3 }), option.some([1, { b: 2, c: 3 }])) assert.deepStrictEqual(pop('x')({ a: 1, b: 2, c: 3 }), option.none) ``` Added in v2.5.0 ## reduceRightWithIndex Same as `reduceWithIndex`, but reduce starting from the right (i.e. in reverse order, from the last to the first entry according to the given `Ord`). **Signature** ```ts export declare function reduceRightWithIndex( O: Ord ): (b: B, f: (k: K, a: A, b: B) => B) => (fa: ReadonlyRecord) => B export declare function reduceRightWithIndex( b: B, f: (k: K, a: A, b: B) => B ): (fa: ReadonlyRecord) => B ``` **Example** ```ts import { reduceRightWithIndex } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduceRightWithIndex(Ord)([] as string[], (k, a, b) => [...b, `${k}-${a}`])(x), [ 'c-3', 'b-false', 'a-foo', ]) ``` Added in v2.5.0 ## reduceWithIndex Reduces a `ReadonlyRecord` passing each key/value pair to the iterating function. Entries are processed in the order, sorted by key according to the given `Ord`. **Signature** ```ts export declare function reduceWithIndex( O: Ord ): (b: B, f: (k: K, b: B, a: A) => B) => (fa: ReadonlyRecord) => B export declare function reduceWithIndex( b: B, f: (k: K, b: B, a: A) => B ): (fa: ReadonlyRecord) => B ``` **Example** ```ts import { reduceWithIndex } from 'fp-ts/ReadonlyRecord' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduceWithIndex(Ord)([] as string[], (k, b, a) => [...b, `${k}-${a}`])(x), [ 'a-foo', 'b-false', 'c-3', ]) ``` Added in v2.5.0 ## sequence `ReadonlyRecord` sequencing, i.e., take a `ReadonlyRecord` in which elements are monads and return a monad of a `ReadonlyRecord` of the base types. The following example for instance shows sequencing a `ReadonlyRecord>` into an `Option>`. `sequence` in `ReadonlyRecord` is equivalent to `sequenceS` in `Apply.ts`. **Signature** ```ts export declare function sequence( F: Applicative3 ): (ta: ReadonlyRecord>) => Kind3> export declare function sequence( F: Applicative3C ): (ta: ReadonlyRecord>) => Kind3> export declare function sequence( F: Applicative2 ): (ta: ReadonlyRecord>) => Kind2> export declare function sequence( F: Applicative2C ): (ta: ReadonlyRecord>) => Kind2> export declare function sequence( F: Applicative1 ): (ta: ReadonlyRecord>) => Kind> export declare function sequence( F: Applicative ): (ta: ReadonlyRecord>) => HKT> ``` **Example** ```ts import { sequence } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' import { sequenceS } from 'fp-ts/Apply' assert.deepStrictEqual( sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), option.some({ a: 1, b: 2 }) ) assert.deepStrictEqual(sequence(option.Applicative)({ a: option.some(1), b: option.none }), option.none) assert.deepStrictEqual( sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), sequenceS(option.Applicative)({ a: option.some(1), b: option.some(2) }) ) ``` Added in v2.5.0 ## size Calculate the number of key/value pairs in a `ReadonlyRecord`, **Signature** ```ts export declare const size: (r: Readonly>) => number ``` **Example** ```ts import { size } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(size({ a: true, b: 2, c: 'three' }), 3) ``` Added in v2.5.0 ## some Test if at least one value in a `ReadonlyRecord` satisfies the predicate. **Signature** ```ts export declare function some(predicate: (a: A) => boolean): (r: ReadonlyRecord) => boolean ``` **Example** ```ts import { some } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(some((n: number) => n >= 0)({ a: 1, b: -2 }), true) assert.deepStrictEqual(some((n: number) => n >= 0)({ a: -1, b: -2 }), false) ``` Added in v2.5.0 ## traverse **Signature** ```ts export declare function traverse( F: Applicative4 ): ( f: (a: A) => Kind4 ) => (ta: ReadonlyRecord) => Kind4> export declare function traverse( F: Applicative3 ): ( f: (a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export declare function traverse( F: Applicative3C ): ( f: (a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export declare function traverse( F: Applicative2 ): ( f: (a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export declare function traverse( F: Applicative2C ): ( f: (a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export declare function traverse( F: Applicative1 ): (f: (a: A) => Kind) => (ta: ReadonlyRecord) => Kind> export declare function traverse( F: Applicative ): (f: (a: A) => HKT) => (ta: ReadonlyRecord) => HKT> ``` Added in v2.5.0 ## traverseWithIndex **Signature** ```ts export declare function traverseWithIndex( F: Applicative4 ): ( f: (k: K, a: A) => Kind4 ) => (ta: ReadonlyRecord) => Kind4> export declare function traverseWithIndex( F: Applicative3 ): ( f: (k: K, a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export declare function traverseWithIndex( F: Applicative3C ): ( f: (k: K, a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export declare function traverseWithIndex( F: Applicative2 ): ( f: (k: K, a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export declare function traverseWithIndex( F: Applicative2C ): ( f: (k: K, a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export declare function traverseWithIndex( F: Applicative1 ): ( f: (k: K, a: A) => Kind ) => (ta: ReadonlyRecord) => Kind> export declare function traverseWithIndex( F: Applicative ): (f: (k: K, a: A) => HKT) => (ta: ReadonlyRecord) => HKT> ``` Added in v2.5.0 ## union Union of two `ReadonlyRecord`s. Takes two `ReadonlyRecord`s and produces a `ReadonlyRecord` combining all the entries of the two inputs. It uses the `concat` function of the provided `Magma` to combine the elements with the same key. **Signature** ```ts export declare const union: ( M: Magma ) => (second: Readonly>) => (first: Readonly>) => Readonly> ``` **Example** ```ts import { union } from 'fp-ts/ReadonlyRecord' import { Magma } from 'fp-ts/Magma' const m1: Magma = { concat: (x: number, y: number) => x + y } assert.deepStrictEqual(union(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4, b: 2, c: 3 }) const m2: Magma = { concat: (x: number) => x } assert.deepStrictEqual(union(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 }) ``` Added in v2.11.0 ## updateAt Replace a key/value pair in a `ReadonlyRecord`. **Signature** ```ts export declare const updateAt: ( k: string, a: A ) => (r: Readonly>) => Option>> ``` **Example** ```ts import { updateAt } from 'fp-ts/ReadonlyRecord' import { option } from 'fp-ts' assert.deepStrictEqual(updateAt('a', 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })) assert.deepStrictEqual(updateAt('c', 3)({ a: 1, b: 2 }), option.none) ``` Added in v2.5.0 ## upsertAt Insert or replace a key/value pair in a `ReadonlyRecord`. **Signature** ```ts export declare const upsertAt: (k: string, a: A) => (r: Readonly>) => Readonly> ``` **Example** ```ts import { upsertAt } from 'fp-ts/ReadonlyRecord' assert.deepStrictEqual(upsertAt('a', 5)({ a: 1, b: 2 }), { a: 5, b: 2 }) assert.deepStrictEqual(upsertAt('c', 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 }) ``` Added in v2.10.0 # zone of death ## ~~FoldableWithIndex~~ Use `getFoldableWithIndex` instead. **Signature** ```ts export declare const FoldableWithIndex: FoldableWithIndex1<'ReadonlyRecord', string> ``` Added in v2.7.0 ## ~~Foldable~~ Use `getFoldable` instead. **Signature** ```ts export declare const Foldable: Foldable1<'ReadonlyRecord'> ``` Added in v2.7.0 ## ~~TraversableWithIndex~~ Use `getTraversableWithIndex` instead. **Signature** ```ts export declare const TraversableWithIndex: TraversableWithIndex1<'ReadonlyRecord', string> ``` Added in v2.7.0 ## ~~Traversable~~ Use `getTraversable` instead. **Signature** ```ts export declare const Traversable: Traversable1<'ReadonlyRecord'> ``` Added in v2.7.0 ## ~~Witherable~~ Use `getWitherable` instead. **Signature** ```ts export declare const Witherable: Witherable1<'ReadonlyRecord'> ``` Added in v2.7.0 ## ~~hasOwnProperty (function)~~ Use [`has`](#has) instead. **Signature** ```ts export declare function hasOwnProperty(k: string, r: ReadonlyRecord): k is K ``` Added in v2.5.0 ## ~~insertAt~~ Use [`upsertAt`](#upsertat) instead. **Signature** ```ts export declare const insertAt: (k: string, a: A) => (r: Readonly>) => Readonly> ``` Added in v2.5.0 ## ~~readonlyRecord~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RR.Functor` instead of `RR.readonlyRecord` (where `RR` is from `import RR from 'fp-ts/ReadonlyRecord'`) **Signature** ```ts export declare const readonlyRecord: FunctorWithIndex1<'ReadonlyRecord', string> & FoldableWithIndex1<'ReadonlyRecord', string> & FilterableWithIndex1<'ReadonlyRecord', string> & TraversableWithIndex1<'ReadonlyRecord', string> & Witherable1<'ReadonlyRecord'> ``` Added in v2.5.0 ================================================ FILE: docs/modules/ReadonlySet.ts.md ================================================ --- title: ReadonlySet.ts nav_order: 87 parent: Modules --- ## ReadonlySet overview Added in v2.5.0 ---

Table of contents

- [constructors](#constructors) - [singleton](#singleton) - [conversions](#conversions) - [fromReadonlyArray](#fromreadonlyarray) - [fromSet](#fromset) - [toReadonlyArray](#toreadonlyarray) - [toSet](#toset) - [folding](#folding) - [reduceRight](#reduceright) - [instances](#instances) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [chain](#chain) - [compact](#compact) - [difference](#difference) - [elem](#elem) - [empty](#empty) - [every](#every) - [filter](#filter) - [filterMap](#filtermap) - [foldMap](#foldmap) - [insert](#insert) - [intersection](#intersection) - [isEmpty](#isempty) - [isSubset](#issubset) - [map](#map) - [partition](#partition) - [partitionMap](#partitionmap) - [reduce](#reduce) - [remove](#remove) - [separate](#separate) - [size](#size) - [some](#some) - [toggle](#toggle) - [union](#union) - [zone of death](#zone-of-death) - [~~fromArray~~](#fromarray) --- # constructors ## singleton Create a set with one element **Signature** ```ts export declare const singleton:
(a: A) => ReadonlySet ``` Added in v2.5.0 # conversions ## fromReadonlyArray Create a `ReadonlySet` from a `ReadonlyArray` **Signature** ```ts export declare const fromReadonlyArray: (E: Eq) => (as: readonly A[]) => ReadonlySet ``` Added in v2.10.0 ## fromSet **Signature** ```ts export declare const fromSet: (s: Set) => ReadonlySet ``` Added in v2.5.0 ## toReadonlyArray Get a sorted `ReadonlyArray` of the values contained in a `ReadonlySet`. **Signature** ```ts export declare const toReadonlyArray: (O: Ord) => (set: ReadonlySet) => readonly A[] ``` Added in v2.5.0 ## toSet **Signature** ```ts export declare function toSet(s: ReadonlySet): Set ``` Added in v2.5.0 # folding ## reduceRight **Signature** ```ts export declare const reduceRight: (O: Ord) => (b: B, f: (a: A, b: B) => B) => (fa: ReadonlySet) => B ``` Added in v2.11.0 # instances ## getDifferenceMagma **Signature** ```ts export declare const getDifferenceMagma: (E: Eq) => Magma> ``` Added in v2.11.0 ## getEq **Signature** ```ts export declare function getEq(E: Eq): Eq> ``` Added in v2.5.0 ## getIntersectionSemigroup **Signature** ```ts export declare const getIntersectionSemigroup: (E: Eq) => Semigroup> ``` Added in v2.5.0 ## getShow **Signature** ```ts export declare function getShow(S: Show): Show> ``` Added in v2.5.0 ## getUnionMonoid **Signature** ```ts export declare const getUnionMonoid: (E: Eq) => Monoid> ``` Added in v2.5.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq) => Semigroup> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReadonlySet' ``` Added in v2.11.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.11.0 # utils ## chain **Signature** ```ts export declare function chain(E: Eq): (f: (x: A) => ReadonlySet) => (set: ReadonlySet) => ReadonlySet ``` Added in v2.5.0 ## compact **Signature** ```ts export declare const compact: (E: Eq) => (fa: ReadonlySet>) => ReadonlySet ``` Added in v2.5.0 ## difference Form the set difference (`x` - `y`) **Signature** ```ts export declare function difference(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => ReadonlySet (me: ReadonlySet, that: ReadonlySet): ReadonlySet } ``` **Example** ```ts import { difference } from 'fp-ts/ReadonlySet' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(new Set([1, 2]), difference(N.Eq)(new Set([1, 3]))), new Set([2])) ``` Added in v2.5.0 ## elem Test if a value is a member of a set **Signature** ```ts export declare function elem(E: Eq): { (a: A): (set: ReadonlySet) => boolean (a: A, set: ReadonlySet): boolean } ``` Added in v2.5.0 ## empty **Signature** ```ts export declare const empty: ReadonlySet ``` Added in v2.5.0 ## every **Signature** ```ts export declare function every(refinement: Refinement): Refinement, ReadonlySet> export declare function every(predicate: Predicate): Predicate> ``` Added in v2.5.0 ## filter **Signature** ```ts export declare function filter(refinement: Refinement): (set: ReadonlySet) => ReadonlySet export declare function filter(predicate: Predicate): (set: ReadonlySet) => ReadonlySet export declare function filter(predicate: Predicate): (set: ReadonlySet) => ReadonlySet ``` Added in v2.5.0 ## filterMap **Signature** ```ts export declare function filterMap(E: Eq): (f: (a: A) => Option) => (fa: ReadonlySet) => ReadonlySet ``` Added in v2.5.0 ## foldMap **Signature** ```ts export declare function foldMap(O: Ord, M: Monoid): (f: (a: A) => M) => (fa: ReadonlySet) => M ``` Added in v2.5.0 ## insert Insert a value into a set **Signature** ```ts export declare function insert(E: Eq): (a: A) => (set: ReadonlySet) => ReadonlySet ``` Added in v2.5.0 ## intersection The set of elements which are in both the first and second set **Signature** ```ts export declare function intersection(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => ReadonlySet (me: ReadonlySet, that: ReadonlySet): ReadonlySet } ``` Added in v2.5.0 ## isEmpty Test whether a `ReadonlySet` is empty. **Signature** ```ts export declare const isEmpty: (set: ReadonlySet) => boolean ``` Added in v2.10.0 ## isSubset `true` if and only if every element in the first set is an element of the second set **Signature** ```ts export declare function isSubset(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => boolean (me: ReadonlySet, that: ReadonlySet): boolean } ``` Added in v2.5.0 ## map Projects a Set through a function **Signature** ```ts export declare function map(E: Eq): (f: (x: A) => B) => (set: ReadonlySet) => ReadonlySet ``` Added in v2.5.0 ## partition **Signature** ```ts export declare function partition( refinement: Refinement ): (set: ReadonlySet) => Separated, ReadonlySet> export declare function partition( predicate: Predicate ): (set: ReadonlySet) => Separated, ReadonlySet> export declare function partition( predicate: Predicate ): (set: ReadonlySet) => Separated, ReadonlySet> ``` Added in v2.5.0 ## partitionMap **Signature** ```ts export declare function partitionMap( EB: Eq, EC: Eq ): (f: (a: A) => Either) => (set: ReadonlySet) => Separated, ReadonlySet> ``` Added in v2.5.0 ## reduce **Signature** ```ts export declare function reduce(O: Ord): (b: B, f: (b: B, a: A) => B) => (fa: ReadonlySet) => B ``` Added in v2.5.0 ## remove Delete a value from a set **Signature** ```ts export declare const remove: (E: Eq) => (a: A) => (set: ReadonlySet) => ReadonlySet ``` Added in v2.5.0 ## separate **Signature** ```ts export declare function separate( EE: Eq, EA: Eq ): (fa: ReadonlySet>) => Separated, ReadonlySet> ``` Added in v2.5.0 ## size Calculate the number of elements in a `ReadonlySet`. **Signature** ```ts export declare const size: (set: ReadonlySet) => number ``` Added in v2.10.0 ## some **Signature** ```ts export declare const some: (predicate: Predicate) => (set: ReadonlySet) => boolean ``` Added in v2.5.0 ## toggle Checks an element is a member of a set; If yes, removes the value from the set If no, inserts the value to the set **Signature** ```ts export declare const toggle: (E: Eq) => (a: A) => (set: ReadonlySet) => ReadonlySet ``` Added in v2.10.0 ## union Form the union of two sets **Signature** ```ts export declare function union(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => ReadonlySet (me: ReadonlySet, that: ReadonlySet): ReadonlySet } ``` Added in v2.5.0 # zone of death ## ~~fromArray~~ Use [`fromReadonlyArray`](#fromreadonlyarray) instead. **Signature** ```ts export declare const fromArray: (E: Eq) => (as: readonly A[]) => ReadonlySet ``` Added in v2.5.0 ================================================ FILE: docs/modules/ReadonlyTuple.ts.md ================================================ --- title: ReadonlyTuple.ts nav_order: 88 parent: Modules --- ## ReadonlyTuple overview Added in v2.5.0 ---

Table of contents

- [Extract](#extract) - [extract](#extract) - [error handling](#error-handling) - [mapLeft](#mapleft) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Bifunctor](#bifunctor) - [Comonad](#comonad) - [Foldable](#foldable) - [Functor](#functor) - [Semigroupoid](#semigroupoid) - [Traversable](#traversable) - [getApplicative](#getapplicative) - [getApply](#getapply) - [getChain](#getchain) - [getChainRec](#getchainrec) - [getMonad](#getmonad) - [mapping](#mapping) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [mapFst](#mapfst) - [mapSnd](#mapsnd) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [compose](#compose) - [duplicate](#duplicate) - [extend](#extend) - [fst](#fst) - [snd](#snd) - [swap](#swap) - [zone of death](#zone-of-death) - [~~readonlyTuple~~](#readonlytuple) --- # Extract ## extract **Signature** ```ts export declare const extract: (wa: readonly [A, E]) => A ``` Added in v2.6.2 # error handling ## mapLeft Alias of [`mapSnd`](#mapsnd). **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) =>
(fa: readonly [A, E]) => readonly [A, G] ``` Added in v2.5.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: readonly [A, E]) => M ``` Added in v2.5.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: readonly [A, E]) => B ``` Added in v2.5.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: readonly [A, E]) => B ``` Added in v2.5.0 # instances ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'ReadonlyTuple'> ``` Added in v2.7.0 ## Comonad **Signature** ```ts export declare const Comonad: Comonad2<'ReadonlyTuple'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable2<'ReadonlyTuple'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'ReadonlyTuple'> ``` Added in v2.7.0 ## Semigroupoid **Signature** ```ts export declare const Semigroupoid: Semigroupoid2<'ReadonlyTuple'> ``` Added in v2.7.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable2<'ReadonlyTuple'> ``` Added in v2.7.0 ## getApplicative **Signature** ```ts export declare function getApplicative(M: Monoid): Applicative2C ``` Added in v2.5.0 ## getApply **Signature** ```ts export declare function getApply(S: Semigroup): Apply2C ``` Added in v2.5.0 ## getChain **Signature** ```ts export declare function getChain(S: Semigroup): Chain2C ``` Added in v2.5.0 ## getChainRec **Signature** ```ts export declare function getChainRec(M: Monoid): ChainRec2C ``` Added in v2.5.0 ## getMonad **Signature** ```ts export declare function getMonad(M: Monoid): Monad2C ``` Added in v2.5.0 # mapping ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: ( mapSnd: (e: E) => G, mapFst: (a: A) => B ) => (fa: readonly [A, E]) => readonly [B, G] ``` Added in v2.5.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: readonly [(a: A) => B, E]) => readonly [B, E] ``` Added in v2.10.0 ## map Alias of [`mapFst`](#mapfst). **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: readonly [A, E]) => readonly [B, E] ``` Added in v2.5.0 ## mapFst Map a function over the first component of a `ReadonlyTuple`. This is the `map` operation of the `Functor` instance. **Signature** ```ts export declare const mapFst: (f: (a: A) => B) => (fa: readonly [A, E]) => readonly [B, E] ``` Added in v2.10.0 ## mapSnd Map a function over the second component of a `ReadonlyTuple`. This is the `mapLeft` operation of the `Bifunctor` instance. **Signature** ```ts export declare const mapSnd: (f: (e: E) => G) => (fa: readonly [A, E]) => readonly [A, G] ``` Added in v2.10.0 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence2<'ReadonlyTuple'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse2<'ReadonlyTuple'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'ReadonlyTuple' ``` Added in v2.5.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.5.0 # utils ## compose **Signature** ```ts export declare const compose: (ab: readonly [B, A]) => (bc: readonly [C, B]) => readonly [C, A] ``` Added in v2.5.0 ## duplicate **Signature** ```ts export declare const duplicate: (wa: readonly [A, E]) => readonly [readonly [A, E], E] ``` Added in v2.5.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: readonly [A, E]) => B) => (wa: readonly [A, E]) => readonly [B, E] ``` Added in v2.5.0 ## fst **Signature** ```ts export declare function fst(ea: readonly [A, E]): A ``` Added in v2.5.0 ## snd **Signature** ```ts export declare function snd(ea: readonly [A, E]): E ``` Added in v2.5.0 ## swap **Signature** ```ts export declare const swap: (ea: readonly [A, E]) => readonly [E, A] ``` Added in v2.5.0 # zone of death ## ~~readonlyTuple~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `RT.Functor` instead of `RT.readonlyTuple` (where `RT` is from `import RT from 'fp-ts/ReadonlyTuple'`) **Signature** ```ts export declare const readonlyTuple: Semigroupoid2<'ReadonlyTuple'> & Bifunctor2<'ReadonlyTuple'> & Comonad2<'ReadonlyTuple'> & Foldable2<'ReadonlyTuple'> & Traversable2<'ReadonlyTuple'> ``` Added in v2.5.0 ================================================ FILE: docs/modules/Record.ts.md ================================================ --- title: Record.ts nav_order: 89 parent: Modules --- ## Record overview The `Record` module enables dealing with Typescript's `Record` type in a functional way, basically treating it as a `Functor` in `T`. Added in v2.0.0 ---

Table of contents

- [conversions](#conversions) - [fromEntries](#fromentries) - [toArray](#toarray) - [toEntries](#toentries) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [getWitherable](#getwitherable) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [wilt](#wilt) - [wither](#wither) - [folding](#folding) - [foldMap](#foldmap) - [getFoldable](#getfoldable) - [getFoldableWithIndex](#getfoldablewithindex) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Compactable](#compactable) - [Filterable](#filterable) - [FilterableWithIndex](#filterablewithindex) - [Functor](#functor) - [FunctorWithIndex](#functorwithindex) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getMonoid](#getmonoid) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [traversing](#traversing) - [getTraversable](#gettraversable) - [getTraversableWithIndex](#gettraversablewithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [collect](#collect) - [deleteAt](#deleteat) - [difference](#difference) - [elem](#elem) - [every](#every) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [foldMapWithIndex](#foldmapwithindex) - [fromFoldable](#fromfoldable) - [fromFoldableMap](#fromfoldablemap) - [has](#has) - [intersection](#intersection) - [isEmpty](#isempty) - [isSubrecord](#issubrecord) - [keys](#keys) - [lookup](#lookup) - [mapWithIndex](#mapwithindex) - [modifyAt](#modifyat) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [pop](#pop) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [sequence](#sequence) - [singleton](#singleton) - [size](#size) - [some](#some) - [toUnfoldable](#tounfoldable) - [traverse](#traverse) - [traverseWithIndex](#traversewithindex) - [union](#union) - [updateAt](#updateat) - [upsertAt](#upsertat) - [zone of death](#zone-of-death) - [~~FoldableWithIndex~~](#foldablewithindex) - [~~Foldable~~](#foldable) - [~~TraversableWithIndex~~](#traversablewithindex) - [~~Traversable~~](#traversable) - [~~Witherable~~](#witherable) - [~~empty~~](#empty) - [~~hasOwnProperty (function)~~](#hasownproperty-function) - [~~insertAt~~](#insertat) - [~~record~~](#record) --- # conversions ## fromEntries Converts an `Array` of `[key, value]` tuples into a `Record`. **Signature** ```ts export declare const fromEntries:
(fa: [string, A][]) => Record ``` **Example** ```ts import { fromEntries } from 'fp-ts/Record' assert.deepStrictEqual( fromEntries([ ['a', 1], ['b', 2], ['a', 3], ]), { b: 2, a: 3 } ) ``` Added in v2.12.0 ## toArray Get a sorted `Array` of the key/value pairs contained in a `Record`. Sorted alphabetically by key. **Signature** ```ts export declare const toArray: (r: Record) => [K, A][] ``` **Example** ```ts import { toArray } from 'fp-ts/Record' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(toArray(x), [ ['a', 'foo'], ['b', false], ['c', 3], ]) ``` Added in v2.0.0 ## toEntries Alias of [`toArray`](#toArray). **Signature** ```ts export declare const toEntries: (r: Record) => [K, A][] ``` **Example** ```ts import { toEntries } from 'fp-ts/Record' assert.deepStrictEqual(toEntries({ b: 2, a: 1 }), [ ['a', 1], ['b', 2], ]) ``` Added in v2.12.0 # filtering ## compact Compact a `Record` of `Option`s discarding the `None` values and keeping the `Some` values. **Signature** ```ts export declare const compact: (fa: Record>) => Record ``` **Example** ```ts import { compact } from 'fp-ts/Record' import { option } from 'fp-ts' assert.deepStrictEqual(compact({ a: option.some('foo'), b: option.none, c: option.some('bar') }), { a: 'foo', c: 'bar', }) ``` Added in v2.0.0 ## filter Given a `Predicate`, it produces a new `Record` keeping only the entries with a value that satisfies the provided predicate. **Signature** ```ts export declare const filter: { (refinement: Refinement): (fa: Record) => Record (predicate: Predicate): (fb: Record) => Record (predicate: Predicate): (fa: Record) => Record } ``` **Example** ```ts import { filter } from 'fp-ts/Record' assert.deepStrictEqual(filter((s: string) => s.length < 4)({ a: 'foo', b: 'bar', c: 'verylong' }), { a: 'foo', b: 'bar', }) ``` Added in v2.0.0 ## filterMap Maps a `Record` with an iterating function that returns an `Option` and it keeps only the `Some` values discarding the `None`s. **Signature** ```ts export declare const filterMap: (f: (a: A) => Option) => (fa: Record) => Record ``` **Example** ```ts import { filterMap } from 'fp-ts/Record' import { option } from 'fp-ts' const f = (s: string) => (s.length < 4 ? option.some(`${s} is short`) : option.none) assert.deepStrictEqual(filterMap(f)({ a: 'foo', b: 'bar', c: 'verylong' }), { a: 'foo is short', b: 'bar is short', }) ``` Added in v2.0.0 ## getWitherable **Signature** ```ts export declare const getWitherable: (O: Ord) => Witherable1 ``` Added in v2.11.0 ## partition Partition a `Record` into two parts according to a `Predicate`. **Signature** ```ts export declare const partition: { (refinement: Refinement): ( fa: Record ) => Separated, Record> (predicate: Predicate): (fb: Record) => Separated, Record> (predicate: Predicate): (fa: Record) => Separated, Record> } ``` **Example** ```ts import { partition } from 'fp-ts/Record' assert.deepStrictEqual(partition((s: string) => s.length < 4)({ a: 'foo', b: 'bar', c: 'verylong' }), { left: { c: 'verylong', }, right: { a: 'foo', b: 'bar', }, }) ``` Added in v2.0.0 ## partitionMap Maps a `Record` with a function returning an `Either` and partitions the resulting `Record` into `Left`s and `Right`s. **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: Record) => Separated, Record> ``` **Example** ```ts import { partitionMap } from 'fp-ts/Record' import { either } from 'fp-ts' const f = (s: string) => (s.length < 4 ? either.right(`${s} is short`) : either.left(`${s} is not short`)) assert.deepStrictEqual(partitionMap(f)({ a: 'foo', b: 'bar', c: 'verylong' }), { left: { c: 'verylong is not short', }, right: { a: 'foo is short', b: 'bar is short', }, }) ``` Added in v2.0.0 ## separate Separate a `Record` of `Either`s into `Left`s and `Right`s. **Signature** ```ts export declare const separate: ( fa: Record> ) => Separated, Record> ``` **Example** ```ts import { separate } from 'fp-ts/Record' import { either } from 'fp-ts' assert.deepStrictEqual(separate({ a: either.right('foo'), b: either.left('bar'), c: either.right('baz') }), { right: { a: 'foo', c: 'baz', }, left: { b: 'bar', }, }) ``` Added in v2.0.0 ## wilt **Signature** ```ts export declare const wilt: PipeableWilt1<'Record'> ``` Added in v2.6.5 ## wither **Signature** ```ts export declare const wither: PipeableWither1<'Record'> ``` Added in v2.6.5 # folding ## foldMap Map and fold a `Record`. Map the `Record` passing each value to the iterating function. Then fold the results using the provided `Monoid`. **Signature** ```ts export declare function foldMap( O: Ord ): (M: Monoid) => (f: (a: A) => M) => (fa: Record) => M export declare function foldMap(M: Monoid): (f: (a: A) => M) => (fa: Record) => M ``` **Example** ```ts import { foldMap } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' import { Monoid } from 'fp-ts/Monoid' const m: Monoid = { empty: '', concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) } const f = (a: number) => `-${a}-` const x = { c: 3, a: 1, b: 2 } assert.deepStrictEqual(foldMap(Ord)(m)(f)(x), '-1- -> -2- -> -3-') ``` Added in v2.0.0 ## getFoldable Produces a `Foldable` instance for a `Record`, using the provided `Ord` to sort the `Record`'s entries by key. **Signature** ```ts export declare const getFoldable: (O: Ord) => Foldable1 ``` Added in v2.11.0 ## getFoldableWithIndex Produces a `FoldableWithIndex1` instance for a `Record`, using the provided `Ord` to sort the `Record`'s entries by key. **Signature** ```ts export declare const getFoldableWithIndex: (O: Ord) => FoldableWithIndex1 ``` Added in v2.11.0 ## reduce Reduces a `Record` passing each value to the iterating function. Entries are processed in order, sorted by key according to the given `Ord`. **Signature** ```ts export declare function reduce(O: Ord): (b: B, f: (b: B, a: A) => B) => (fa: Record) => B export declare function reduce(b: B, f: (b: B, a: A) => B): (fa: Record) => B ``` **Example** ```ts import { reduce } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduce(Ord)([] as string[], (b, a) => [...b, `-${a}-`])(x), ['-foo-', '-false-', '-3-']) ``` Added in v2.0.0 ## reduceRight Same as `reduce` but entries are processed _from the right_, i.e. in reverse order, from the last to the first entry, according to the given `Ord`. **Signature** ```ts export declare function reduceRight(O: Ord): (b: B, f: (a: A, b: B) => B) => (fa: Record) => B export declare function reduceRight(b: B, f: (a: A, b: B) => B): (fa: Record) => B ``` **Example** ```ts import { reduceRight } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduceRight(Ord)([] as string[], (a, b) => [...b, `-${a}-`])(x), ['-3-', '-false-', '-foo-']) ``` Added in v2.0.0 # instances ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'Record'> ``` Added in v2.7.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'Record'> ``` Added in v2.7.0 ## FilterableWithIndex **Signature** ```ts export declare const FilterableWithIndex: FilterableWithIndex1<'Record', string> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'Record'> ``` Added in v2.7.0 ## FunctorWithIndex **Signature** ```ts export declare const FunctorWithIndex: FunctorWithIndex1<'Record', string> ``` Added in v2.7.0 ## getDifferenceMagma Produces a `Magma` with a `concat` function that combines two `Record`s by making the `difference`. **Signature** ```ts export declare const getDifferenceMagma: () => Magma> ``` **Example** ```ts import { getDifferenceMagma, difference } from 'fp-ts/Record' import { Magma } from 'fp-ts/Magma' const r1 = { a: 3, c: 3 } const r2 = { a: 1, b: 2 } const m: Magma> = getDifferenceMagma() assert.deepStrictEqual(m.concat(r1, r2), difference(r2)(r1)) assert.deepStrictEqual(m.concat(r1, r2), { c: 3, b: 2 }) ``` Added in v2.11.0 ## getEq Given an `Eq` for the base type, it produces an `Eq` for a `Record` of that base type. **Signature** ```ts export declare const getEq: (E: Eq) => Eq> ``` **Example** ```ts import { getEq } from 'fp-ts/Record' import { string } from 'fp-ts' import { Eq } from 'fp-ts/Eq' const eq: Eq> = getEq(string.Eq) assert.deepStrictEqual(eq.equals({ a: 'foo' }, { b: 'bar' }), false) assert.deepStrictEqual(eq.equals({ a: 'foo' }, { a: 'foo' }), true) ``` Added in v2.0.0 ## getIntersectionSemigroup Given a `Semigroup` in the base type, it produces a `Semigroup` in the `Record` of the base type. The resulting `Semigroup` concatenates two `Record`s by `intersection`. **Signature** ```ts export declare const getIntersectionSemigroup: (S: Se.Semigroup) => Se.Semigroup> ``` **Example** ```ts import { getIntersectionSemigroup } from 'fp-ts/Record' import { Semigroup } from 'fp-ts/Semigroup' const sNumber: Semigroup = { concat: (x, y) => x - y } const sRecord: Semigroup> = getIntersectionSemigroup(sNumber) assert.deepStrictEqual(sRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { b: -1 }) ``` Added in v2.11.0 ## getMonoid Returns a `Monoid` instance for `Record`s, given a `Semigroup` instance for the base type. The `Monoid` makes the union of two `Record`s comining the overlapping entries with the provided `Semigroup`. **Signature** ```ts export declare const getMonoid: (S: Se.Semigroup) => Monoid> ``` **Example** ```ts import { SemigroupSum } from 'fp-ts/number' import { getMonoid } from 'fp-ts/Record' const M = getMonoid(SemigroupSum) assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579, bar: 234, baz: 567 }) ``` Added in v2.0.0 ## getShow Produces a `Show` for a `Record`, given a `Show` for the base type (a `Show` produces a human-readable representation of an instance). `Record` entries are sorted by key with the provided `Ord`. **Signature** ```ts export declare function getShow(O: Ord): (S: Show) => Show> export declare function getShow(S: Show): Show> ``` **Example** ```ts import { getShow } from 'fp-ts/Record' import { Show } from 'fp-ts/Show' import { Ord } from 'fp-ts/string' const sNumber: Show = { show: (n: number) => `${n}` } const sRecord: Show> = getShow(Ord)(sNumber) assert.deepStrictEqual(sRecord.show({ b: 2, a: 1 }), '{ "a": 1, "b": 2 }') ``` Added in v2.0.0 ## getUnionMonoid Same as `getMonoid`. Returns a `Monoid` instance for `Record`s given a `Semigroup` instance for the base type. The `Monoid` makes the union of two `Record`s combining the entries that have the same key with the provided `Semigroup`. **Signature** ```ts export declare const getUnionMonoid: (S: Se.Semigroup) => Monoid> ``` **Example** ```ts import { SemigroupSum } from 'fp-ts/number' import { getUnionMonoid } from 'fp-ts/Record' const M = getUnionMonoid(SemigroupSum) assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579, bar: 234, baz: 567 }) ``` Added in v2.11.0 ## getUnionSemigroup Given a `Semigroup` in the base type, it produces a `Semigroup` in the `Record` of the base type. The resulting `Semigroup` concatenates two `Record`s by `union`. **Signature** ```ts export declare const getUnionSemigroup: (S: Se.Semigroup) => Se.Semigroup> ``` **Example** ```ts import { getUnionSemigroup } from 'fp-ts/Record' import { Semigroup } from 'fp-ts/Semigroup' const sNumber: Semigroup = { concat: (x, y) => x - y } const sRecord: Semigroup> = getUnionSemigroup(sNumber) assert.deepStrictEqual(sRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { a: 1, b: -1, c: 4 }) ``` Added in v2.11.0 # mapping ## flap Takes a value and a `Record` of functions and returns a `Record` by applying each function to the input value. **Signature** ```ts export declare const flap: (a: A) => (fab: Record B>) => Record ``` **Example** ```ts import { flap } from 'fp-ts/Record' const fab = { x: (n: number) => `${n} times 2`, y: (n: number) => `${n * 2}` } assert.deepStrictEqual(flap(3)(fab), { x: '3 times 2', y: '6', }) ``` Added in v2.10.0 ## map Map a `Record` passing the values to the iterating function. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Record) => Record ``` **Example** ```ts import { map } from 'fp-ts/Record' const f = (n: number) => `-${n}-` assert.deepStrictEqual(map(f)({ a: 3, b: 5 }), { a: '-3-', b: '-5-' }) ``` Added in v2.0.0 # traversing ## getTraversable Produces a `Traversable` instance for a `Record`, using the provided `Ord` to sort the `Record`'s entries by key. **Signature** ```ts export declare const getTraversable: (O: Ord) => Traversable1 ``` Added in v2.11.0 ## getTraversableWithIndex Produces a `TraversableWithIndex` instance for a `Record`, using the provided `Ord` to sort the `Record`'s entries by key. **Signature** ```ts export declare const getTraversableWithIndex: (O: Ord) => TraversableWithIndex1 ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Record' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## collect Map a `Record` into an `Array`. It passes each key/value pair to the iterating function and collects the results in an array, sorted alphabetically by the original key. **Signature** ```ts export declare function collect( O: Ord ): (f: (k: K, a: A) => B) => (r: Record) => Array export declare function collect(f: (k: K, a: A) => B): (r: Record) => Array ``` **Example** ```ts import { collect } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' const f = (k: string, a: A) => `${k.toUpperCase()}-${a}` const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(collect(Ord)(f)(x), ['A-foo', 'B-false', 'C-3']) ``` Added in v2.0.0 ## deleteAt Delete a key and value from a `Record`. **Signature** ```ts export declare function deleteAt( k: K ): (r: Record) => Record, A> ``` **Example** ```ts import { deleteAt } from 'fp-ts/Record' assert.deepStrictEqual(deleteAt('a')({ a: 1, b: 2 }), { b: 2 }) assert.deepStrictEqual(deleteAt('c')({ a: 1, b: 2 }), { a: 1, b: 2 }) ``` Added in v2.0.0 ## difference Difference between two `Record`s. Takes two `Record`s and produces a `Record` composed by the entries of the two inputs, removing the entries with the same key in both inputs. **Signature** ```ts export declare const difference: (second: Record) => (first: Record) => Record ``` **Example** ```ts import { difference } from 'fp-ts/Record' assert.deepStrictEqual(difference({ a: 1 })({ a: 1, b: 2 }), { b: 2 }) assert.deepStrictEqual(difference({ a: 3 })({ a: 1, b: 2 }), { b: 2 }) assert.deepStrictEqual(difference({ a: 3, c: 3 })({ a: 1, b: 2 }), { b: 2, c: 3 }) ``` Added in v2.11.0 ## elem Given an `Eq` checks if a `Record` contains an entry with value equal to a provided value. **Signature** ```ts export declare const elem: (E: Eq) => { (a: A): (fa: Record) => boolean (a: A, fa: Record): boolean } ``` **Example** ```ts import { elem } from 'fp-ts/Record' import { number } from 'fp-ts' assert.deepStrictEqual(elem(number.Eq)(123, { foo: 123, bar: 234 }), true) assert.deepStrictEqual(elem(number.Eq)(-7, { foo: 123, bar: 234 }), false) ``` Added in v2.0.0 ## every Test if every value in a `Record` satisfies the predicate. **Signature** ```ts export declare const every: { (refinement: Refinement): Refinement, Record> (predicate: Predicate): Predicate> } ``` **Example** ```ts import { every } from 'fp-ts/Record' assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: 2 }), true) assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: -1 }), false) ``` Added in v2.0.0 ## filterMapWithIndex Maps a `Record` with an iterating function that takes key and value and returns an `Option`, keeping only the `Some` values and discarding `None`s. **Signature** ```ts export declare const filterMapWithIndex: ( f: (key: K, a: A) => Option ) => (fa: Record) => Record ``` **Example** ```ts import { filterMapWithIndex } from 'fp-ts/Record' import { option } from 'fp-ts' const f = (key: string, a: number) => (a >= 0 ? option.some(`${key}${a}`) : option.none) assert.deepStrictEqual(filterMapWithIndex(f)({ a: -1, b: 2, c: 3 }), { b: 'b2', c: 'c3', }) ``` Added in v2.0.0 ## filterWithIndex Produce a new `Record` keeping only the entries that satisfy a predicate taking key and value as input. **Signature** ```ts export declare function filterWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: Record) => Record export declare function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: Record) => Record export declare function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: Record) => Record ``` **Example** ```ts import { filterWithIndex } from 'fp-ts/Record' assert.deepStrictEqual(filterWithIndex((s: string, v: number) => s.length <= 1 && v > 0)({ a: 1, b: -2, ccc: 3 }), { a: 1, }) ``` Added in v2.0.0 ## foldMapWithIndex Map and fold a `Record`. Map the `Record` passing each key/value pair to the iterating function. Then fold the results using the provided `Monoid`. **Signature** ```ts export declare function foldMapWithIndex( O: Ord ): (M: Monoid) => (f: (k: K, a: A) => M) => (fa: Record) => M export declare function foldMapWithIndex( M: Monoid ): (f: (k: K, a: A) => M) => (fa: Record) => M ``` **Example** ```ts import { foldMapWithIndex } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' import { Monoid } from 'fp-ts/Monoid' const m: Monoid = { empty: '', concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) } const f = (k: string, a: number) => `${k}-${a}` const x = { c: 3, a: 1, b: 2 } assert.deepStrictEqual(foldMapWithIndex(Ord)(m)(f)(x), 'a-1 -> b-2 -> c-3') ``` Added in v2.0.0 ## fromFoldable Create a `Record` from a foldable collection of key/value pairs, using the specified `Magma` to combine values for duplicate keys. **Signature** ```ts export declare function fromFoldable( M: Magma, F: Foldable3 ): (fka: Kind3) => Record export declare function fromFoldable( M: Magma, F: Foldable2 ): (fka: Kind2) => Record export declare function fromFoldable( M: Magma, F: Foldable1 ): (fka: Kind) => Record export declare function fromFoldable( M: Magma, F: FoldableHKT ): (fka: HKT) => Record ``` Added in v2.0.0 ## fromFoldableMap Create a `Record` from a foldable collection using the specified functions to - map to key/value pairs - combine values for duplicate keys. **Signature** ```ts export declare function fromFoldableMap( M: Magma, F: Foldable3 ): (fa: Kind3, f: (a: A) => [string, B]) => Record export declare function fromFoldableMap( M: Magma, F: Foldable2 ): (fa: Kind2, f: (a: A) => [string, B]) => Record export declare function fromFoldableMap( M: Magma, F: Foldable1 ): (fa: Kind, f: (a: A) => [string, B]) => Record export declare function fromFoldableMap( M: Magma, F: FoldableHKT ): (fa: HKT, f: (a: A) => [string, B]) => Record ``` **Example** ```ts import { last } from 'fp-ts/Semigroup' import { Foldable, zip } from 'fp-ts/Array' import { identity } from 'fp-ts/function' import { fromFoldableMap } from 'fp-ts/Record' export const zipObject = (keys: Array, values: Array): Record => fromFoldableMap(last(), Foldable)(zip(keys, values), identity) assert.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 }) interface User { readonly id: string readonly name: string } const users: Array = [ { id: 'id1', name: 'name1' }, { id: 'id2', name: 'name2' }, { id: 'id1', name: 'name3' }, ] assert.deepStrictEqual( fromFoldableMap(last(), Foldable)(users, (user) => [user.id, user]), { id1: { id: 'id1', name: 'name3' }, id2: { id: 'id2', name: 'name2' }, } ) ``` Added in v2.0.0 ## has Test whether or not a key exists in a `Record`. Note. This function is not pipeable because is a `Refinement`. **Signature** ```ts export declare const has: (k: string, r: Record) => k is K ``` **Example** ```ts import { has } from 'fp-ts/Record' assert.deepStrictEqual(has('a', { a: 1, b: 2 }), true) assert.deepStrictEqual(has('c', { a: 1, b: 2 }), false) ``` Added in v2.10.0 ## intersection Intersection of two `Record`s. Takes two `Record`s and produces a `Record` combining only the entries of the two inputswith the same key. It uses the `concat` function of the provided `Magma` to combine the elements. **Signature** ```ts export declare const intersection: ( M: Magma ) => (second: Record) => (first: Record) => Record ``` **Example** ```ts import { intersection } from 'fp-ts/Record' import { Magma } from 'fp-ts/Magma' const m1: Magma = { concat: (x: number, y: number) => x + y } assert.deepStrictEqual(intersection(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4 }) const m2: Magma = { concat: (x: number) => x } assert.deepStrictEqual(intersection(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1 }) ``` Added in v2.11.0 ## isEmpty Test whether a `Record` is empty. **Signature** ```ts export declare const isEmpty: (r: Record) => boolean ``` **Example** ```ts import { isEmpty } from 'fp-ts/Record' assert.deepStrictEqual(isEmpty({}), true) assert.deepStrictEqual(isEmpty({ a: 3 }), false) ``` Added in v2.0.0 ## isSubrecord Test whether one `Record` contains all of the keys and values contained in another `Record`. **Signature** ```ts export declare const isSubrecord: (E: Eq) => { (that: Record): (me: Record) => boolean (me: Record, that: Record): boolean } ``` **Example** ```ts import { isSubrecord } from 'fp-ts/Record' import { string } from 'fp-ts' assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', b: 'bar', c: 'baz' }), true) assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', c: 'baz' }), true) assert.deepStrictEqual( isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', b: 'not-bar', c: 'baz' }), false ) assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar' })({ a: 'foo', b: 'bar', c: 'baz' }), false) ``` Added in v2.0.0 ## keys The keys of a `Record`, sorted alphabetically. **Signature** ```ts export declare const keys: (r: Record) => K[] ``` **Example** ```ts import { keys } from 'fp-ts/Record' assert.deepStrictEqual(keys({ c: 1, a: 2, b: 3 }), ['a', 'b', 'c']) ``` Added in v2.0.0 ## lookup Lookup the value for a key in a `Record`. **Signature** ```ts export declare const lookup: { (k: string): (r: Record) => Option (k: string, r: Record): Option } ``` **Example** ```ts import { lookup } from 'fp-ts/Record' import { option } from 'fp-ts' assert.deepStrictEqual(lookup('b')({ a: 'foo', b: 'bar' }), option.some('bar')) assert.deepStrictEqual(lookup('c')({ a: 'foo', b: 'bar' }), option.none) ``` Added in v2.0.0 ## mapWithIndex Map a `Record` passing the key/value pairs to the iterating function. **Signature** ```ts export declare const mapWithIndex: (f: (k: K, a: A) => B) => (fa: Record) => Record ``` **Example** ```ts import { mapWithIndex } from 'fp-ts/Record' const f = (k: string, n: number) => `${k.toUpperCase()}-${n}` assert.deepStrictEqual(mapWithIndex(f)({ a: 3, b: 5 }), { a: 'A-3', b: 'B-5' }) ``` Added in v2.0.0 ## modifyAt Applies a mapping function to one spcific key/value pair in a `Record`. **Signature** ```ts export declare const modifyAt: ( k: string, f: (a: A) => A ) => (r: Record) => Option> ``` **Example** ```ts import { modifyAt } from 'fp-ts/Record' import { option } from 'fp-ts' assert.deepStrictEqual(modifyAt('a', (x: number) => x * 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })) assert.deepStrictEqual(modifyAt('c', (x: number) => x * 3)({ a: 1, b: 2 }), option.none) ``` Added in v2.0.0 ## partitionMapWithIndex Maps a `Record` with a function returning an `Either` and partitions the resulting `Record` into `Left`s and `Right`s. **Signature** ```ts export declare const partitionMapWithIndex: ( f: (key: K, a: A) => Either ) => (fa: Record) => Separated, Record> ``` **Example** ```ts import { partitionMapWithIndex } from 'fp-ts/Record' import { either } from 'fp-ts' const f = (key: string, a: number) => a >= 0 ? either.right(`${key} is >= 0 (${a})`) : either.left(`${key} is < 0 (${a})`) assert.deepStrictEqual(partitionMapWithIndex(f)({ a: -1, b: 2, c: 123 }), { left: { a: 'a is < 0 (-1)', }, right: { b: 'b is >= 0 (2)', c: 'c is >= 0 (123)', }, }) ``` Added in v2.0.0 ## partitionWithIndex Partition a `Record` into two parts according to a predicate that takes a key and a value. **Signature** ```ts export declare function partitionWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: Record) => Separated, Record> export declare function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: Record) => Separated, Record> export declare function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: Record) => Separated, Record> ``` **Example** ```ts import { partitionWithIndex } from 'fp-ts/Record' assert.deepStrictEqual( partitionWithIndex((key: string, a: number) => key.length <= 1 && a > 0)({ a: -1, b: 2, ccc: 7 }), { left: { a: -1, ccc: 7, }, right: { b: 2, }, } ) ``` Added in v2.0.0 ## pop Delete a key and value from a `Record`, returning the value as well as the subsequent `Record`. **Signature** ```ts export declare function pop( k: K ): (r: Record) => Option<[A, Record, A>]> ``` **Example** ```ts import { pop } from 'fp-ts/Record' import { option } from 'fp-ts' assert.deepStrictEqual(pop('a')({ a: 1, b: 2, c: 3 }), option.some([1, { b: 2, c: 3 }])) assert.deepStrictEqual(pop('x')({ a: 1, b: 2, c: 3 }), option.none) ``` Added in v2.0.0 ## reduceRightWithIndex Same as `reduceWithIndex`, but reduce starting from the right (i.e. in reverse order, from the last to the first entry according to the given `Ord`). **Signature** ```ts export declare function reduceRightWithIndex( O: Ord ): (b: B, f: (k: K, a: A, b: B) => B) => (fa: Record) => B export declare function reduceRightWithIndex( b: B, f: (k: K, a: A, b: B) => B ): (fa: Record) => B ``` **Example** ```ts import { reduceRightWithIndex } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduceRightWithIndex(Ord)([] as string[], (k, a, b) => [...b, `${k}-${a}`])(x), [ 'c-3', 'b-false', 'a-foo', ]) ``` Added in v2.0.0 ## reduceWithIndex Reduces a `Record` passing each key/value pair to the iterating function. Entries are processed in the order, sorted by key according to the given `Ord`. **Signature** ```ts export declare function reduceWithIndex( O: Ord ): (b: B, f: (k: K, b: B, a: A) => B) => (fa: Record) => B export declare function reduceWithIndex( b: B, f: (k: K, b: B, a: A) => B ): (fa: Record) => B ``` **Example** ```ts import { reduceWithIndex } from 'fp-ts/Record' import { Ord } from 'fp-ts/string' const x = { c: 3, a: 'foo', b: false } assert.deepStrictEqual(reduceWithIndex(Ord)([] as string[], (k, b, a) => [...b, `${k}-${a}`])(x), [ 'a-foo', 'b-false', 'c-3', ]) ``` Added in v2.0.0 ## sequence `Record` sequencing, i.e., take a `Record` in which elements are monads and return a monad of a `Record` of the base types. The following example for instance shows sequencing a `Record>` into an `Option>`. `sequence` in `Record` is equivalent to `sequenceS` in `Apply.ts`. **Signature** ```ts export declare function sequence( F: Applicative3 ): (ta: Record>) => Kind3> export declare function sequence( F: Applicative3C ): (ta: Record>) => Kind3> export declare function sequence( F: Applicative2 ): (ta: Record>) => Kind2> export declare function sequence( F: Applicative2C ): (ta: Record>) => Kind2> export declare function sequence( F: Applicative1 ): (ta: Record>) => Kind> export declare function sequence( F: Applicative ): (ta: Record>) => HKT> ``` **Example** ```ts import { sequence } from 'fp-ts/Record' import { option } from 'fp-ts' import { sequenceS } from 'fp-ts/Apply' assert.deepStrictEqual( sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), option.some({ a: 1, b: 2 }) ) assert.deepStrictEqual(sequence(option.Applicative)({ a: option.some(1), b: option.none }), option.none) assert.deepStrictEqual( sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), sequenceS(option.Applicative)({ a: option.some(1), b: option.some(2) }) ) ``` Added in v2.0.0 ## singleton Create a `Record` with one key/value pair. **Signature** ```ts export declare const singleton: (k: string, a: A) => Record ``` **Example** ```ts import { singleton } from 'fp-ts/Record' assert.deepStrictEqual(singleton('a', 1), { a: 1 }) ``` Added in v2.0.0 ## size Calculate the number of key/value pairs in a `Record`. **Signature** ```ts export declare const size: (r: Record) => number ``` **Example** ```ts import { size } from 'fp-ts/Record' assert.deepStrictEqual(size({ a: true, b: 2, c: 'three' }), 3) ``` Added in v2.0.0 ## some Test if at least one value in a `Record` satisfies the predicate. **Signature** ```ts export declare const some: (predicate: (a: A) => boolean) => (r: Record) => boolean ``` **Example** ```ts import { some } from 'fp-ts/Record' assert.deepStrictEqual(some((n: number) => n >= 0)({ a: 1, b: -2 }), true) assert.deepStrictEqual(some((n: number) => n >= 0)({ a: -1, b: -2 }), false) ``` Added in v2.0.0 ## toUnfoldable Unfolds a `Record` into a list of key/value pairs. Given an `Unfoldable` class type `U` such as `array` or `readonlyArray`, it uses the `unfold` function to create an instance of `U`, providing an iterating function that iterates over each key/value pair in the record sorted alphabetically by key. **Signature** ```ts export declare function toUnfoldable( U: Unfoldable1 ): (r: Record) => Kind export declare function toUnfoldable(U: Unfoldable): (r: Record) => HKT ``` **Example** ```ts import { array, readonlyArray } from 'fp-ts' import { toUnfoldable } from 'fp-ts/Record' assert.deepStrictEqual(toUnfoldable(array)({ b: 2, a: 1 }), [ ['a', 1], ['b', 2], ]) assert.deepStrictEqual(toUnfoldable(readonlyArray)({ b: 2, a: 1 }), [ ['a', 1], ['b', 2], ]) ``` Added in v2.0.0 ## traverse **Signature** ```ts export declare function traverse( F: Applicative4 ): ( f: (a: A) => Kind4 ) => (ta: Record) => Kind4> export declare function traverse( F: Applicative3 ): (f: (a: A) => Kind3) => (ta: Record) => Kind3> export declare function traverse( F: Applicative3C ): (f: (a: A) => Kind3) => (ta: Record) => Kind3> export declare function traverse( F: Applicative2 ): (f: (a: A) => Kind2) => (ta: Record) => Kind2> export declare function traverse( F: Applicative2C ): (f: (a: A) => Kind2) => (ta: Record) => Kind2> export declare function traverse( F: Applicative1 ): (f: (a: A) => Kind) => (ta: Record) => Kind> export declare function traverse( F: Applicative ): (f: (a: A) => HKT) => (ta: Record) => HKT> ``` Added in v2.0.0 ## traverseWithIndex **Signature** ```ts export declare function traverseWithIndex( F: Applicative4 ): ( f: (k: K, a: A) => Kind4 ) => (ta: Record) => Kind4> export declare function traverseWithIndex( F: Applicative3 ): ( f: (k: K, a: A) => Kind3 ) => (ta: Record) => Kind3> export declare function traverseWithIndex( F: Applicative3C ): ( f: (k: K, a: A) => Kind3 ) => (ta: Record) => Kind3> export declare function traverseWithIndex( F: Applicative2 ): (f: (k: K, a: A) => Kind2) => (ta: Record) => Kind2> export declare function traverseWithIndex( F: Applicative2C ): (f: (k: K, a: A) => Kind2) => (ta: Record) => Kind2> export declare function traverseWithIndex( F: Applicative1 ): (f: (k: K, a: A) => Kind) => (ta: Record) => Kind> export declare function traverseWithIndex( F: Applicative ): (f: (k: K, a: A) => HKT) => (ta: Record) => HKT> ``` Added in v2.0.0 ## union Union of two `Record`s. Takes two `Record`s and produces a `Record` combining all the entries of the two inputs. It uses the `concat` function of the provided `Magma` to combine the elements with the same key. **Signature** ```ts export declare const union: ( M: Magma ) => (second: Record) => (first: Record) => Record ``` **Example** ```ts import { union } from 'fp-ts/Record' import { Magma } from 'fp-ts/Magma' const m1: Magma = { concat: (x: number, y: number) => x + y } assert.deepStrictEqual(union(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4, b: 2, c: 3 }) const m2: Magma = { concat: (x: number) => x } assert.deepStrictEqual(union(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 }) ``` Added in v2.11.0 ## updateAt Replace a key/value pair in a `Record`. **Signature** ```ts export declare const updateAt: (k: string, a: A) => (r: Record) => Option> ``` **Example** ```ts import { updateAt } from 'fp-ts/Record' import { option } from 'fp-ts' assert.deepStrictEqual(updateAt('a', 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })) assert.deepStrictEqual(updateAt('c', 3)({ a: 1, b: 2 }), option.none) ``` Added in v2.0.0 ## upsertAt Insert or replace a key/value pair in a `Record`. **Signature** ```ts export declare const upsertAt: (k: string, a: A) => (r: Record) => Record ``` **Example** ```ts import { upsertAt } from 'fp-ts/Record' assert.deepStrictEqual(upsertAt('a', 5)({ a: 1, b: 2 }), { a: 5, b: 2 }) assert.deepStrictEqual(upsertAt('c', 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 }) ``` Added in v2.10.0 # zone of death ## ~~FoldableWithIndex~~ Use `getFoldableWithIndex` instead. **Signature** ```ts export declare const FoldableWithIndex: FoldableWithIndex1<'Record', string> ``` Added in v2.7.0 ## ~~Foldable~~ Use `getFoldable` instead. **Signature** ```ts export declare const Foldable: Foldable1<'Record'> ``` Added in v2.7.0 ## ~~TraversableWithIndex~~ Use the `getTraversableWithIndex` instead. **Signature** ```ts export declare const TraversableWithIndex: TraversableWithIndex1<'Record', string> ``` Added in v2.7.0 ## ~~Traversable~~ Use `getTraversable` instead. **Signature** ```ts export declare const Traversable: Traversable1<'Record'> ``` Added in v2.7.0 ## ~~Witherable~~ Use `getWitherable` instead. **Signature** ```ts export declare const Witherable: Witherable1<'Record'> ``` Added in v2.7.0 ## ~~empty~~ Use a new `{}` instead. **Signature** ```ts export declare const empty: Record ``` Added in v2.0.0 ## ~~hasOwnProperty (function)~~ Use [`has`](#has) instead. **Signature** ```ts export declare const hasOwnProperty: (k: string, r: Record) => k is K ``` Added in v2.0.0 ## ~~insertAt~~ Use [`upsertAt`](#upsertat) instead. **Signature** ```ts export declare const insertAt: (k: string, a: A) => (r: Record) => Record ``` Added in v2.0.0 ## ~~record~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `R.Functor` instead of `R.record` (where `R` is from `import R from 'fp-ts/Record'`) **Signature** ```ts export declare const record: FunctorWithIndex1<'Record', string> & FoldableWithIndex1<'Record', string> & FilterableWithIndex1<'Record', string> & TraversableWithIndex1<'Record', string> & Witherable1<'Record'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Refinement.ts.md ================================================ --- title: Refinement.ts nav_order: 90 parent: Modules --- ## Refinement overview Added in v2.11.0 ---

Table of contents

- [constructors](#constructors) - [id](#id) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromOptionK](#fromoptionk) - [utils](#utils) - [Refinement (interface)](#refinement-interface) - [and](#and) - [compose](#compose) - [not](#not) - [or](#or) - [zero](#zero) --- # constructors ## id **Signature** ```ts export declare const id:
() => Refinement ``` Added in v2.11.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: (getEither: (a: A) => Either) => Refinement ``` Added in v2.11.0 ## fromOptionK Returns a `Refinement` from a `Option` returning function. This function ensures that a `Refinement` definition is type-safe. **Signature** ```ts export declare const fromOptionK: (getOption: (a: A) => Option) => Refinement ``` Added in v2.11.0 # utils ## Refinement (interface) **Signature** ```ts export interface Refinement { (a: A): a is B } ``` Added in v2.11.0 ## and **Signature** ```ts export declare const and: ( second: Refinement ) => (first: Refinement) => Refinement ``` Added in v2.11.0 ## compose **Signature** ```ts export declare const compose: ( bc: Refinement ) => (ab: Refinement) => Refinement ``` Added in v2.11.0 ## not **Signature** ```ts export declare const not: (refinement: Refinement) => Refinement> ``` Added in v2.11.0 ## or **Signature** ```ts export declare const or: ( second: Refinement ) => (first: Refinement) => Refinement ``` Added in v2.11.0 ## zero **Signature** ```ts export declare const zero: () => Refinement ``` Added in v2.11.0 ================================================ FILE: docs/modules/Ring.ts.md ================================================ --- title: Ring.ts nav_order: 91 parent: Modules --- ## Ring overview The `Ring` class is for types that support addition, multiplication, and subtraction operations. Instances must satisfy the following law in addition to the `Semiring` laws: - Additive inverse: `a - a <-> (zero - a) + a <-> zero` Adapted from https://github.com/purescript/purescript-prelude/blob/master/src/Data/Ring.purs Added in v2.0.0 ---

Table of contents

- [model](#model) - [Ring (interface)](#ring-interface) - [utils](#utils) - [negate](#negate) - [tuple](#tuple) - [zone of death](#zone-of-death) - [~~getFunctionRing~~](#getfunctionring) - [~~getTupleRing~~](#gettuplering) --- # model ## Ring (interface) **Signature** ```ts export interface Ring
extends Semiring { readonly sub: (x: A, y: A) => A } ``` Added in v2.0.0 # utils ## negate `negate x` can be used as a shorthand for `zero - x` **Signature** ```ts export declare const negate: (R: Ring) => (a: A) => A ``` Added in v2.0.0 ## tuple Given a tuple of `Ring`s returns a `Ring` for the tuple **Signature** ```ts export declare const tuple: ( ...rings: { [K in keyof A]: Ring } ) => Ring> ``` **Example** ```ts import { tuple } from 'fp-ts/Ring' import * as N from 'fp-ts/number' const R = tuple(N.Field, N.Field, N.Field) assert.deepStrictEqual(R.add([1, 2, 3], [4, 5, 6]), [5, 7, 9]) assert.deepStrictEqual(R.mul([1, 2, 3], [4, 5, 6]), [4, 10, 18]) assert.deepStrictEqual(R.one, [1, 1, 1]) assert.deepStrictEqual(R.sub([1, 2, 3], [4, 5, 6]), [-3, -3, -3]) assert.deepStrictEqual(R.zero, [0, 0, 0]) ``` Added in v2.10.0 # zone of death ## ~~getFunctionRing~~ Use [`getRing`](./function.ts.html#getring) instead. **Signature** ```ts export declare const getFunctionRing: (R: Ring) => Ring<(a: A) => B> ``` Added in v2.0.0 ## ~~getTupleRing~~ Use [`tuple`](#tuple) instead. **Signature** ```ts export declare const getTupleRing: []>( ...rings: T ) => Ring<{ [K in keyof T]: T[K] extends Ring ? A : never }> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Semigroup.ts.md ================================================ --- title: Semigroup.ts nav_order: 92 parent: Modules --- ## Semigroup overview If a type `A` can form a `Semigroup` it has an **associative** binary operation. ```ts interface Semigroup { readonly concat: (x: A, y: A) => A } ``` Associativity means the following equality must hold for any choice of `x`, `y`, and `z`. ```ts concat(x, concat(y, z)) = concat(concat(x, y), z) ``` A common example of a semigroup is the type `string` with the operation `+`. ```ts import { Semigroup } from 'fp-ts/Semigroup' const semigroupString: Semigroup = { concat: (x, y) => x + y, } const x = 'x' const y = 'y' const z = 'z' semigroupString.concat(x, y) // 'xy' semigroupString.concat(x, semigroupString.concat(y, z)) // 'xyz' semigroupString.concat(semigroupString.concat(x, y), z) // 'xyz' ``` _Adapted from https://typelevel.org/cats_ Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [constant](#constant) - [max](#max) - [min](#min) - [instances](#instances) - [first](#first) - [last](#last) - [model](#model) - [Semigroup (interface)](#semigroup-interface) - [utils](#utils) - [concatAll](#concatall) - [intercalate](#intercalate) - [reverse](#reverse) - [struct](#struct) - [tuple](#tuple) - [zone of death](#zone-of-death) - [~~fold~~](#fold) - [~~getDualSemigroup~~](#getdualsemigroup) - [~~getFirstSemigroup~~](#getfirstsemigroup) - [~~getFunctionSemigroup~~](#getfunctionsemigroup) - [~~getIntercalateSemigroup~~](#getintercalatesemigroup) - [~~getJoinSemigroup~~](#getjoinsemigroup) - [~~getLastSemigroup~~](#getlastsemigroup) - [~~getMeetSemigroup~~](#getmeetsemigroup) - [~~getObjectSemigroup~~](#getobjectsemigroup) - [~~getStructSemigroup~~](#getstructsemigroup) - [~~getTupleSemigroup~~](#gettuplesemigroup) - [~~semigroupAll~~](#semigroupall) - [~~semigroupAny~~](#semigroupany) - [~~semigroupProduct~~](#semigroupproduct) - [~~semigroupString~~](#semigroupstring) - [~~semigroupSum~~](#semigroupsum) - [~~semigroupVoid~~](#semigroupvoid) --- # constructors ## constant **Signature** ```ts export declare const constant:
(a: A) => Semigroup ``` Added in v2.10.0 ## max Get a semigroup where `concat` will return the maximum, based on the provided order. **Signature** ```ts export declare const max: (O: Or.Ord) => Semigroup ``` **Example** ```ts import * as N from 'fp-ts/number' import * as S from 'fp-ts/Semigroup' const S1 = S.max(N.Ord) assert.deepStrictEqual(S1.concat(1, 2), 2) ``` Added in v2.10.0 ## min Get a semigroup where `concat` will return the minimum, based on the provided order. **Signature** ```ts export declare const min: (O: Or.Ord) => Semigroup ``` **Example** ```ts import * as N from 'fp-ts/number' import * as S from 'fp-ts/Semigroup' const S1 = S.min(N.Ord) assert.deepStrictEqual(S1.concat(1, 2), 1) ``` Added in v2.10.0 # instances ## first Always return the first argument. **Signature** ```ts export declare const first: () => Semigroup ``` **Example** ```ts import * as S from 'fp-ts/Semigroup' assert.deepStrictEqual(S.first().concat(1, 2), 1) ``` Added in v2.10.0 ## last Always return the last argument. **Signature** ```ts export declare const last: () => Semigroup ``` **Example** ```ts import * as S from 'fp-ts/Semigroup' assert.deepStrictEqual(S.last().concat(1, 2), 2) ``` Added in v2.10.0 # model ## Semigroup (interface) **Signature** ```ts export interface Semigroup extends Magma {} ``` Added in v2.0.0 # utils ## concatAll Given a sequence of `as`, concat them and return the total. If `as` is empty, return the provided `startWith` value. **Signature** ```ts export declare const concatAll: (S: Semigroup) => (startWith: A) => (as: readonly A[]) => A ``` **Example** ```ts import { concatAll } from 'fp-ts/Semigroup' import * as N from 'fp-ts/number' const sum = concatAll(N.SemigroupSum)(0) assert.deepStrictEqual(sum([1, 2, 3]), 6) assert.deepStrictEqual(sum([]), 0) ``` Added in v2.10.0 ## intercalate Between each pair of elements insert `middle`. **Signature** ```ts export declare const intercalate: (middle: A) => (S: Semigroup) => Semigroup ``` **Example** ```ts import { intercalate } from 'fp-ts/Semigroup' import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' const S1 = pipe(S.Semigroup, intercalate(' + ')) assert.strictEqual(S1.concat('a', 'b'), 'a + b') ``` Added in v2.10.0 ## reverse The dual of a `Semigroup`, obtained by swapping the arguments of `concat`. **Signature** ```ts export declare const reverse: (S: Semigroup) => Semigroup ``` **Example** ```ts import { reverse } from 'fp-ts/Semigroup' import * as S from 'fp-ts/string' assert.deepStrictEqual(reverse(S.Semigroup).concat('a', 'b'), 'ba') ``` Added in v2.10.0 ## struct Given a struct of semigroups returns a semigroup for the struct. **Signature** ```ts export declare const struct: (semigroups: { [K in keyof A]: Semigroup }) => Semigroup<{ readonly [K in keyof A]: A[K] }> ``` **Example** ```ts import { struct } from 'fp-ts/Semigroup' import * as N from 'fp-ts/number' interface Point { readonly x: number readonly y: number } const S = struct({ x: N.SemigroupSum, y: N.SemigroupSum, }) assert.deepStrictEqual(S.concat({ x: 1, y: 2 }, { x: 3, y: 4 }), { x: 4, y: 6 }) ``` Added in v2.10.0 ## tuple Given a tuple of semigroups returns a semigroup for the tuple. **Signature** ```ts export declare const tuple: ( ...semigroups: { [K in keyof A]: Semigroup } ) => Semigroup> ``` **Example** ```ts import { tuple } from 'fp-ts/Semigroup' import * as B from 'fp-ts/boolean' import * as N from 'fp-ts/number' import * as S from 'fp-ts/string' const S1 = tuple(S.Semigroup, N.SemigroupSum) assert.deepStrictEqual(S1.concat(['a', 1], ['b', 2]), ['ab', 3]) const S2 = tuple(S.Semigroup, N.SemigroupSum, B.SemigroupAll) assert.deepStrictEqual(S2.concat(['a', 1, true], ['b', 2, false]), ['ab', 3, false]) ``` Added in v2.10.0 # zone of death ## ~~fold~~ Use [`concatAll`](#concatall) instead. **Signature** ```ts export declare function fold(S: Semigroup): { (startWith: A): (as: ReadonlyArray) => A (startWith: A, as: ReadonlyArray): A } ``` Added in v2.0.0 ## ~~getDualSemigroup~~ Use [`reverse`](#reverse) instead. **Signature** ```ts export declare const getDualSemigroup: (S: Semigroup) => Semigroup ``` Added in v2.0.0 ## ~~getFirstSemigroup~~ Use [`first`](#first) instead. **Signature** ```ts export declare const getFirstSemigroup: () => Semigroup ``` Added in v2.0.0 ## ~~getFunctionSemigroup~~ Use [`getSemigroup`](./function.ts.html#getSemigroup) instead. **Signature** ```ts export declare const getFunctionSemigroup: (S: Semigroup) => () => Semigroup<(a: A) => S> ``` Added in v2.0.0 ## ~~getIntercalateSemigroup~~ Use [`intercalate`](#intercalate) instead. **Signature** ```ts export declare const getIntercalateSemigroup: (middle: A) => (S: Semigroup) => Semigroup ``` Added in v2.5.0 ## ~~getJoinSemigroup~~ Use [`max`](#max) instead. **Signature** ```ts export declare const getJoinSemigroup: (O: Or.Ord) => Semigroup ``` Added in v2.0.0 ## ~~getLastSemigroup~~ Use [`last`](#last) instead. **Signature** ```ts export declare const getLastSemigroup: () => Semigroup ``` Added in v2.0.0 ## ~~getMeetSemigroup~~ Use [`min`](#min) instead. **Signature** ```ts export declare const getMeetSemigroup: (O: Or.Ord) => Semigroup ``` Added in v2.0.0 ## ~~getObjectSemigroup~~ Use [`getAssignSemigroup`](./struct.ts.html#getAssignSemigroup) instead. **Signature** ```ts export declare const getObjectSemigroup: () => Semigroup ``` Added in v2.0.0 ## ~~getStructSemigroup~~ Use [`struct`](#struct) instead. **Signature** ```ts export declare const getStructSemigroup: >>(semigroups: { [K in keyof O]: Semigroup }) => Semigroup ``` Added in v2.0.0 ## ~~getTupleSemigroup~~ Use [`tuple`](#tuple) instead. **Signature** ```ts export declare const getTupleSemigroup: []>( ...semigroups: T ) => Semigroup<{ [K in keyof T]: T[K] extends Semigroup ? A : never }> ``` Added in v2.0.0 ## ~~semigroupAll~~ Use [`SemigroupAll`](./boolean.ts.html#SemigroupAll) instead. **Signature** ```ts export declare const semigroupAll: Semigroup ``` Added in v2.0.0 ## ~~semigroupAny~~ Use [`SemigroupAny`](./boolean.ts.html#SemigroupAny) instead. **Signature** ```ts export declare const semigroupAny: Semigroup ``` Added in v2.0.0 ## ~~semigroupProduct~~ Use [`SemigroupProduct`](./number.ts.html#SemigroupProduct) instead. **Signature** ```ts export declare const semigroupProduct: Semigroup ``` Added in v2.0.0 ## ~~semigroupString~~ Use [`Semigroup`](./string.ts.html#Semigroup) instead. **Signature** ```ts export declare const semigroupString: Semigroup ``` Added in v2.0.0 ## ~~semigroupSum~~ Use [`SemigroupSum`](./number.ts.html#SemigroupSum) instead. **Signature** ```ts export declare const semigroupSum: Semigroup ``` Added in v2.0.0 ## ~~semigroupVoid~~ Use `void` module instead. **Signature** ```ts export declare const semigroupVoid: Semigroup ``` Added in v2.0.0 ================================================ FILE: docs/modules/Semigroupoid.ts.md ================================================ --- title: Semigroupoid.ts nav_order: 93 parent: Modules --- ## Semigroupoid overview Added in v2.0.0 ---

Table of contents

- [model](#model) - [Semigroupoid (interface)](#semigroupoid-interface) - [Semigroupoid2 (interface)](#semigroupoid2-interface) - [Semigroupoid2C (interface)](#semigroupoid2c-interface) - [Semigroupoid3 (interface)](#semigroupoid3-interface) - [Semigroupoid3C (interface)](#semigroupoid3c-interface) - [Semigroupoid4 (interface)](#semigroupoid4-interface) --- # model ## Semigroupoid (interface) **Signature** ```ts export interface Semigroupoid { readonly URI: F readonly compose: (bc: HKT2, ab: HKT2) => HKT2 } ``` Added in v2.0.0 ## Semigroupoid2 (interface) **Signature** ```ts export interface Semigroupoid2 { readonly URI: F readonly compose: (ab: Kind2, la: Kind2) => Kind2 } ``` Added in v2.0.0 ## Semigroupoid2C (interface) **Signature** ```ts export interface Semigroupoid2C { readonly URI: F readonly _E: A readonly compose: (ab: Kind2, la: Kind2) => Kind2 } ``` Added in v2.0.0 ## Semigroupoid3 (interface) **Signature** ```ts export interface Semigroupoid3 { readonly URI: F readonly compose: (ab: Kind3, la: Kind3) => Kind3 } ``` Added in v2.0.0 ## Semigroupoid3C (interface) **Signature** ```ts export interface Semigroupoid3C { readonly URI: F readonly _E: A readonly compose: (ab: Kind3, la: Kind3) => Kind3 } ``` Added in v2.2.0 ## Semigroupoid4 (interface) **Signature** ```ts export interface Semigroupoid4 { readonly URI: F readonly compose: (ab: Kind4, la: Kind4) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Semiring.ts.md ================================================ --- title: Semiring.ts nav_order: 94 parent: Modules --- ## Semiring overview The `Semiring` class is for types that support an addition and multiplication operation. Instances must satisfy the following laws: - Commutative monoid under addition: - Associativity: `(a + b) + c <-> a + (b + c)` - Identity: `zero + a = a + zero <-> a` - Commutative: `a + b <-> b + a` - Monoid under multiplication: - Associativity: `(a * b) * c <-> a * (b * c)` - Identity: `one * a <-> a * one <-> a` - Multiplication distributes over addition: - Left distributivity: `a * (b + c) <-> (a * b) + (a * c)` - Right distributivity: `(a + b) * c <-> (a * c) + (b * c)` - Annihilation: `zero * a <-> a * zero <-> zero` **Note:** The `number` type is not fully law abiding members of this class hierarchy due to the potential for arithmetic overflows, and the presence of `NaN` and `Infinity` values. The behaviour is unspecified in these cases. Added in v2.0.0 ---

Table of contents

- [model](#model) - [Semiring (interface)](#semiring-interface) - [zone of death](#zone-of-death) - [~~getFunctionSemiring~~](#getfunctionsemiring) --- # model ## Semiring (interface) **Signature** ```ts export interface Semiring
{ readonly add: (x: A, y: A) => A readonly zero: A readonly mul: (x: A, y: A) => A readonly one: A } ``` Added in v2.0.0 # zone of death ## ~~getFunctionSemiring~~ Use [`getSemiring`](./function.ts.html#getsemiring) instead. **Signature** ```ts export declare const getFunctionSemiring: (S: Semiring) => Semiring<(a: A) => B> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Separated.ts.md ================================================ --- title: Separated.ts nav_order: 95 parent: Modules --- ## Separated overview ```ts interface Separated { readonly left: E readonly right: A } ``` Represents a result of separating a whole into two parts. Added in v2.10.0 ---

Table of contents

- [constructors](#constructors) - [separated](#separated) - [error handling](#error-handling) - [mapLeft](#mapleft) - [instances](#instances) - [Bifunctor](#bifunctor) - [Functor](#functor) - [mapping](#mapping) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [model](#model) - [Separated (interface)](#separated-interface) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [left](#left) - [right](#right) --- # constructors ## separated **Signature** ```ts export declare const separated: (left: E, right: A) => Separated ``` Added in v2.10.0 # error handling ## mapLeft Map a function over the first type argument of a bifunctor. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) =>
(fa: Separated) => Separated ``` Added in v2.10.0 # instances ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'Separated'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Separated'> ``` Added in v2.10.0 # mapping ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Separated) => Separated ``` Added in v2.10.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Separated B>) => Separated ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Separated) => Separated ``` Added in v2.10.0 # model ## Separated (interface) A `Separated` type which holds `left` and `right` parts. **Signature** ```ts export interface Separated { readonly left: E readonly right: A } ``` Added in v2.10.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Separated' ``` Added in v2.10.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.10.0 # utils ## left **Signature** ```ts export declare const left: (s: Separated) => E ``` Added in v2.10.0 ## right **Signature** ```ts export declare const right: (s: Separated) => A ``` Added in v2.10.0 ================================================ FILE: docs/modules/Set.ts.md ================================================ --- title: Set.ts nav_order: 96 parent: Modules --- ## Set overview Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [singleton](#singleton) - [conversions](#conversions) - [fromArray](#fromarray) - [toArray](#toarray) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [getDifferenceMagma](#getdifferencemagma) - [getEq](#geteq) - [getIntersectionSemigroup](#getintersectionsemigroup) - [getShow](#getshow) - [getUnionMonoid](#getunionmonoid) - [getUnionSemigroup](#getunionsemigroup) - [utils](#utils) - [chain](#chain) - [compact](#compact) - [difference](#difference) - [elem](#elem) - [empty](#empty) - [every](#every) - [filter](#filter) - [filterMap](#filtermap) - [insert](#insert) - [intersection](#intersection) - [isEmpty](#isempty) - [isSubset](#issubset) - [map](#map) - [partition](#partition) - [partitionMap](#partitionmap) - [remove](#remove) - [separate](#separate) - [size](#size) - [some](#some) - [toggle](#toggle) - [union](#union) - [zone of death](#zone-of-death) - [~~subset~~](#subset) --- # constructors ## singleton Create a set with one element **Signature** ```ts export declare const singleton:
(a: A) => Set ``` Added in v2.0.0 # conversions ## fromArray Create a set from an array **Signature** ```ts export declare const fromArray: (E: Eq) => (as: A[]) => Set ``` Added in v2.0.0 ## toArray Get a sorted `Array` of the values contained in a `Set`. **Signature** ```ts export declare const toArray: (O: Ord) => (set: Set) => A[] ``` Added in v2.0.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (O: Ord, M: Monoid) => (f: (a: A) => M) => (fa: Set) => M ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (O: Ord) => (b: B, f: (b: B, a: A) => B) => (fa: Set) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (O: Ord) => (b: B, f: (a: A, b: B) => B) => (fa: Set) => B ``` Added in v2.11.0 # instances ## getDifferenceMagma **Signature** ```ts export declare const getDifferenceMagma: (E: Eq) => Magma> ``` Added in v2.11.0 ## getEq **Signature** ```ts export declare const getEq: (E: Eq) => Eq> ``` Added in v2.0.0 ## getIntersectionSemigroup **Signature** ```ts export declare const getIntersectionSemigroup: (E: Eq) => Semigroup> ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare const getShow: (S: Show) => Show> ``` Added in v2.0.0 ## getUnionMonoid **Signature** ```ts export declare const getUnionMonoid: (E: Eq) => Monoid> ``` Added in v2.0.0 ## getUnionSemigroup **Signature** ```ts export declare const getUnionSemigroup: (E: Eq) => Semigroup> ``` Added in v2.11.0 # utils ## chain Composes computations in sequence, using the return value of one computation to determine the next computation. **Signature** ```ts export declare function chain(E: Eq): (f: (x: A) => Set) => (set: Set) => Set ``` Added in v2.0.0 ## compact **Signature** ```ts export declare const compact: (E: Eq) => (fa: Set>) => Set ``` Added in v2.0.0 ## difference Form the set difference (`x` - `y`) **Signature** ```ts export declare function difference(E: Eq): { (that: Set): (me: Set) => Set (me: Set, that: Set): Set } ``` **Example** ```ts import { difference } from 'fp-ts/Set' import * as N from 'fp-ts/number' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(new Set([1, 2]), difference(N.Eq)(new Set([1, 3]))), new Set([2])) ``` Added in v2.0.0 ## elem Test if a value is a member of a set **Signature** ```ts export declare const elem: (E: Eq) => { (a: A): (set: Set) => boolean; (a: A, set: Set): boolean } ``` Added in v2.0.0 ## empty **Signature** ```ts export declare const empty: Set ``` Added in v2.0.0 ## every **Signature** ```ts export declare const every: { (refinement: Refinement): Refinement, Set> (predicate: Predicate): Predicate> } ``` Added in v2.0.0 ## filter **Signature** ```ts export declare function filter(refinement: Refinement): (set: Set) => Set export declare function filter(predicate: Predicate): (set: Set) => Set export declare function filter(predicate: Predicate): (set: Set) => Set ``` Added in v2.0.0 ## filterMap **Signature** ```ts export declare function filterMap(E: Eq): (f: (a: A) => Option) => (fa: Set) => Set ``` Added in v2.0.0 ## insert Insert a value into a set **Signature** ```ts export declare function insert(E: Eq): (a: A) => (set: Set) => Set ``` Added in v2.0.0 ## intersection The set of elements which are in both the first and second set **Signature** ```ts export declare function intersection(E: Eq): { (that: Set): (me: Set) => Set (me: Set, that: Set): Set } ``` Added in v2.0.0 ## isEmpty Test whether a `Set` is empty. **Signature** ```ts export declare const isEmpty: (set: Set) => boolean ``` Added in v2.10.0 ## isSubset **Signature** ```ts export declare const isSubset: (E: Eq) => (that: Set) => (me: Set) => boolean ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare function map(E: Eq): (f: (x: A) => B) => (set: Set) => Set ``` Added in v2.0.0 ## partition **Signature** ```ts export declare function partition( refinement: Refinement ): (set: Set) => Separated, Set> export declare function partition(predicate: Predicate): (set: Set) => Separated, Set> export declare function partition(predicate: Predicate): (set: Set) => Separated, Set> ``` Added in v2.0.0 ## partitionMap **Signature** ```ts export declare function partitionMap( EB: Eq, EC: Eq ): (f: (a: A) => Either) => (set: Set) => Separated, Set> ``` Added in v2.0.0 ## remove Delete a value from a set **Signature** ```ts export declare const remove: (E: Eq) => (a: A) => (set: Set) => Set ``` Added in v2.0.0 ## separate **Signature** ```ts export declare function separate(EE: Eq, EA: Eq): (fa: Set>) => Separated, Set> ``` Added in v2.0.0 ## size Calculate the number of elements in a `Set`. **Signature** ```ts export declare const size: (set: Set) => number ``` Added in v2.10.0 ## some **Signature** ```ts export declare const some: (predicate: Predicate) => (set: Set) => boolean ``` Added in v2.0.0 ## toggle Checks an element is a member of a set; If yes, removes the value from the set If no, inserts the value to the set **Signature** ```ts export declare const toggle: (E: Eq) => (a: A) => (set: Set) => Set ``` Added in v2.5.0 ## union Form the union of two sets **Signature** ```ts export declare function union(E: Eq): { (that: Set): (me: Set) => Set (me: Set, that: Set): Set } ``` Added in v2.0.0 # zone of death ## ~~subset~~ Use [`isSubset`](#issubset) instead. **Signature** ```ts export declare const subset: (E: Eq) => { (that: Set): (me: Set) => boolean (me: Set, that: Set): boolean } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Show.ts.md ================================================ --- title: Show.ts nav_order: 97 parent: Modules --- ## Show overview The `Show` type class represents those types which can be converted into a human-readable `string` representation. While not required, it is recommended that for any expression `x`, the string `show(x)` be executable TypeScript code which evaluates to the same value as the expression `x`. Added in v2.0.0 ---

Table of contents

- [model](#model) - [Show (interface)](#show-interface) - [utils](#utils) - [struct](#struct) - [tuple](#tuple) - [zone of death](#zone-of-death) - [~~getStructShow~~](#getstructshow) - [~~getTupleShow~~](#gettupleshow) - [~~showBoolean~~](#showboolean) - [~~showNumber~~](#shownumber) - [~~showString~~](#showstring) --- # model ## Show (interface) **Signature** ```ts export interface Show
{ readonly show: (a: A) => string } ``` Added in v2.0.0 # utils ## struct **Signature** ```ts export declare const struct: (shows: { [K in keyof A]: Show }) => Show<{ readonly [K in keyof A]: A[K] }> ``` Added in v2.10.0 ## tuple **Signature** ```ts export declare const tuple: ( ...shows: { [K in keyof A]: Show } ) => Show> ``` Added in v2.10.0 # zone of death ## ~~getStructShow~~ Use [`struct`](#struct) instead. **Signature** ```ts export declare const getStructShow: >>(shows: { [K in keyof O]: Show }) => Show ``` Added in v2.0.0 ## ~~getTupleShow~~ Use [`tuple`](#tuple) instead. **Signature** ```ts export declare const getTupleShow: []>( ...shows: T ) => Show<{ [K in keyof T]: T[K] extends Show ? A : never }> ``` Added in v2.0.0 ## ~~showBoolean~~ Use [`Show`](./boolean.ts.html#show) instead. **Signature** ```ts export declare const showBoolean: Show ``` Added in v2.0.0 ## ~~showNumber~~ Use [`Show`](./number.ts.html#show) instead. **Signature** ```ts export declare const showNumber: Show ``` Added in v2.0.0 ## ~~showString~~ Use [`Show`](./string.ts.html#show) instead. **Signature** ```ts export declare const showString: Show ``` Added in v2.0.0 ================================================ FILE: docs/modules/State.ts.md ================================================ --- title: State.ts nav_order: 98 parent: Modules --- ## State overview Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [constructors](#constructors) - [get](#get) - [gets](#gets) - [modify](#modify) - [of](#of) - [put](#put) - [instances](#instances) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [FromState](#fromstate) - [Functor](#functor) - [Monad](#monad) - [Pointed](#pointed) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [State (interface)](#state-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatten](#flatten) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apS](#aps) - [apSecond](#apsecond) - [bind](#bind) - [bindTo](#bindto) - [evaluate](#evaluate) - [execute](#execute) - [let](#let) - [zone of death](#zone-of-death) - [~~evalState~~](#evalstate) - [~~execState~~](#execstate) - [~~state~~](#state) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: State, f: (a: A) => State): State (f: (a: A) => State): (self: State) => State } ``` Added in v2.15.0 # constructors ## get Get the current state **Signature** ```ts export declare const get: () => State ``` Added in v2.0.0 ## gets Get a value which depends on the current state **Signature** ```ts export declare const gets: (f: (s: S) => A) => State ``` Added in v2.0.0 ## modify Modify the state by applying a function to the current state **Signature** ```ts export declare const modify: (f: (s: S) => S) => State ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => State ``` Added in v2.0.0 ## put Set the state **Signature** ```ts export declare const put: (s: S) => State ``` Added in v2.0.0 # instances ## Applicative **Signature** ```ts export declare const Applicative: Applicative2<'State'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply2<'State'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'State'> ``` Added in v2.10.0 ## FromState **Signature** ```ts export declare const FromState: FromState2<'State'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'State'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'State'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'State'> ``` Added in v2.10.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => State) => (ma: State) => State ``` Added in v2.0.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => State) => (ma: State) => State ``` Added in v2.0.0 # mapping ## flap **Signature** ```ts export declare const flap:
(a: A) => (fab: State B>) => State ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: State) => State ``` Added in v2.0.0 # model ## State (interface) **Signature** ```ts export interface State { (s: S): [A, S] } ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => State): (ma: State) => State (ma: State, f: (a: A) => State): State } ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: State>) => State ``` Added in v2.0.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly State[]) => State ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: (f: (a: A) => State) => (as: readonly A[]) => State ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => State ) => (as: readonly A[]) => State ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => State ) => (as: readonly A[]) => State ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => State ) => (as: ReadonlyNonEmptyArray) => State> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'State' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ap **Signature** ```ts export declare const ap: (fa: State) => (fab: State B>) => State ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: State) => (first: State) => State ``` Added in v2.0.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: State ) => (fa: State) => State ``` Added in v2.8.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: State) => (first: State) => State ``` Added in v2.0.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => State ) => (ma: State) => State ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: State) => State ``` Added in v2.8.0 ## evaluate Run a computation in the `State` monad, discarding the final state **Signature** ```ts export declare const evaluate: (s: S) => (ma: State) => A ``` Added in v2.8.0 ## execute Run a computation in the `State` monad discarding the result **Signature** ```ts export declare const execute: (s: S) => (ma: State) => S ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: State) => State ``` Added in v2.13.0 # zone of death ## ~~evalState~~ Use [`evaluate`](#evaluate) instead **Signature** ```ts export declare const evalState: (ma: State, s: S) => A ``` Added in v2.0.0 ## ~~execState~~ Use [`execute`](#execute) instead **Signature** ```ts export declare const execState: (ma: State, s: S) => S ``` Added in v2.0.0 ## ~~state~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `S.Functor` instead of `S.state` (where `S` is from `import S from 'fp-ts/State'`) **Signature** ```ts export declare const state: Monad2<'State'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/StateReaderTaskEither.ts.md ================================================ --- title: StateReaderTaskEither.ts nav_order: 99 parent: Modules --- ## StateReaderTaskEither overview Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapIO](#tapio) - [tapReader](#tapreader) - [tapTask](#taptask) - [constructors](#constructors) - [ask](#ask) - [asks](#asks) - [asksStateReaderTaskEither](#asksstatereadertaskeither) - [asksStateReaderTaskEitherW](#asksstatereadertaskeitherw) - [fromReaderTaskEither](#fromreadertaskeither) - [get](#get) - [gets](#gets) - [left](#left) - [leftIO](#leftio) - [leftReader](#leftreader) - [leftState](#leftstate) - [leftTask](#lefttask) - [modify](#modify) - [of](#of) - [put](#put) - [right](#right) - [rightIO](#rightio) - [rightReader](#rightreader) - [rightState](#rightstate) - [rightTask](#righttask) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromIOEither](#fromioeither) - [fromOption](#fromoption) - [fromReader](#fromreader) - [fromReaderEither](#fromreadereither) - [fromState](#fromstate) - [fromTask](#fromtask) - [fromTaskEither](#fromtaskeither) - [do notation](#do-notation) - [apSW](#apsw) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [mapLeft](#mapleft) - [filtering](#filtering) - [filterOrElse](#filterorelse) - [filterOrElseW](#filterorelsew) - [instances](#instances) - [Alt](#alt) - [Applicative](#applicative) - [Apply](#apply) - [Bifunctor](#bifunctor) - [Chain](#chain) - [FromEither](#fromeither) - [FromIO](#fromio) - [FromReader](#fromreader) - [FromState](#fromstate) - [FromTask](#fromtask) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadTask](#monadtask) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [legacy](#legacy) - [chain](#chain) - [chainEitherK](#chaineitherk) - [chainEitherKW](#chaineitherkw) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstEitherKW](#chainfirsteitherkw) - [chainFirstIOK](#chainfirstiok) - [chainFirstReaderK](#chainfirstreaderk) - [chainFirstReaderKW](#chainfirstreaderkw) - [chainFirstTaskK](#chainfirsttaskk) - [chainFirstW](#chainfirstw) - [chainIOEitherK](#chainioeitherk) - [chainIOEitherKW](#chainioeitherkw) - [chainIOK](#chainiok) - [chainOptionK](#chainoptionk) - [chainOptionKW](#chainoptionkw) - [chainReaderK](#chainreaderk) - [chainReaderKW](#chainreaderkw) - [chainReaderTaskEitherK](#chainreadertaskeitherk) - [chainReaderTaskEitherKW](#chainreadertaskeitherkw) - [chainStateK](#chainstatek) - [chainTaskEitherK](#chaintaskeitherk) - [chainTaskEitherKW](#chaintaskeitherkw) - [chainTaskK](#chaintaskk) - [chainW](#chainw) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromIOEitherK](#fromioeitherk) - [fromIOK](#fromiok) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [fromReaderK](#fromreaderk) - [fromReaderTaskEitherK](#fromreadertaskeitherk) - [fromStateK](#fromstatek) - [fromTaskEitherK](#fromtaskeitherk) - [fromTaskK](#fromtaskk) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [model](#model) - [StateReaderTaskEither (interface)](#statereadertaskeither-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapEither](#flatmapeither) - [flatMapIO](#flatmapio) - [flatMapIOEither](#flatmapioeither) - [flatMapOption](#flatmapoption) - [flatMapReader](#flatmapreader) - [flatMapReaderTaskEither](#flatmapreadertaskeither) - [flatMapState](#flatmapstate) - [flatMapTask](#flatmaptask) - [flatMapTaskEither](#flatmaptaskeither) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apS](#aps) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [evaluate](#evaluate) - [execute](#execute) - [let](#let) - [local](#local) - [throwError](#throwerror) - [zone of death](#zone-of-death) - [~~evalState~~](#evalstate) - [~~execState~~](#execstate) - [~~run~~](#run) - [~~stateReaderTaskEitherSeq~~](#statereadertaskeitherseq) - [~~stateReaderTaskEither~~](#statereadertaskeither) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { ( self: StateReaderTaskEither, f: (a: A) => StateReaderTaskEither ): StateReaderTaskEither (f: (a: A) => StateReaderTaskEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => E.Either): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => E.Either): StateReaderTaskEither< S, R1, E1 | E2, A > } ``` Added in v2.16.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => IO<_>): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => IO<_>): StateReaderTaskEither } ``` Added in v2.16.0 ## tapReader Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapReader: { (f: (a: A) => R.Reader): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => R.Reader): StateReaderTaskEither< S, R1 & R2, E, A > } ``` Added in v2.16.0 ## tapTask Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapTask: { (f: (a: A) => Task<_>): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Task<_>): StateReaderTaskEither } ``` Added in v2.16.0 # constructors ## ask Reads the current context. **Signature** ```ts export declare const ask: () => StateReaderTaskEither ``` Added in v2.11.0 ## asks Projects a value from the global context in a `ReaderEither`. **Signature** ```ts export declare const asks: (f: (r: R) => A) => StateReaderTaskEither ``` Added in v2.11.0 ## asksStateReaderTaskEither Effectfully accesses the environment. **Signature** ```ts export declare const asksStateReaderTaskEither: ( f: (r: R) => StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.11.0 ## asksStateReaderTaskEitherW Less strict version of [`asksStateReaderTaskEither`](#asksstatereadertaskeither). **Signature** ```ts export declare const asksStateReaderTaskEitherW: ( f: (r1: R1) => StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.11.0 ## fromReaderTaskEither **Signature** ```ts export declare const fromReaderTaskEither: ( fa: RTE.ReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.0.0 ## get Get the current state **Signature** ```ts export declare const get: () => StateReaderTaskEither ``` Added in v2.0.0 ## gets Get a value which depends on the current state **Signature** ```ts export declare const gets: (f: (s: S) => A) => StateReaderTaskEither ``` Added in v2.0.0 ## left **Signature** ```ts export declare const left: (e: E) => StateReaderTaskEither ``` Added in v2.0.0 ## leftIO **Signature** ```ts export declare function leftIO(me: IO): StateReaderTaskEither ``` Added in v2.0.0 ## leftReader **Signature** ```ts export declare function leftReader(me: Reader): StateReaderTaskEither ``` Added in v2.0.0 ## leftState **Signature** ```ts export declare const leftState: (me: State) => StateReaderTaskEither ``` Added in v2.0.0 ## leftTask **Signature** ```ts export declare function leftTask(me: Task): StateReaderTaskEither ``` Added in v2.0.0 ## modify Modify the state by applying a function to the current state **Signature** ```ts export declare const modify: (f: Endomorphism) => StateReaderTaskEither ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => StateReaderTaskEither ``` Added in v2.7.0 ## put Set the state **Signature** ```ts export declare const put: (s: S) => StateReaderTaskEither ``` Added in v2.0.0 ## right **Signature** ```ts export declare const right: (a: A) => StateReaderTaskEither ``` Added in v2.0.0 ## rightIO **Signature** ```ts export declare function rightIO(ma: IO
): StateReaderTaskEither ``` Added in v2.0.0 ## rightReader **Signature** ```ts export declare function rightReader(ma: Reader): StateReaderTaskEither ``` Added in v2.0.0 ## rightState **Signature** ```ts export declare const rightState: (ma: State) => StateReaderTaskEither ``` Added in v2.0.0 ## rightTask **Signature** ```ts export declare function rightTask(ma: Task): StateReaderTaskEither ``` Added in v2.0.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: E.Either) => StateReaderTaskEither ``` Added in v2.0.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO) => StateReaderTaskEither ``` Added in v2.7.0 ## fromIOEither **Signature** ```ts export declare const fromIOEither: (fa: IOEither) => StateReaderTaskEither ``` Added in v2.0.0 ## fromOption **Signature** ```ts export declare const fromOption: ( onNone: LazyArg ) => (fa: Option) => StateReaderTaskEither ``` Added in v2.0.0 ## fromReader **Signature** ```ts export declare const fromReader: (fa: R.Reader) => StateReaderTaskEither ``` Added in v2.11.0 ## fromReaderEither **Signature** ```ts export declare const fromReaderEither: (fa: ReaderEither) => StateReaderTaskEither ``` Added in v2.0.0 ## fromState **Signature** ```ts export declare const fromState: (fa: State) => StateReaderTaskEither ``` Added in v2.10.0 ## fromTask **Signature** ```ts export declare const fromTask: (fa: Task) => StateReaderTaskEither ``` Added in v2.7.0 ## fromTaskEither **Signature** ```ts export declare const fromTaskEither: (fa: TaskEither) => StateReaderTaskEither ``` Added in v2.0.0 # do notation ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: StateReaderTaskEither ) => ( fa: StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.8.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. **Signature** ```ts export declare const alt: ( that: LazyArg> ) => (fa: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.2 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the environment, the error and the return types will be merged. **Signature** ```ts export declare const altW: ( that: () => StateReaderTaskEither ) => (fa: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.9.0 ## mapLeft Map a function over the third type argument of a bifunctor. **Signature** ```ts export declare const mapLeft: ( f: (e: E) => G ) => (fa: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.2 # filtering ## filterOrElse **Signature** ```ts export declare const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( mb: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( ma: StateReaderTaskEither ) => StateReaderTaskEither } ``` Added in v2.4.4 ## filterOrElseW Less strict version of [`filterOrElse`](#filterorelse). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( ma: StateReaderTaskEither ) => StateReaderTaskEither } ``` Added in v2.9.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt4<'StateReaderTaskEither'> ``` Added in v2.7.0 ## Applicative **Signature** ```ts export declare const Applicative: Applicative4<'StateReaderTaskEither'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor4<'StateReaderTaskEither'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## FromReader **Signature** ```ts export declare const FromReader: FromReader4<'StateReaderTaskEither'> ``` Added in v2.11.0 ## FromState **Signature** ```ts export declare const FromState: FromState4<'StateReaderTaskEither'> ``` Added in v2.11.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor4<'StateReaderTaskEither'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## MonadTask **Signature** ```ts export declare const MonadTask: MonadTask4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow4<'StateReaderTaskEither'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed4<'StateReaderTaskEither'> ``` Added in v2.10.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.0.0 ## chainEitherK Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherK: ( f: (a: A) => E.Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.4.0 ## chainEitherKW Alias of `flatMapEither`. Less strict version of [`chainEitherK`](#chaineitherk). The `W` suffix (short for **W**idening) means that the error types will be merged. The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainEitherKW: ( f: (a: A) => E.Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.1 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.0.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.12.0 ## chainFirstEitherKW Alias of `tapEither`. Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.12.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: ( f: (a: A) => IO ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.10.0 ## chainFirstReaderK Alias of `tapReader`. **Signature** ```ts export declare const chainFirstReaderK: ( f: (a: A) => R.Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.11.0 ## chainFirstReaderKW Alias of `tapReader`. Less strict version of [`chainFirstReaderK`](#chainFirstReaderK). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.11.0 ## chainFirstTaskK Alias of `tapTask`. **Signature** ```ts export declare const chainFirstTaskK: ( f: (a: A) => Task ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.10.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.8.0 ## chainIOEitherK Alias of `flatMapIOEither`. **Signature** ```ts export declare const chainIOEitherK: ( f: (a: A) => IOEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.4.0 ## chainIOEitherKW Alias of `flatMapIOEither`. Less strict version of [`chainIOEitherK`](#chainioeitherk). **Signature** ```ts export declare const chainIOEitherKW: ( f: (a: A) => IOEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.1 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: ( f: (a: A) => IO ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.10.0 ## chainOptionK Use `flatMapOption`. **Signature** ```ts export declare const chainOptionK: ( onNone: LazyArg ) => ( f: (a: A) => Option ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.10.0 ## chainOptionKW Use `flatMapOption`. Less strict version of [`chainOptionK`](#chainoptionk). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const chainOptionKW: ( onNone: LazyArg ) => ( f: (a: A) => Option ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.13.2 ## chainReaderK Alias of `flatMapReader`. **Signature** ```ts export declare const chainReaderK: ( f: (a: A) => R.Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.11.0 ## chainReaderKW Alias of `flatMapReader`. Less strict version of [`chainReaderK`](#chainReaderK). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.11.0 ## chainReaderTaskEitherK Alias of `flatMapReaderTaskEither`. **Signature** ```ts export declare const chainReaderTaskEitherK: ( f: (a: A) => RTE.ReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.4.0 ## chainReaderTaskEitherKW Alias of `flatMapReaderTaskEither`. Less strict version of [`chainReaderTaskEitherK`](#chainreadertaskeitherk). **Signature** ```ts export declare const chainReaderTaskEitherKW: ( f: (a: A) => RTE.ReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.1 ## chainStateK Alias of `flatMapState`. **Signature** ```ts export declare const chainStateK: ( f: (a: A) => State ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.11.0 ## chainTaskEitherK Alias of `flatMapTaskEither`. **Signature** ```ts export declare const chainTaskEitherK: ( f: (a: A) => TaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.4.0 ## chainTaskEitherKW Alias of `flatMapTaskEither`. Less strict version of [`chainTaskEitherK`](#chaintaskeitherk). **Signature** ```ts export declare const chainTaskEitherKW: ( f: (a: A) => TaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.1 ## chainTaskK Alias of `flatMapTask`. **Signature** ```ts export declare const chainTaskK: ( f: (a: A) => Task ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.10.0 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => E.Either ) => (...a: A) => StateReaderTaskEither ``` Added in v2.4.0 ## fromIOEitherK **Signature** ```ts export declare const fromIOEitherK: ( f: (...a: A) => IOEither ) => (...a: A) => StateReaderTaskEither ``` Added in v2.4.0 ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => IO ) => (...a: A) => StateReaderTaskEither ``` Added in v2.10.0 ## fromOptionK **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => ( f: (...a: A) => Option ) => (...a: A) => StateReaderTaskEither ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): ( a: A ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( b: B ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => StateReaderTaskEither } ``` Added in v2.4.4 ## fromReaderK **Signature** ```ts export declare const fromReaderK: ( f: (...a: A) => R.Reader ) => (...a: A) => StateReaderTaskEither ``` Added in v2.11.0 ## fromReaderTaskEitherK **Signature** ```ts export declare const fromReaderTaskEitherK: ( f: (...a: A) => RTE.ReaderTaskEither ) => (...a: A) => StateReaderTaskEither ``` Added in v2.4.0 ## fromStateK **Signature** ```ts export declare const fromStateK: ( f: (...a: A) => State ) => (...a: A) => StateReaderTaskEither ``` Added in v2.11.0 ## fromTaskEitherK **Signature** ```ts export declare const fromTaskEitherK: ( f: (...a: A) => TaskEither ) => (...a: A) => StateReaderTaskEither ``` Added in v2.4.0 ## fromTaskK **Signature** ```ts export declare const fromTaskK: ( f: (...a: A) => Task ) => (...a: A) => StateReaderTaskEither ``` Added in v2.10.0 # mapping ## as Maps the `Right` value of this `StateReaderTaskEither` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, a: A): StateReaderTaskEither } ``` Added in v2.16.0 ## asUnit Maps the `Right` value of this `StateReaderTaskEither` to the void constant value. **Signature** ```ts export declare const asUnit: ( self: StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.16.0 ## bimap Map a pair of functions over the two last type arguments of the bifunctor. **Signature** ```ts export declare const bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.6.2 ## flap **Signature** ```ts export declare const flap: ( a: A ) => (fab: StateReaderTaskEither B>) => StateReaderTaskEither ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: ( f: (a: A) => B ) => (fa: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.0.0 # model ## StateReaderTaskEither (interface) **Signature** ```ts export interface StateReaderTaskEither { (s: S): ReaderTaskEither } ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => StateReaderTaskEither): ( ma: StateReaderTaskEither ) => StateReaderTaskEither ( ma: StateReaderTaskEither, f: (a: A) => StateReaderTaskEither ): StateReaderTaskEither } ``` Added in v2.14.0 ## flatMapEither **Signature** ```ts export declare const flatMapEither: { (f: (a: A) => E.Either): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => E.Either): StateReaderTaskEither< S, R, E1 | E2, B > } ``` Added in v2.16.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => IO): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => IO): StateReaderTaskEither } ``` Added in v2.16.0 ## flatMapIOEither **Signature** ```ts export declare const flatMapIOEither: { (f: (a: A) => IOEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => IOEither): StateReaderTaskEither< S, R, E1 | E2, B > } ``` Added in v2.16.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: StateReaderTaskEither ) => StateReaderTaskEither ( self: StateReaderTaskEither, f: (a: A) => Option, onNone: (a: A) => E2 ): StateReaderTaskEither } ``` Added in v2.16.0 ## flatMapReader **Signature** ```ts export declare const flatMapReader: { (f: (a: A) => R.Reader): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => R.Reader): StateReaderTaskEither< S, R1 & R2, E, B > } ``` Added in v2.16.0 ## flatMapReaderTaskEither **Signature** ```ts export declare const flatMapReaderTaskEither: { (f: (a: A) => RTE.ReaderTaskEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither ( self: StateReaderTaskEither, f: (a: A) => RTE.ReaderTaskEither ): StateReaderTaskEither } ``` Added in v2.16.0 ## flatMapState **Signature** ```ts export declare const flatMapState: { (f: (a: A) => State): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => State): StateReaderTaskEither } ``` Added in v2.16.0 ## flatMapTask **Signature** ```ts export declare const flatMapTask: { (f: (a: A) => Task): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Task): StateReaderTaskEither } ``` Added in v2.16.0 ## flatMapTaskEither **Signature** ```ts export declare const flatMapTaskEither: { (f: (a: A) => TaskEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => TaskEither): StateReaderTaskEither< S, R, E1 | E2, B > } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: ( mma: StateReaderTaskEither> ) => StateReaderTaskEither ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const flattenW: ( mma: StateReaderTaskEither> ) => StateReaderTaskEither ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: ( arr: readonly StateReaderTaskEither[] ) => StateReaderTaskEither ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => StateReaderTaskEither ) => (as: readonly A[]) => StateReaderTaskEither ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => StateReaderTaskEither ) => (as: readonly A[]) => StateReaderTaskEither ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => StateReaderTaskEither ) => (as: readonly A[]) => StateReaderTaskEither ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => StateReaderTaskEither ) => (as: ReadonlyNonEmptyArray) => StateReaderTaskEither> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'StateReaderTaskEither' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ap **Signature** ```ts export declare const ap: ( fa: StateReaderTaskEither ) => (fab: StateReaderTaskEither B>) => StateReaderTaskEither ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: ( second: StateReaderTaskEither ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apFirstW: ( second: StateReaderTaskEither ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.12.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: StateReaderTaskEither ) => ( fa: StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.8.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: ( second: StateReaderTaskEither ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apSecondW: ( second: StateReaderTaskEither ) => (first: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const apW: ( fa: StateReaderTaskEither ) => (fab: StateReaderTaskEither B>) => StateReaderTaskEither ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => StateReaderTaskEither ) => ( ma: StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: ( name: N ) => (fa: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => StateReaderTaskEither ) => ( fa: StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.8.0 ## evaluate Run a computation in the `StateReaderTaskEither` monad, discarding the final state **Signature** ```ts export declare const evaluate: ( s: S ) => (ma: StateReaderTaskEither) => RTE.ReaderTaskEither ``` Added in v2.8.0 ## execute Run a computation in the `StateReaderTaskEither` monad discarding the result **Signature** ```ts export declare const execute: ( s: S ) => (ma: StateReaderTaskEither) => RTE.ReaderTaskEither ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => ( fa: StateReaderTaskEither ) => StateReaderTaskEither ``` Added in v2.13.0 ## local Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s `contramap`). **Signature** ```ts export declare const local: ( f: (r2: R2) => R1 ) => (ma: StateReaderTaskEither) => StateReaderTaskEither ``` Added in v2.11.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => StateReaderTaskEither ``` Added in v2.7.0 # zone of death ## ~~evalState~~ Use [`evaluate`](#evaluate) instead **Signature** ```ts export declare const evalState: ( ma: StateReaderTaskEither, s: S ) => RTE.ReaderTaskEither ``` Added in v2.0.0 ## ~~execState~~ Use [`execute`](#execute) instead **Signature** ```ts export declare const execState: ( ma: StateReaderTaskEither, s: S ) => RTE.ReaderTaskEither ``` Added in v2.0.0 ## ~~run~~ **Signature** ```ts export declare function run(ma: StateReaderTaskEither, s: S, r: R): Promise> ``` Added in v2.0.0 ## ~~stateReaderTaskEitherSeq~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `SRTE.Functor` instead of `SRTE.stateReaderTaskEitherSeq` (where `SRTE` is from `import SRTE from 'fp-ts/StateReaderTaskEither'`) **Signature** ```ts export declare const stateReaderTaskEitherSeq: Monad4<'StateReaderTaskEither'> & Bifunctor4<'StateReaderTaskEither'> & Alt4<'StateReaderTaskEither'> & MonadTask4<'StateReaderTaskEither'> & MonadThrow4<'StateReaderTaskEither'> ``` Added in v2.0.0 ## ~~stateReaderTaskEither~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `SRTE.Functor` instead of `SRTE.stateReaderTaskEither` (where `SRTE` is from `import SRTE from 'fp-ts/StateReaderTaskEither'`) **Signature** ```ts export declare const stateReaderTaskEither: Monad4<'StateReaderTaskEither'> & Bifunctor4<'StateReaderTaskEither'> & Alt4<'StateReaderTaskEither'> & MonadTask4<'StateReaderTaskEither'> & MonadThrow4<'StateReaderTaskEither'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/StateT.ts.md ================================================ --- title: StateT.ts nav_order: 100 parent: Modules --- ## StateT overview The state monad transformer. It can be used to add state to other monads. The `of` function leaves the state unchanged, while `chain` uses the final state of the first computation as the initial state of the second. Added in v2.0.0 ---

Table of contents

- [model](#model) - [StateT (interface)](#statet-interface) - [StateT1 (interface)](#statet1-interface) - [StateT2 (interface)](#statet2-interface) - [StateT3 (interface)](#statet3-interface) - [utils](#utils) - [ap](#ap) - [chain](#chain) - [evaluate](#evaluate) - [execute](#execute) - [fromF](#fromf) - [fromState](#fromstate) - [map](#map) - [of](#of) - [zone of death](#zone-of-death) - [~~StateM1~~ (interface)](#statem1-interface) - [~~StateM2C~~ (interface)](#statem2c-interface) - [~~StateM2~~ (interface)](#statem2-interface) - [~~StateM3C~~ (interface)](#statem3c-interface) - [~~StateM3~~ (interface)](#statem3-interface) - [~~StateM~~ (interface)](#statem-interface) - [~~getStateM~~](#getstatem) --- # model ## StateT (interface) **Signature** ```ts export interface StateT { (s: S): HKT } ``` Added in v2.0.0 ## StateT1 (interface) **Signature** ```ts export interface StateT1 { (s: S): Kind } ``` Added in v2.0.0 ## StateT2 (interface) **Signature** ```ts export interface StateT2 { (s: S): Kind2 } ``` Added in v2.0.0 ## StateT3 (interface) **Signature** ```ts export interface StateT3 { (s: S): Kind3 } ``` Added in v2.0.0 # utils ## ap **Signature** ```ts export declare function ap( M: Chain3 ): (fa: StateT3) => (fab: StateT3 B>) => StateT3 export declare function ap( M: Chain3C ): (fa: StateT3) => (fab: StateT3 B>) => StateT3 export declare function ap( M: Chain2 ): (fa: StateT2) => (fab: StateT2 B>) => StateT2 export declare function ap( M: Chain2C ): (fa: StateT2) => (fab: StateT2 B>) => StateT2 export declare function ap( M: Chain1 ): (fa: StateT1) => (fab: StateT1 B>) => StateT1 export declare function ap( M: Chain ): (fa: StateT) => (fab: StateT B>) => StateT ``` Added in v2.10.0 ## chain **Signature** ```ts export declare function chain( M: Chain3 ): (f: (a: A) => StateT3) => (ma: StateT3) => StateT3 export declare function chain( M: Chain3C ): (f: (a: A) => StateT3) => (ma: StateT3) => StateT3 export declare function chain( M: Chain2 ): (f: (a: A) => StateT2) => (ma: StateT2) => StateT2 export declare function chain( M: Chain2C ): (f: (a: A) => StateT2) => (ma: StateT2) => StateT2 export declare function chain( M: Chain1 ): (f: (a: A) => StateT1) => (ma: StateT1) => StateT1 export declare function chain( M: Chain ): (f: (a: A) => StateT) => (ma: StateT) => StateT ``` Added in v2.10.0 ## evaluate **Signature** ```ts export declare function evaluate( F: Functor3 ): (s: S) => (ma: StateT3) => Kind3 export declare function evaluate( F: Functor3C ): (s: S) => (ma: StateT3) => Kind3 export declare function evaluate( F: Functor2 ): (s: S) => (ma: StateT2) => Kind2 export declare function evaluate( F: Functor2C ): (s: S) =>
(ma: StateT2) => Kind2 export declare function evaluate(F: Functor1): (s: S) => (ma: StateT1) => Kind export declare function evaluate(F: Functor): (s: S) => (ma: StateT) => HKT ``` Added in v2.10.0 ## execute **Signature** ```ts export declare function execute( F: Functor3 ): (s: S) => (ma: StateT3) => Kind3 export declare function execute( F: Functor3C ): (s: S) => (ma: StateT3) => Kind3 export declare function execute( F: Functor2 ): (s: S) => (ma: StateT2) => Kind2 export declare function execute( F: Functor2C ): (s: S) => (ma: StateT2) => Kind2 export declare function execute(F: Functor1): (s: S) => (ma: StateT1) => Kind export declare function execute(F: Functor): (s: S) => (ma: StateT) => HKT ``` Added in v2.10.0 ## fromF **Signature** ```ts export declare function fromF( F: Functor3 ): (ma: Kind3) => StateT3 export declare function fromF( F: Functor3C ): (ma: Kind3) => StateT3 export declare function fromF(F: Functor2): (ma: Kind2) => StateT2 export declare function fromF(F: Functor2C): (ma: Kind2) => StateT2 export declare function fromF(F: Functor1): (ma: Kind) => StateT1 export declare function fromF(F: Functor): (ma: HKT) => StateT ``` Added in v2.10.0 ## fromState **Signature** ```ts export declare function fromState( F: Pointed3 ): (sa: State) => StateT3 export declare function fromState( F: Pointed3C ): (sa: State) => StateT3 export declare function fromState(F: Pointed2): (sa: State) => StateT2 export declare function fromState( F: Pointed2C ): (sa: State) => StateT2 export declare function fromState(F: Pointed1): (sa: State) => StateT1 export declare function fromState(F: Pointed): (sa: State) => StateT ``` Added in v2.10.0 ## map **Signature** ```ts export declare function map( F: Functor3 ): (f: (a: A) => B) => (fa: StateT3) => StateT3 export declare function map( F: Functor3C ): (f: (a: A) => B) => (fa: StateT3) => StateT3 export declare function map( F: Functor2 ): (f: (a: A) => B) => (fa: StateT2) => StateT2 export declare function map( F: Functor2C ): (f: (a: A) => B) => (fa: StateT2) => StateT2 export declare function map( F: Functor1 ): (f: (a: A) => B) => (fa: StateT1) => StateT1 export declare function map(F: Functor): (f: (a: A) => B) => (fa: StateT) => StateT ``` Added in v2.10.0 ## of **Signature** ```ts export declare function of(F: Pointed3): (a: A) => StateT3 export declare function of(F: Pointed3C): (a: A) => StateT3 export declare function of(F: Pointed2): (a: A) => StateT2 export declare function of(F: Pointed2C): (a: A) => StateT2 export declare function of(F: Pointed1): (a: A) => StateT1 export declare function of(F: Pointed): (a: A) => StateT ``` Added in v2.10.0 # zone of death ## ~~StateM1~~ (interface) **Signature** ```ts export interface StateM1 { readonly map: (fa: StateT1, f: (a: A) => B) => StateT1 readonly of: (a: A) => StateT1 readonly ap: (fab: StateT1 B>, fa: StateT1) => StateT1 readonly chain: (fa: StateT1, f: (a: A) => StateT1) => StateT1 readonly get: () => StateT1 readonly put: (s: S) => StateT1 readonly modify: (f: (s: S) => S) => StateT1 readonly gets: (f: (s: S) => A) => StateT1 readonly fromState: (fa: State) => StateT1 readonly fromM: (ma: Kind) => StateT1 readonly evalState: (ma: StateT1, s: S) => Kind readonly execState: (ma: StateT1, s: S) => Kind } ``` Added in v2.0.0 ## ~~StateM2C~~ (interface) **Signature** ```ts export interface StateM2C { readonly map: (fa: StateT2, f: (a: A) => B) => StateT2 readonly of: (a: A) => StateT2 readonly ap: (fab: StateT2 B>, fa: StateT2) => StateT2 readonly chain: (fa: StateT2, f: (a: A) => StateT2) => StateT2 readonly get: () => StateT2 readonly put: (s: S) => StateT2 readonly modify: (f: (s: S) => S) => StateT2 readonly gets: (f: (s: S) => A) => StateT2 readonly fromState: (fa: State) => StateT2 readonly fromM: (ma: Kind2) => StateT2 readonly evalState: (ma: StateT2, s: S) => Kind2 readonly execState: (ma: StateT2, s: S) => Kind2 } ``` Added in v2.5.4 ## ~~StateM2~~ (interface) **Signature** ```ts export interface StateM2 { readonly map: (fa: StateT2, f: (a: A) => B) => StateT2 readonly of: (a: A) => StateT2 readonly ap: (fab: StateT2 B>, fa: StateT2) => StateT2 readonly chain: (fa: StateT2, f: (a: A) => StateT2) => StateT2 readonly get: () => StateT2 readonly put: (s: S) => StateT2 readonly modify: (f: (s: S) => S) => StateT2 readonly gets: (f: (s: S) => A) => StateT2 readonly fromState: (fa: State) => StateT2 readonly fromM: (ma: Kind2) => StateT2 readonly evalState: (ma: StateT2, s: S) => Kind2 readonly execState: (ma: StateT2, s: S) => Kind2 } ``` Added in v2.0.0 ## ~~StateM3C~~ (interface) **Signature** ```ts export interface StateM3C { readonly map: (fa: StateT3, f: (a: A) => B) => StateT3 readonly of: (a: A) => StateT3 readonly ap: (fab: StateT3 B>, fa: StateT3) => StateT3 readonly chain: ( fa: StateT3, f: (a: A) => StateT3 ) => StateT3 readonly get: () => StateT3 readonly put: (s: S) => StateT3 readonly modify: (f: (s: S) => S) => StateT3 readonly gets: (f: (s: S) => A) => StateT3 readonly fromState: (fa: State) => StateT3 readonly fromM: (ma: Kind3) => StateT3 readonly evalState: (ma: StateT3, s: S) => Kind3 readonly execState: (ma: StateT3, s: S) => Kind3 } ``` Added in v2.5.4 ## ~~StateM3~~ (interface) **Signature** ```ts export interface StateM3 { readonly map: (fa: StateT3, f: (a: A) => B) => StateT3 readonly of: (a: A) => StateT3 readonly ap: ( fab: StateT3 B>, fa: StateT3 ) => StateT3 readonly chain: ( fa: StateT3, f: (a: A) => StateT3 ) => StateT3 readonly get: () => StateT3 readonly put: (s: S) => StateT3 readonly modify: (f: (s: S) => S) => StateT3 readonly gets: (f: (s: S) => A) => StateT3 readonly fromState: (fa: State) => StateT3 readonly fromM: (ma: Kind3) => StateT3 readonly evalState: (ma: StateT3, s: S) => Kind3 readonly execState: (ma: StateT3, s: S) => Kind3 } ``` Added in v2.0.0 ## ~~StateM~~ (interface) **Signature** ```ts export interface StateM { readonly map: (fa: StateT, f: (a: A) => B) => StateT readonly of: (a: A) => StateT readonly ap: (fab: StateT B>, fa: StateT) => StateT readonly chain: (fa: StateT, f: (a: A) => StateT) => StateT readonly get: () => StateT readonly put: (s: S) => StateT readonly modify: (f: (s: S) => S) => StateT readonly gets: (f: (s: S) => A) => StateT readonly fromState: (fa: State) => StateT readonly fromM: (ma: HKT) => StateT readonly evalState: (ma: StateT, s: S) => HKT readonly execState: (ma: StateT, s: S) => HKT } ``` Added in v2.0.0 ## ~~getStateM~~ **Signature** ```ts export declare function getStateM(M: Monad3): StateM3 export declare function getStateM(M: Monad3C): StateM3C export declare function getStateM(M: Monad2): StateM2 export declare function getStateM(M: Monad2C): StateM2C export declare function getStateM(M: Monad1): StateM1 export declare function getStateM(M: Monad): StateM ``` Added in v2.0.0 ================================================ FILE: docs/modules/Store.ts.md ================================================ --- title: Store.ts nav_order: 101 parent: Modules --- ## Store overview Added in v2.0.0 ---

Table of contents

- [Extract](#extract) - [extract](#extract) - [instances](#instances) - [Comonad](#comonad) - [Functor](#functor) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [Store (interface)](#store-interface) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [duplicate](#duplicate) - [experiment](#experiment) - [extend](#extend) - [peeks](#peeks) - [seek](#seek) - [seeks](#seeks) - [zone of death](#zone-of-death) - [~~store~~](#store) --- # Extract ## extract **Signature** ```ts export declare const extract: (wa: Store) => A ``` Added in v2.6.2 # instances ## Comonad **Signature** ```ts export declare const Comonad: Comonad2<'Store'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Store'> ``` Added in v2.7.0 # mapping ## flap **Signature** ```ts export declare const flap:
(a: A) => (fab: Store B>) => Store ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Store) => Store ``` Added in v2.0.0 # model ## Store (interface) **Signature** ```ts export interface Store { readonly peek: (s: S) => A readonly pos: S } ``` Added in v2.0.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Store' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## duplicate **Signature** ```ts export declare const duplicate: (wa: Store) => Store> ``` Added in v2.0.0 ## experiment Extract a collection of values from positions which depend on the current position **Signature** ```ts export declare function experiment( F: Functor3 ): (f: (s: S) => Kind3) => (wa: Store) => Kind3 export declare function experiment( F: Functor3C ): (f: (s: S) => Kind3) => (wa: Store) => Kind3 export declare function experiment( F: Functor2 ): (f: (s: S) => Kind2) => (wa: Store) => Kind2 export declare function experiment( F: Functor2C ): (f: (s: S) => Kind2) => (wa: Store) => Kind2 export declare function experiment( F: Functor1 ): (f: (s: S) => Kind) => (wa: Store) => Kind export declare function experiment( F: FunctorHKT ): (f: (s: S) => HKT) => (wa: Store) => HKT ``` Added in v2.0.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: Store) => B) => (wa: Store) => Store ``` Added in v2.0.0 ## peeks Extract a value from a position which depends on the current position **Signature** ```ts export declare function peeks(f: Endomorphism): (wa: Store) => A ``` Added in v2.0.0 ## seek Reposition the focus at the specified position **Signature** ```ts export declare function seek(s: S): (wa: Store) => Store ``` Added in v2.0.0 ## seeks Reposition the focus at the specified position, which depends on the current position **Signature** ```ts export declare function seeks(f: Endomorphism): (wa: Store) => Store ``` Added in v2.0.0 # zone of death ## ~~store~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Comonad` instance, pass `S.Comonad` instead of `S.store` (where `S` is from `import S from 'fp-ts/Store'`) **Signature** ```ts export declare const store: Comonad2<'Store'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Strong.ts.md ================================================ --- title: Strong.ts nav_order: 103 parent: Modules --- ## Strong overview The `Strong` class extends `Profunctor` with combinators for working with product types. `first` and `second` lift values in a `Profunctor` to act on the first and second components of a tuple, respectively. Another way to think about Strong is to piggyback on the intuition of inputs and outputs. Rewriting the type signature in this light then yields: ```purescript first :: forall input output a. p input output -> p (Tuple input a) (Tuple output a) second :: forall input output a. p input output -> p (Tuple a input) (Tuple a output) ``` If we specialize the profunctor p to the function arrow, we get the following type signatures, which may look a bit more familiar: ```purescript first :: forall input output a. (input -> output) -> (Tuple input a) -> (Tuple output a) second :: forall input output a. (input -> output) -> (Tuple a input) -> (Tuple a output) ``` So, when the `profunctor` is `Function` application, `first` essentially applies your function to the first element of a tuple, and `second` applies it to the second element (same as `map` would do). Adapted from https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Strong.purs Added in v2.0.0 ---

Table of contents

- [model](#model) - [Strong (interface)](#strong-interface) - [Strong2 (interface)](#strong2-interface) - [Strong3 (interface)](#strong3-interface) - [Strong4 (interface)](#strong4-interface) - [utils](#utils) - [fanOut](#fanout) - [split](#split) - [zone of death](#zone-of-death) - [~~fanout~~](#fanout) - [~~splitStrong~~](#splitstrong) --- # model ## Strong (interface) **Signature** ```ts export interface Strong extends Profunctor { readonly first: (pab: HKT2) => HKT2 readonly second: (pab: HKT2) => HKT2 } ``` Added in v2.0.0 ## Strong2 (interface) **Signature** ```ts export interface Strong2 extends Profunctor2 { readonly first: (pab: Kind2) => Kind2 readonly second: (pab: Kind2) => Kind2 } ``` Added in v2.0.0 ## Strong3 (interface) **Signature** ```ts export interface Strong3 extends Profunctor3 { readonly first: (pab: Kind3) => Kind3 readonly second: (pab: Kind3) => Kind3 } ``` Added in v2.0.0 ## Strong4 (interface) **Signature** ```ts export interface Strong4 extends Profunctor4 { readonly first: (pab: Kind4) => Kind4 readonly second: (pab: Kind4) => Kind4 } ``` Added in v2.0.0 # utils ## fanOut Compose a value which introduces a tuple from two values, each introducing one side of the tuple. This combinator is useful when assembling values from smaller components, because it provides a way to support two different types of output. Specializing `fanOut` to function application would look like this: ```purescript fanOut :: forall a b c. (a -> b) -> (a -> c) -> (a -> (Tuple b c)) ``` We take two functions, `f` and `g`, with the same parameter type and we transform them into a single function which takes one parameter and returns a tuple of the results of running `f` and `g` on the parameter, respectively. This allows us to run two parallel computations on the same input and return both results in a tuple. **Signature** ```ts export declare function fanOut( S: Strong4, C: Category4 ): (pab: Kind4, pac: Kind4) => Kind4 export declare function fanOut( S: Strong3, C: Category3 ): (pab: Kind3, pac: Kind3) => Kind3 export declare function fanOut( S: Strong2, C: Category2 ): (pab: Kind2, pac: Kind2) => Kind2 export declare function fanOut( S: Strong, C: Category ): (pab: HKT2, pac: HKT2) => HKT2 ``` Added in v2.10.0 ## split Compose a value acting on a tuple from two values, each acting on one of the components of the tuple. Specializing `split` to function application would look like this: ```purescript split :: forall a b c d. (a -> b) -> (c -> d) -> (Tuple a c) -> (Tuple b d) ``` We take two functions, `f` and `g`, and we transform them into a single function which takes a tuple and maps `f` over the first element and `g` over the second. Just like `bi-map` would do for the `bi-functor` instance of tuple. **Signature** ```ts export declare function split( S: Strong4, C: Category4 ): (pab: Kind4, pcd: Kind4) => Kind4 export declare function split( S: Strong3, C: Category3 ): (pab: Kind3, pcd: Kind3) => Kind3 export declare function split( S: Strong2, C: Category2 ): (pab: Kind2, pcd: Kind2) => Kind2 export declare function split( S: Strong, C: Category ): (pab: HKT2, pcd: HKT2) => HKT2 ``` Added in v2.10.0 # zone of death ## ~~fanout~~ Use [`fanOut`](#fanout) instead. **Signature** ```ts export declare function fanout( F: Category4 & Strong4 ): (pab: Kind4, pac: Kind4) => Kind4 export declare function fanout( F: Category3 & Strong3 ): (pab: Kind3, pac: Kind3) => Kind3 export declare function fanout( F: Category2 & Strong2 ): (pab: Kind2, pac: Kind2) => Kind2 export declare function fanout( F: Category & Strong ): (pab: HKT2, pac: HKT2) => HKT2 ``` Added in v2.0.0 ## ~~splitStrong~~ Use [`split`](#split) instead. **Signature** ```ts export declare function splitStrong( F: Category4 & Strong4 ): (pab: Kind4, pcd: Kind4) => Kind4 export declare function splitStrong( F: Category3 & Strong3 ): (pab: Kind3, pcd: Kind3) => Kind3 export declare function splitStrong( F: Category2 & Strong2 ): (pab: Kind2, pcd: Kind2) => Kind2 export declare function splitStrong( F: Category & Strong ): (pab: HKT2, pcd: HKT2) => HKT2 ``` Added in v2.0.0 ================================================ FILE: docs/modules/Task.ts.md ================================================ --- title: Task.ts nav_order: 105 parent: Modules --- ## Task overview ```ts interface Task
{ (): Promise } ``` `Task` represents an asynchronous computation that yields a value of type `A` and **never fails**. If you want to represent an asynchronous computation that may fail, please see `TaskEither`. Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapIO](#tapio) - [constructors](#constructors) - [of](#of) - [conversions](#conversions) - [fromIO](#fromio) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [let](#let) - [instances](#instances) - [ApplicativePar](#applicativepar) - [ApplicativeSeq](#applicativeseq) - [ApplyPar](#applypar) - [ApplySeq](#applyseq) - [Chain](#chain) - [FromIO](#fromio) - [FromTask](#fromtask) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadTask](#monadtask) - [Pointed](#pointed) - [getRaceMonoid](#getracemonoid) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstIOK](#chainfirstiok) - [chainIOK](#chainiok) - [lifting](#lifting) - [fromIOK](#fromiok) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [Task (interface)](#task-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapIO](#flatmapio) - [flatten](#flatten) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [sequenceSeqArray](#sequenceseqarray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [traverseSeqArray](#traverseseqarray) - [traverseSeqArrayWithIndex](#traverseseqarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [delay](#delay) - [never](#never) - [zone of death](#zone-of-death) - [~~fromTask~~](#fromtask) - [~~getMonoid~~](#getmonoid) - [~~getSemigroup~~](#getsemigroup) - [~~taskSeq~~](#taskseq) - [~~task~~](#task) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: Task
, f: (a: A) => Task<_>): Task (f: (a: A) => Task<_>): (self: Task) => Task } ``` Added in v2.15.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => IO<_>): (self: Task) => Task (self: Task, f: (a: A) => IO<_>): Task } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as T from 'fp-ts/Task' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effect = pipe( T.of('fp-ts'), T.tapIO((value) => Console.log(`Hello, ${value}`)) ) async function test() { assert.deepStrictEqual(await effect(), 'fp-ts') } test() ``` Added in v2.16.0 # constructors ## of **Signature** ```ts export declare const of: (a: A) => Task ``` Added in v2.0.0 # conversions ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO) => Task ``` Added in v2.0.0 # do notation ## Do **Signature** ```ts export declare const Do: Task<{}> ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: Task ) => (fa: Task) => Task<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => Task ) => (ma: Task) => Task<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: Task) => Task<{ readonly [K in N]: A }> ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: Task) => Task<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # instances ## ApplicativePar Runs computations in parallel. **Signature** ```ts export declare const ApplicativePar: Applicative1<'Task'> ``` Added in v2.7.0 ## ApplicativeSeq Runs computations sequentially. **Signature** ```ts export declare const ApplicativeSeq: Applicative1<'Task'> ``` Added in v2.7.0 ## ApplyPar Runs computations in parallel. **Signature** ```ts export declare const ApplyPar: Apply1<'Task'> ``` Added in v2.10.0 ## ApplySeq Runs computations sequentially. **Signature** ```ts export declare const ApplySeq: Apply1<'Task'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain1<'Task'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO1<'Task'> ``` Added in v2.10.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask1<'Task'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'Task'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'Task'> ``` Added in v2.10.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO1<'Task'> ``` Added in v2.10.0 ## MonadTask **Signature** ```ts export declare const MonadTask: MonadTask1<'Task'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'Task'> ``` Added in v2.10.0 ## getRaceMonoid Monoid returning the first completed task. Note: uses `Promise.race` internally. **Signature** ```ts export declare function getRaceMonoid(): Monoid> ``` **Example** ```ts import * as T from 'fp-ts/Task' async function test() { const S = T.getRaceMonoid() const fa = T.delay(20)(T.of('a')) const fb = T.delay(10)(T.of('b')) assert.deepStrictEqual(await S.concat(fa, fb)(), 'b') } test() ``` Added in v2.0.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => Task) => (ma: Task) => Task ``` Added in v2.0.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => Task) => (first: Task) => Task ``` Added in v2.0.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => IO) => (first: Task) => Task ``` Added in v2.10.0 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => IO) => (first: Task) => Task ``` Added in v2.4.0 # lifting ## fromIOK **Signature** ```ts export declare const fromIOK: (f: (...a: A) => IO) => (...a: A) => Task ``` Added in v2.4.0 # mapping ## as Maps the value to the specified constant value. **Signature** ```ts export declare const as: { (a: A): <_>(self: Task<_>) => Task; <_, A>(self: Task<_>, a: A): Task } ``` Added in v2.16.0 ## asUnit Maps the value to the void constant value. **Signature** ```ts export declare const asUnit: <_>(self: Task<_>) => Task ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Task<(a: A) => B>) => Task ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Task) => Task ``` Added in v2.0.0 # model ## Task (interface) **Signature** ```ts export interface Task { (): Promise } ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => Task): (ma: Task) => Task (ma: Task, f: (a: A) => Task): Task } ``` Added in v2.14.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => IO): (self: Task) => Task (self: Task, f: (a: A) => IO): Task } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: Task>) => Task ``` Added in v2.0.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly Task[]) => Task ``` Added in v2.9.0 ## sequenceSeqArray Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. **Signature** ```ts export declare const sequenceSeqArray: (arr: readonly Task[]) => Task ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: (f: (a: A) => Task) => (as: readonly A[]) => Task ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => Task ) => (as: readonly A[]) => Task ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => Task ) => (as: readonly A[]) => Task ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( f: (index: number, a: A) => Task ) => (as: readonly A[]) => Task ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => Task ) => (as: ReadonlyNonEmptyArray) => Task> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( f: (index: number, a: A) => Task ) => (as: ReadonlyNonEmptyArray) => Task> ``` Added in v2.11.0 ## traverseSeqArray Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArray: (f: (a: A) => Task) => (as: readonly A[]) => Task ``` Added in v2.9.0 ## traverseSeqArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => Task ) => (as: readonly A[]) => Task ``` Added in v2.9.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Task' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: Task ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: Task) => (fab: Task<(a: A) => B>) => Task ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: Task) => (first: Task) => Task ``` Added in v2.0.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: Task) => (first: Task) => Task ``` Added in v2.0.0 ## delay Creates a task that will complete after a time delay **Signature** ```ts export declare function delay(millis: number): (ma: Task) => Task ``` **Example** ```ts import { sequenceT } from 'fp-ts/Apply' import * as T from 'fp-ts/Task' import { takeRight } from 'fp-ts/Array' async function test() { const log: Array = [] const append = (message: string): T.Task => T.fromIO(() => { log.push(message) }) const fa = append('a') const fb = T.delay(20)(append('b')) const fc = T.delay(10)(append('c')) const fd = append('d') await sequenceT(T.ApplyPar)(fa, fb, fc, fd)() assert.deepStrictEqual(takeRight(2)(log), ['c', 'b']) } test() ``` Added in v2.0.0 ## never A `Task` that never completes. **Signature** ```ts export declare const never: Task ``` Added in v2.0.0 # zone of death ## ~~fromTask~~ **Signature** ```ts export declare const fromTask: (fa: Task) => Task ``` Added in v2.7.0 ## ~~getMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. Lift a monoid into 'Task', the inner values are concatenated using the provided `Monoid`. **Signature** ```ts export declare const getMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~taskSeq~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.taskSeq` (where `T` is from `import T from 'fp-ts/Task'`) **Signature** ```ts export declare const taskSeq: Monad1<'Task'> & MonadTask1<'Task'> ``` Added in v2.0.0 ## ~~task~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.task` (where `T` is from `import T from 'fp-ts/Task'`) **Signature** ```ts export declare const task: Monad1<'Task'> & MonadTask1<'Task'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/TaskEither.ts.md ================================================ --- title: TaskEither.ts nav_order: 106 parent: Modules --- ## TaskEither overview ```ts interface TaskEither extends Task> {} ``` `TaskEither` represents an asynchronous computation that either yields a value of type `A` or fails yielding an error of type `E`. If you want to represent an asynchronous computation that never fails, please see `Task`. Added in v2.0.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapIO](#tapio) - [tapTask](#taptask) - [constructors](#constructors) - [left](#left) - [leftIO](#leftio) - [leftTask](#lefttask) - [of](#of) - [right](#right) - [rightIO](#rightio) - [rightTask](#righttask) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromIOEither](#fromioeither) - [fromNullable](#fromnullable) - [fromOption](#fromoption) - [fromTask](#fromtask) - [fromTaskOption](#fromtaskoption) - [toUnion](#tounion) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [apSW](#apsw) - [bind](#bind) - [bindTo](#bindto) - [bindW](#bindw) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getAltTaskValidation](#getalttaskvalidation) - [getApplicativeTaskValidation](#getapplicativetaskvalidation) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [mapBoth](#mapboth) - [mapError](#maperror) - [orElse](#orelse) - [orElseFirstIOK](#orelsefirstiok) - [orElseFirstTaskK](#orelsefirsttaskk) - [orElseW](#orelsew) - [orLeft](#orleft) - [tapError](#taperror) - [filtering](#filtering) - [filterOrElse](#filterorelse) - [filterOrElseW](#filterorelsew) - [getCompactable](#getcompactable) - [getFilterable](#getfilterable) - [instances](#instances) - [Alt](#alt) - [ApplicativePar](#applicativepar) - [ApplicativeSeq](#applicativeseq) - [ApplyPar](#applypar) - [ApplySeq](#applyseq) - [Bifunctor](#bifunctor) - [Chain](#chain) - [FromEither](#fromeither) - [FromIO](#fromio) - [FromTask](#fromtask) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadTask](#monadtask) - [MonadThrow](#monadthrow) - [Pointed](#pointed) - [interop](#interop) - [taskify](#taskify) - [tryCatch](#trycatch) - [tryCatchK](#trycatchk) - [legacy](#legacy) - [bimap](#bimap) - [chain](#chain) - [chainEitherK](#chaineitherk) - [chainEitherKW](#chaineitherkw) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstEitherKW](#chainfirsteitherkw) - [chainFirstIOK](#chainfirstiok) - [chainFirstTaskK](#chainfirsttaskk) - [chainFirstW](#chainfirstw) - [chainIOEitherK](#chainioeitherk) - [chainIOEitherKW](#chainioeitherkw) - [chainIOK](#chainiok) - [chainNullableK](#chainnullablek) - [chainOptionK](#chainoptionk) - [chainOptionKW](#chainoptionkw) - [chainTaskK](#chaintaskk) - [chainTaskOptionK](#chaintaskoptionk) - [chainTaskOptionKW](#chaintaskoptionkw) - [chainW](#chainw) - [fromNullableK](#fromnullablek) - [fromOptionK](#fromoptionk) - [mapLeft](#mapleft) - [orElseFirst](#orelsefirst) - [orElseFirstW](#orelsefirstw) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromIOEitherK](#fromioeitherk) - [fromIOK](#fromiok) - [fromPredicate](#frompredicate) - [fromTaskK](#fromtaskk) - [fromTaskOptionK](#fromtaskoptionk) - [liftNullable](#liftnullable) - [liftOption](#liftoption) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [TaskEither (interface)](#taskeither-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatMapEither](#flatmapeither) - [flatMapIO](#flatmapio) - [flatMapIOEither](#flatmapioeither) - [flatMapNullable](#flatmapnullable) - [flatMapOption](#flatmapoption) - [flatMapTask](#flatmaptask) - [flatMapTaskOption](#flatmaptaskoption) - [flatten](#flatten) - [flattenW](#flattenw) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [sequenceSeqArray](#sequenceseqarray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [traverseSeqArray](#traverseseqarray) - [traverseSeqArrayWithIndex](#traverseseqarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apFirstW](#apfirstw) - [apSecond](#apsecond) - [apSecondW](#apsecondw) - [apW](#apw) - [bracket](#bracket) - [bracketW](#bracketw) - [swap](#swap) - [throwError](#throwerror) - [zone of death](#zone-of-death) - [~~getApplyMonoid~~](#getapplymonoid) - [~~getApplySemigroup~~](#getapplysemigroup) - [~~getSemigroup~~](#getsemigroup) - [~~getTaskValidation~~](#gettaskvalidation) - [~~taskEitherSeq~~](#taskeitherseq) - [~~taskEither~~](#taskeither) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: TaskEither, f: (a: A) => TaskEither): TaskEither (f: (a: A) => TaskEither): (self: TaskEither) => TaskEither } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => E.Either): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => E.Either): TaskEither } ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as TE from 'fp-ts/TaskEither' const checkString = (value: string) => pipe( TE.of(value), TE.tapEither(() => (value.length > 0 ? E.right('ok') : E.left('error'))) ) async function test() { assert.deepStrictEqual(await checkString('')(), E.left('error')) assert.deepStrictEqual(await checkString('fp-ts')(), E.right('fp-ts')) } test() ``` Added in v2.16.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => IO<_>): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => IO<_>): TaskEither } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as TE from 'fp-ts/TaskEither' import * as E from 'fp-ts/Either' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effectA = TE.tapIO(TE.of(1), (value) => Console.log(`Hello, ${value}`)) // No output to the stdout const effectB = pipe( TE.left('error'), TE.tapIO((value) => Console.log(`Hello, ${value}`)) ) async function test() { assert.deepStrictEqual(await effectA(), E.of(1)) assert.deepStrictEqual(await effectB(), E.left('error')) } test() ``` Added in v2.16.0 ## tapTask Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapTask: { (f: (a: A) => T.Task<_>): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => T.Task<_>): TaskEither } ``` **Example** ```ts import * as TE from 'fp-ts/TaskEither' import * as T from 'fp-ts/Task' import * as E from 'fp-ts/Either' const effect = TE.tapIO(TE.of(1), (value) => T.of(value + 1)) async function test() { assert.deepStrictEqual(await effect(), E.of(1)) } test() ``` Added in v2.16.0 # constructors ## left **Signature** ```ts export declare const left: (e: E) => TaskEither ``` Added in v2.0.0 ## leftIO **Signature** ```ts export declare const leftIO: (me: IO) => TaskEither ``` Added in v2.0.0 ## leftTask **Signature** ```ts export declare const leftTask: (me: T.Task) => TaskEither ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => TaskEither ``` Added in v2.0.0 ## right **Signature** ```ts export declare const right: (a: A) => TaskEither ``` Added in v2.0.0 ## rightIO **Signature** ```ts export declare const rightIO: (ma: IO
) => TaskEither ``` Added in v2.0.0 ## rightTask **Signature** ```ts export declare const rightTask: (ma: T.Task) => TaskEither ``` Added in v2.0.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: E.Either) => TaskEither ``` Added in v2.0.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO) => TaskEither ``` Added in v2.7.0 ## fromIOEither **Signature** ```ts export declare const fromIOEither: (fa: IOEither) => TaskEither ``` Added in v2.0.0 ## fromNullable **Signature** ```ts export declare const fromNullable: (e: E) => (a: A) => TaskEither> ``` Added in v2.12.0 ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option) => TaskEither ``` Added in v2.0.0 ## fromTask **Signature** ```ts export declare const fromTask: (fa: T.Task) => TaskEither ``` Added in v2.7.0 ## fromTaskOption **Signature** ```ts export declare const fromTaskOption: (onNone: LazyArg) => (fa: TaskOption) => TaskEither ``` Added in v2.11.0 ## toUnion **Signature** ```ts export declare const toUnion: (fa: TaskEither) => T.Task ``` Added in v2.10.0 # do notation ## Do **Signature** ```ts export declare const Do: TaskEither ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: TaskEither ) => (fa: TaskEither) => TaskEither ``` Added in v2.8.0 ## apSW Less strict version of [`apS`](#aps). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apSW: ( name: Exclude, fb: TaskEither ) => (fa: TaskEither) => TaskEither ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => TaskEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: TaskEither) => TaskEither ``` Added in v2.8.0 ## bindW The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const bindW: ( name: Exclude, f: (a: A) => TaskEither ) => (fa: TaskEither) => TaskEither ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: TaskEither) => TaskEither ``` Added in v2.13.0 # error handling ## alt Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to types of kind `* -> *`. In case of `TaskEither` returns `fa` if is a `Right` or the value returned by `that` otherwise. See also [orElse](#orelse). **Signature** ```ts export declare const alt: (that: LazyArg>) => (fa: TaskEither) => TaskEither ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as TE from 'fp-ts/TaskEither' async function test() { assert.deepStrictEqual( await pipe( TE.right(1), TE.alt(() => TE.right(2)) )(), E.right(1) ) assert.deepStrictEqual( await pipe( TE.left('a'), TE.alt(() => TE.right(2)) )(), E.right(2) ) assert.deepStrictEqual( await pipe( TE.left('a'), TE.alt(() => TE.left('b')) )(), E.left('b') ) } test() ``` Added in v2.0.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the error and the return types will be merged. **Signature** ```ts export declare const altW: ( that: LazyArg> ) => (fa: TaskEither) => TaskEither ``` Added in v2.9.0 ## getAltTaskValidation The default [`Alt`](#alt) instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. See [`getAltValidation`](./Either.ts.html#getaltvalidation). **Signature** ```ts export declare function getAltTaskValidation(S: Semigroup): Alt2C ``` Added in v2.7.0 ## getApplicativeTaskValidation The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a `Semigroup`. **Signature** ```ts export declare function getApplicativeTaskValidation(A: Apply1, S: Semigroup): Applicative2C ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as RA from 'fp-ts/ReadonlyArray' import * as S from 'fp-ts/Semigroup' import * as string from 'fp-ts/string' import * as T from 'fp-ts/Task' import * as TE from 'fp-ts/TaskEither' interface User { readonly id: string readonly name: string } const remoteDatabase: ReadonlyArray = [ { id: 'id1', name: 'John' }, { id: 'id2', name: 'Mary' }, { id: 'id3', name: 'Joey' }, ] const fetchUser = (id: string): TE.TaskEither => pipe( remoteDatabase, RA.findFirst((user) => user.id === id), TE.fromOption(() => `${id} not found`) ) async function test() { assert.deepStrictEqual( await pipe(['id4', 'id5'], RA.traverse(TE.ApplicativePar)(fetchUser))(), E.left('id4 not found') // <= first error ) const Applicative = TE.getApplicativeTaskValidation(T.ApplyPar, pipe(string.Semigroup, S.intercalate(', '))) assert.deepStrictEqual( await pipe(['id4', 'id5'], RA.traverse(Applicative)(fetchUser))(), E.left('id4 not found, id5 not found') // <= all errors ) } test() ``` Added in v2.7.0 ## getOrElse **Signature** ```ts export declare const getOrElse: (onLeft: (e: E) => T.Task) => (ma: TaskEither) => T.Task ``` Added in v2.0.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: (onLeft: (e: E) => T.Task) => (ma: TaskEither) => T.Task ``` Added in v2.6.0 ## mapBoth Returns a `TaskEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. **Signature** ```ts export declare const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: TaskEither) => TaskEither (self: TaskEither, f: (e: E) => G, g: (a: A) => B): TaskEither } ``` **Example** ```ts import * as TaskEither from 'fp-ts/TaskEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) const g = (n: number) => n * 2 async function test() { assert.deepStrictEqual(await TaskEither.mapBoth(TaskEither.right(1), f, g)(), Either.right(2)) assert.deepStrictEqual(await TaskEither.mapBoth(TaskEither.left('err'), f, g)(), Either.left(new Error('err'))) } test() ``` Added in v2.16.0 ## mapError Returns a `TaskEither` with its error channel mapped using the specified function. **Signature** ```ts export declare const mapError: { (f: (e: E) => G): (self: TaskEither) => TaskEither (self: TaskEither, f: (e: E) => G): TaskEither } ``` **Example** ```ts import * as TaskEither from 'fp-ts/TaskEither' import * as Either from 'fp-ts/Either' const f = (s: string) => new Error(s) async function test() { assert.deepStrictEqual(await TaskEither.mapError(TaskEither.right(1), f)(), Either.right(1)) assert.deepStrictEqual(await TaskEither.mapError(TaskEither.left('err'), f)(), Either.left(new Error('err'))) } test() ``` Added in v2.16.0 ## orElse Returns `ma` if is a `Right` or the value returned by `onLeft` otherwise. See also [alt](#alt). **Signature** ```ts export declare const orElse: ( onLeft: (e: E1) => TaskEither ) => (ma: TaskEither) => TaskEither ``` **Example** ```ts import * as E from 'fp-ts/Either' import { pipe } from 'fp-ts/function' import * as TE from 'fp-ts/TaskEither' async function test() { const errorHandler = TE.orElse((error: string) => TE.right(`recovering from ${error}...`)) assert.deepStrictEqual(await pipe(TE.right('ok'), errorHandler)(), E.right('ok')) assert.deepStrictEqual(await pipe(TE.left('ko'), errorHandler)(), E.right('recovering from ko...')) } test() ``` Added in v2.0.0 ## orElseFirstIOK **Signature** ```ts export declare const orElseFirstIOK: (onLeft: (e: E) => IO) => (ma: TaskEither) => TaskEither ``` Added in v2.12.0 ## orElseFirstTaskK **Signature** ```ts export declare const orElseFirstTaskK: ( onLeft: (e: E) => T.Task ) => (ma: TaskEither) => TaskEither ``` Added in v2.12.0 ## orElseW Less strict version of [`orElse`](#orelse). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const orElseW: ( onLeft: (e: E1) => TaskEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.10.0 ## orLeft **Signature** ```ts export declare const orLeft: (onLeft: (e: E1) => T.Task) => (fa: TaskEither) => TaskEither ``` Added in v2.11.0 ## tapError Returns an effect that effectfully "peeks" at the failure of this effect. **Signature** ```ts export declare const tapError: { (onLeft: (e: E1) => TaskEither): (self: TaskEither) => TaskEither (self: TaskEither, onLeft: (e: E1) => TaskEither): TaskEither } ``` Added in v2.15.0 # filtering ## filterOrElse **Signature** ```ts export declare const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: TaskEither) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (mb: TaskEither) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (ma: TaskEither) => TaskEither } ``` Added in v2.0.0 ## filterOrElseW Less strict version of [`filterOrElse`](#filterorelse). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: TaskEither ) => TaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: TaskEither ) => TaskEither (predicate: Predicate, onFalse: (a: A) => E2): (ma: TaskEither) => TaskEither } ``` Added in v2.9.0 ## getCompactable **Signature** ```ts export declare const getCompactable: (M: Monoid) => Compactable2C<'TaskEither', E> ``` Added in v2.10.0 ## getFilterable **Signature** ```ts export declare function getFilterable(M: Monoid): Filterable2C ``` Added in v2.1.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt2<'TaskEither'> ``` Added in v2.7.0 ## ApplicativePar Runs computations in parallel. **Signature** ```ts export declare const ApplicativePar: Applicative2<'TaskEither'> ``` Added in v2.7.0 ## ApplicativeSeq Runs computations sequentially. **Signature** ```ts export declare const ApplicativeSeq: Applicative2<'TaskEither'> ``` Added in v2.7.0 ## ApplyPar Runs computations in parallel. **Signature** ```ts export declare const ApplyPar: Apply2<'TaskEither'> ``` Added in v2.10.0 ## ApplySeq Runs computations sequentially. **Signature** ```ts export declare const ApplySeq: Apply2<'TaskEither'> ``` Added in v2.10.0 ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'TaskEither'> ``` Added in v2.7.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain2<'TaskEither'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither2<'TaskEither'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO2<'TaskEither'> ``` Added in v2.10.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask2<'TaskEither'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'TaskEither'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad2<'TaskEither'> ``` Added in v2.10.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO2<'TaskEither'> ``` Added in v2.10.0 ## MonadTask **Signature** ```ts export declare const MonadTask: MonadTask2<'TaskEither'> ``` Added in v2.10.0 ## MonadThrow **Signature** ```ts export declare const MonadThrow: MonadThrow2<'TaskEither'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'TaskEither'> ``` Added in v2.10.0 # interop ## taskify Convert a node style callback function to one returning a `TaskEither` **Note**. If the function `f` admits multiple overloadings, `taskify` will pick last one. If you want a different behaviour, add an explicit type annotation ```ts // readFile admits multiple overloadings // const readFile: (a: string) => TaskEither const readFile = taskify(fs.readFile) const readFile2: (filename: string, encoding: string) => TaskEither = taskify( fs.readFile ) ``` **Signature** ```ts export declare function taskify(f: (cb: (e: L | null | undefined, r?: R) => void) => void): () => TaskEither export declare function taskify( f: (a: A, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A) => TaskEither export declare function taskify( f: (a: A, b: B, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B) => TaskEither export declare function taskify( f: (a: A, b: B, c: C, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B, c: C) => TaskEither export declare function taskify( f: (a: A, b: B, c: C, d: D, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B, c: C, d: D) => TaskEither export declare function taskify( f: (a: A, b: B, c: C, d: D, e: E, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B, c: C, d: D, e: E) => TaskEither ``` **Example** ```ts import { taskify } from 'fp-ts/TaskEither' import * as fs from 'fs' // const stat: (a: string | Buffer) => TaskEither const stat = taskify(fs.stat) assert.strictEqual(stat.length, 0) ``` Added in v2.0.0 ## tryCatch Transforms a `Promise` that may reject to a `Promise` that never rejects and returns an `Either` instead. See also [`tryCatchK`](#trycatchk). **Signature** ```ts export declare const tryCatch: (f: LazyArg>, onRejected: (reason: unknown) => E) => TaskEither ``` **Example** ```ts import { left, right } from 'fp-ts/Either' import { tryCatch } from 'fp-ts/TaskEither' tryCatch(() => Promise.resolve(1), String)().then((result) => { assert.deepStrictEqual(result, right(1)) }) tryCatch(() => Promise.reject('error'), String)().then((result) => { assert.deepStrictEqual(result, left('error')) }) ``` Added in v2.0.0 ## tryCatchK Converts a function returning a `Promise` to one returning a `TaskEither`. **Signature** ```ts export declare const tryCatchK: ( f: (...a: A) => Promise, onRejected: (reason: unknown) => E ) => (...a: A) => TaskEither ``` Added in v2.5.0 # legacy ## bimap Alias of `mapBoth`. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: TaskEither) => TaskEither ``` Added in v2.0.0 ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => TaskEither) => (ma: TaskEither) => TaskEither ``` Added in v2.0.0 ## chainEitherK Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherK: (f: (a: A) => E.Either) => (ma: TaskEither) => TaskEither ``` Added in v2.4.0 ## chainEitherKW Alias of `flatMapEither`. **Signature** ```ts export declare const chainEitherKW: ( f: (a: A) => E.Either ) => (ma: TaskEither) => TaskEither ``` Added in v2.6.1 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => TaskEither) => (ma: TaskEither) => TaskEither ``` Added in v2.0.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: TaskEither) => TaskEither ``` Added in v2.12.0 ## chainFirstEitherKW Alias of `tapEither`. Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: TaskEither) => TaskEither ``` Added in v2.12.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => IO) => (first: TaskEither) => TaskEither ``` Added in v2.10.0 ## chainFirstTaskK Alias of `tapTask`. **Signature** ```ts export declare const chainFirstTaskK: (f: (a: A) => T.Task) => (first: TaskEither) => TaskEither ``` Added in v2.10.0 ## chainFirstW Alias of `tap`. **Signature** ```ts export declare const chainFirstW: ( f: (a: A) => TaskEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.8.0 ## chainIOEitherK Alias of `flatMapIOEither`. **Signature** ```ts export declare const chainIOEitherK: ( f: (a: A) => IOEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.4.0 ## chainIOEitherKW Alias of `flatMapIOEither`. Less strict version of [`chainIOEitherK`](#chainioeitherk). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const chainIOEitherKW: ( f: (a: A) => IOEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.6.1 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => IO) => (first: TaskEither) => TaskEither ``` Added in v2.10.0 ## chainNullableK Use `flatMapNullable`. **Signature** ```ts export declare const chainNullableK: ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: TaskEither) => TaskEither> ``` Added in v2.12.0 ## chainOptionK Use `flatMapOption`. **Signature** ```ts export declare const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: TaskEither) => TaskEither ``` Added in v2.10.0 ## chainOptionKW Use `flatMapOption`. **Signature** ```ts export declare const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: TaskEither) => TaskEither ``` Added in v2.13.2 ## chainTaskK Alias of `flatMapTask`. **Signature** ```ts export declare const chainTaskK: (f: (a: A) => T.Task) => (first: TaskEither) => TaskEither ``` Added in v2.10.0 ## chainTaskOptionK Use `flatMapTaskOption`. **Signature** ```ts export declare const chainTaskOptionK: ( onNone: LazyArg ) => (f: (a: A) => TaskOption) => (ma: TaskEither) => TaskEither ``` Added in v2.11.0 ## chainTaskOptionKW Use `flatMapTaskOption`. The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const chainTaskOptionKW: ( onNone: LazyArg ) => (f: (a: A) => TaskOption) => (ma: TaskEither) => TaskEither ``` Added in v2.12.3 ## chainW Alias of `flatMap`. **Signature** ```ts export declare const chainW: ( f: (a: A) => TaskEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.6.0 ## fromNullableK Use `liftNullable`. **Signature** ```ts export declare const fromNullableK: ( e: E ) => ( f: (...a: A) => B | null | undefined ) => (...a: A) => TaskEither> ``` Added in v2.12.0 ## fromOptionK Use `liftOption`. **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => TaskEither ``` Added in v2.10.0 ## mapLeft Alias of `mapError`. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: TaskEither) => TaskEither ``` Added in v2.0.0 ## orElseFirst Alias of `tapError`. **Signature** ```ts export declare const orElseFirst: ( onLeft: (e: E) => TaskEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.11.0 ## orElseFirstW Alias of `tapError`. **Signature** ```ts export declare const orElseFirstW: ( onLeft: (e: E1) => TaskEither ) => (ma: TaskEither) => TaskEither ``` Added in v2.11.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => E.Either ) => (...a: A) => TaskEither ``` Added in v2.4.0 ## fromIOEitherK **Signature** ```ts export declare const fromIOEitherK: ( f: (...a: A) => IOEither ) => (...a: A) => TaskEither ``` Added in v2.4.0 ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => IO ) => (...a: A) => TaskEither ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (b: B) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => TaskEither } ``` Added in v2.0.0 ## fromTaskK **Signature** ```ts export declare const fromTaskK: ( f: (...a: A) => T.Task ) => (...a: A) => TaskEither ``` Added in v2.10.0 ## fromTaskOptionK **Signature** ```ts export declare const fromTaskOptionK: ( onNone: LazyArg ) => (f: (...a: A) => TaskOption) => (...a: A) => TaskEither ``` Added in v2.11.0 ## liftNullable **Signature** ```ts export declare const liftNullable: ( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => TaskEither> ``` Added in v2.15.0 ## liftOption **Signature** ```ts export declare const liftOption: ( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => TaskEither ``` Added in v2.15.0 # mapping ## as Maps the `Right` value of this `TaskEither` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): (self: TaskEither) => TaskEither (self: TaskEither, a: A): TaskEither } ``` Added in v2.16.0 ## asUnit Maps the `Right` value of this `TaskEither` to the void constant value. **Signature** ```ts export declare const asUnit: (self: TaskEither) => TaskEither ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: TaskEither B>) => TaskEither ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: TaskEither) => TaskEither ``` Added in v2.0.0 # model ## TaskEither (interface) **Signature** ```ts export interface TaskEither extends Task> {} ``` Added in v2.0.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task ) => (ma: TaskEither) => T.Task ``` Added in v2.0.0 ## foldW Alias of [`matchEW`](#matchew). **Signature** ```ts export declare const foldW: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task ) => (ma: TaskEither) => T.Task ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: TaskEither) => T.Task ``` Added in v2.10.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`). **Signature** ```ts export declare const matchE: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task ) => (ma: TaskEither) => T.Task ``` Added in v2.10.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task ) => (ma: TaskEither) => T.Task ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C ) => (ma: TaskEither) => T.Task ``` Added in v2.10.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => TaskEither): (ma: TaskEither) => TaskEither (ma: TaskEither, f: (a: A) => TaskEither): TaskEither } ``` Added in v2.14.0 ## flatMapEither **Signature** ```ts export declare const flatMapEither: { (f: (a: A) => E.Either): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => E.Either): TaskEither } ``` Added in v2.15.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => IO): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => IO): TaskEither } ``` Added in v2.15.0 ## flatMapIOEither **Signature** ```ts export declare const flatMapIOEither: { (f: (a: A) => IOEither): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => IOEither): TaskEither } ``` Added in v2.16.0 ## flatMapNullable **Signature** ```ts export declare const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: TaskEither ) => TaskEither> (self: TaskEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): TaskEither< E1 | E2, NonNullable > } ``` Added in v2.15.0 ## flatMapOption **Signature** ```ts export declare const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => Option, onNone: (a: A) => E2): TaskEither } ``` Added in v2.15.0 ## flatMapTask **Signature** ```ts export declare const flatMapTask: { (f: (a: A) => T.Task): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => T.Task): TaskEither } ``` Added in v2.16.0 ## flatMapTaskOption **Signature** ```ts export declare const flatMapTaskOption: { (f: (a: A) => TaskOption, onNone: (a: A) => E2): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => TaskOption, onNone: (a: A) => E2): TaskEither } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: TaskEither>) => TaskEither ``` Added in v2.0.0 ## flattenW Less strict version of [`flatten`](#flatten). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const flattenW: (mma: TaskEither>) => TaskEither ``` Added in v2.11.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (arr: readonly TaskEither[]) => TaskEither ``` Added in v2.9.0 ## sequenceSeqArray Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. **Signature** ```ts export declare const sequenceSeqArray: (arr: readonly TaskEither[]) => TaskEither ``` Added in v2.9.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: ( f: (a: A) => TaskEither ) => (as: readonly A[]) => TaskEither ``` Added in v2.9.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => TaskEither ) => (as: readonly A[]) => TaskEither ``` Added in v2.9.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => TaskEither ) => (as: readonly A[]) => TaskEither ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( f: (index: number, a: A) => TaskEither ) => (as: readonly A[]) => TaskEither ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => TaskEither ) => (as: ReadonlyNonEmptyArray) => TaskEither> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( f: (index: number, a: A) => TaskEither ) => (as: ReadonlyNonEmptyArray) => TaskEither> ``` Added in v2.11.0 ## traverseSeqArray Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArray: ( f: (a: A) => TaskEither ) => (as: readonly A[]) => TaskEither ``` Added in v2.9.0 ## traverseSeqArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => TaskEither ) => (as: readonly A[]) => TaskEither ``` Added in v2.9.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'TaskEither' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: TaskEither ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: TaskEither) => (fab: TaskEither B>) => TaskEither ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: TaskEither) => (first: TaskEither) => TaskEither ``` Added in v2.0.0 ## apFirstW Less strict version of [`apFirst`](#apfirst). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apFirstW: ( second: TaskEither ) => (first: TaskEither) => TaskEither ``` Added in v2.12.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: TaskEither) => (first: TaskEither) => TaskEither ``` Added in v2.0.0 ## apSecondW Less strict version of [`apSecond`](#apsecond). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apSecondW: ( second: TaskEither ) => (first: TaskEither) => TaskEither ``` Added in v2.12.0 ## apW Less strict version of [`ap`](#ap). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const apW: ( fa: TaskEither ) => (fab: TaskEither B>) => TaskEither ``` Added in v2.8.0 ## bracket Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of whether the body action throws (\*) or returns. (\*) i.e. returns a `Left` **Signature** ```ts export declare const bracket: ( acquire: TaskEither, use: (a: A) => TaskEither, release: (a: A, e: E.Either) => TaskEither ) => TaskEither ``` Added in v2.0.0 ## bracketW Less strict version of [`bracket`](#bracket). The `W` suffix (short for **W**idening) means that the error types will be merged. **Signature** ```ts export declare const bracketW: ( acquire: TaskEither, use: (a: A) => TaskEither, release: (a: A, e: E.Either) => TaskEither ) => TaskEither ``` Added in v2.12.0 ## swap **Signature** ```ts export declare const swap: (ma: TaskEither) => TaskEither ``` Added in v2.0.0 ## throwError **Signature** ```ts export declare const throwError: (e: E) => TaskEither ``` Added in v2.7.0 # zone of death ## ~~getApplyMonoid~~ Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. **Signature** ```ts export declare const getApplyMonoid: (M: Monoid) => Monoid> ``` Added in v2.0.0 ## ~~getApplySemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getApplySemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => Semigroup> ``` Added in v2.0.0 ## ~~getTaskValidation~~ Use [`getApplicativeTaskValidation`](#getapplicativetaskvalidation) and [`getAltTaskValidation`](#getalttaskvalidation) instead. **Signature** ```ts export declare function getTaskValidation( SE: Semigroup ): Monad2C & Bifunctor2 & Alt2C & MonadTask2C & MonadThrow2C ``` Added in v2.0.0 ## ~~taskEitherSeq~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `TE.Functor` instead of `TE.taskEitherSeq` (where `TE` is from `import TE from 'fp-ts/TaskEither'`) **Signature** ```ts export declare const taskEitherSeq: Monad2<'TaskEither'> & Bifunctor2<'TaskEither'> & Alt2<'TaskEither'> & MonadTask2<'TaskEither'> & MonadThrow2<'TaskEither'> ``` Added in v2.0.0 ## ~~taskEither~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `TE.Functor` instead of `TE.taskEither` (where `TE` is from `import TE from 'fp-ts/TaskEither'`) **Signature** ```ts export declare const taskEither: Monad2<'TaskEither'> & Bifunctor2<'TaskEither'> & Alt2<'TaskEither'> & MonadTask2<'TaskEither'> & MonadThrow2<'TaskEither'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/TaskOption.ts.md ================================================ --- title: TaskOption.ts nav_order: 107 parent: Modules --- ## TaskOption overview Added in v2.10.0 ---

Table of contents

- [combinators](#combinators) - [tap](#tap) - [tapEither](#tapeither) - [tapIO](#tapio) - [tapTask](#taptask) - [constructors](#constructors) - [none](#none) - [of](#of) - [some](#some) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromNullable](#fromnullable) - [fromOption](#fromoption) - [fromTask](#fromtask) - [fromTaskEither](#fromtaskeither) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [guard](#guard) - [let](#let) - [error handling](#error-handling) - [alt](#alt) - [altW](#altw) - [getOrElse](#getorelse) - [getOrElseW](#getorelsew) - [filtering](#filtering) - [compact](#compact) - [filter](#filter) - [filterMap](#filtermap) - [partition](#partition) - [partitionMap](#partitionmap) - [separate](#separate) - [instances](#instances) - [Alt](#alt) - [Alternative](#alternative) - [ApplicativePar](#applicativepar) - [ApplicativeSeq](#applicativeseq) - [ApplyPar](#applypar) - [ApplySeq](#applyseq) - [Chain](#chain) - [Compactable](#compactable) - [Filterable](#filterable) - [FromEither](#fromeither) - [FromIO](#fromio) - [FromTask](#fromtask) - [Functor](#functor) - [Monad](#monad) - [MonadIO](#monadio) - [MonadTask](#monadtask) - [Pointed](#pointed) - [Zero](#zero) - [interop](#interop) - [tryCatch](#trycatch) - [tryCatchK](#trycatchk) - [legacy](#legacy) - [chain](#chain) - [chainFirst](#chainfirst) - [chainFirstEitherK](#chainfirsteitherk) - [chainFirstIOK](#chainfirstiok) - [chainFirstTaskK](#chainfirsttaskk) - [chainIOK](#chainiok) - [chainTaskK](#chaintaskk) - [lifting](#lifting) - [fromEitherK](#fromeitherk) - [fromIOK](#fromiok) - [fromNullableK](#fromnullablek) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [fromTaskK](#fromtaskk) - [mapping](#mapping) - [as](#as) - [asUnit](#asunit) - [flap](#flap) - [map](#map) - [model](#model) - [TaskOption (interface)](#taskoption-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [sequencing](#sequencing) - [chainEitherK](#chaineitherk) - [chainNullableK](#chainnullablek) - [chainOptionK](#chainoptionk) - [flatMap](#flatmap) - [flatMapIO](#flatmapio) - [flatMapTask](#flatmaptask) - [flatten](#flatten) - [traversing](#traversing) - [sequenceArray](#sequencearray) - [sequenceSeqArray](#sequenceseqarray) - [traverseArray](#traversearray) - [traverseArrayWithIndex](#traversearraywithindex) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [traverseSeqArray](#traverseseqarray) - [traverseSeqArrayWithIndex](#traverseseqarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [zero](#zero) --- # combinators ## tap Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tap: { (self: TaskOption
, f: (a: A) => TaskOption<_>): TaskOption (f: (a: A) => TaskOption<_>): (self: TaskOption) => TaskOption } ``` Added in v2.15.0 ## tapEither Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapEither: { (f: (a: A) => Either): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => Either): TaskOption } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as TO from 'fp-ts/TaskOption' import * as O from 'fp-ts/Option' import * as E from 'fp-ts/Either' const compute = (value: number) => pipe( TO.of(value), TO.tapEither((value) => (value > 0 ? E.right('ok') : E.left('error'))) ) async function test() { assert.deepStrictEqual(await compute(1)(), O.of(1)) assert.deepStrictEqual(await compute(-1)(), O.none) } test() ``` Added in v2.16.0 ## tapIO Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapIO: { (f: (a: A) => IO<_>): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => IO<_>): TaskOption } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import * as TO from 'fp-ts/TaskOption' import * as O from 'fp-ts/Option' import * as Console from 'fp-ts/Console' // Will produce `Hello, fp-ts` to the stdout const effectA = TO.tapIO(TO.of(1), (value) => Console.log(`Hello, ${value}`)) // No output to the stdout const effectB = pipe( TO.none as TO.TaskOption, TO.tapIO((value) => Console.log(`Hello, ${value}`)) ) async function test() { assert.deepStrictEqual(await effectA(), O.of(1)) assert.deepStrictEqual(await effectB(), O.none) } test() ``` Added in v2.16.0 ## tapTask Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const tapTask: { (f: (a: A) => T.Task<_>): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => T.Task<_>): TaskOption } ``` **Example** ```ts import * as TO from 'fp-ts/TaskOption' import * as O from 'fp-ts/Option' import * as T from 'fp-ts/Task' const effect = TO.tapIO(TO.of(1), (value) => T.of(value + 1)) async function test() { assert.deepStrictEqual(await effect(), O.of(1)) } test() ``` Added in v2.16.0 # constructors ## none **Signature** ```ts export declare const none: TaskOption ``` Added in v2.10.0 ## of **Signature** ```ts export declare const of: (a: A) => TaskOption ``` Added in v2.10.0 ## some **Signature** ```ts export declare const some: (a: A) => TaskOption ``` Added in v2.10.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: Either) => TaskOption ``` Added in v2.10.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO) => TaskOption ``` Added in v2.10.0 ## fromNullable **Signature** ```ts export declare const fromNullable: (a: A) => TaskOption> ``` Added in v2.10.0 ## fromOption **Signature** ```ts export declare const fromOption: (fa: O.Option) => TaskOption ``` Added in v2.10.0 ## fromTask **Signature** ```ts export declare const fromTask: (fa: T.Task) => TaskOption ``` Added in v2.10.0 ## fromTaskEither **Signature** ```ts export declare const fromTaskEither: (fa: TaskEither) => TaskOption ``` Added in v2.11.0 # do notation ## Do **Signature** ```ts export declare const Do: TaskOption<{}> ``` Added in v2.10.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: TaskOption ) => (fa: TaskOption) => TaskOption<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.10.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => TaskOption ) => (ma: TaskOption) => TaskOption<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.10.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: TaskOption) => TaskOption<{ readonly [K in N]: A }> ``` Added in v2.10.0 ## guard **Signature** ```ts export declare const guard: (b: boolean) => TaskOption ``` Added in v2.11.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: TaskOption) => TaskOption<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # error handling ## alt **Signature** ```ts export declare const alt: (second: LazyArg>) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## altW Less strict version of [`alt`](#alt). The `W` suffix (short for **W**idening) means that the return types will be merged. **Signature** ```ts export declare const altW: (second: LazyArg>) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## getOrElse **Signature** ```ts export declare const getOrElse: (onNone: LazyArg>) => (fa: TaskOption) => T.Task ``` Added in v2.10.0 ## getOrElseW Less strict version of [`getOrElse`](#getorelse). The `W` suffix (short for **W**idening) means that the handler return type will be merged. **Signature** ```ts export declare const getOrElseW: (onNone: LazyArg>) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 # filtering ## compact **Signature** ```ts export declare const compact: (fa: TaskOption>) => TaskOption ``` Added in v2.10.0 ## filter **Signature** ```ts export declare const filter: { (refinement: Refinement): (fb: TaskOption) => TaskOption (predicate: Predicate): (fb: TaskOption) => TaskOption (predicate: Predicate): (fa: TaskOption) => TaskOption } ``` Added in v2.10.0 ## filterMap **Signature** ```ts export declare const filterMap: (f: (a: A) => O.Option) => (fga: TaskOption) => TaskOption ``` Added in v2.10.0 ## partition **Signature** ```ts export declare const partition: { (refinement: Refinement): (fb: TaskOption) => Separated, TaskOption> (predicate: Predicate): (fb: TaskOption) => Separated, TaskOption> (predicate: Predicate): (fa: TaskOption) => Separated, TaskOption> } ``` Added in v2.10.0 ## partitionMap **Signature** ```ts export declare const partitionMap: ( f: (a: A) => Either ) => (fa: TaskOption) => Separated, TaskOption> ``` Added in v2.10.0 ## separate **Signature** ```ts export declare const separate: (fa: TaskOption>) => Separated, TaskOption> ``` Added in v2.10.0 # instances ## Alt **Signature** ```ts export declare const Alt: Alt1<'TaskOption'> ``` Added in v2.10.0 ## Alternative **Signature** ```ts export declare const Alternative: Alternative1<'TaskOption'> ``` Added in v2.10.0 ## ApplicativePar Runs computations in parallel. **Signature** ```ts export declare const ApplicativePar: Applicative1<'TaskOption'> ``` Added in v2.10.0 ## ApplicativeSeq Runs computations sequentially. **Signature** ```ts export declare const ApplicativeSeq: Applicative1<'TaskOption'> ``` Added in v2.10.0 ## ApplyPar Runs computations in parallel. **Signature** ```ts export declare const ApplyPar: Apply1<'TaskOption'> ``` Added in v2.10.0 ## ApplySeq Runs computations sequentially. **Signature** ```ts export declare const ApplySeq: Apply1<'TaskOption'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: chainable.Chain1<'TaskOption'> ``` Added in v2.10.0 ## Compactable **Signature** ```ts export declare const Compactable: Compactable1<'TaskOption'> ``` Added in v2.10.0 ## Filterable **Signature** ```ts export declare const Filterable: Filterable1<'TaskOption'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither1<'TaskOption'> ``` Added in v2.11.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO1<'TaskOption'> ``` Added in v2.10.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask1<'TaskOption'> ``` Added in v2.10.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'TaskOption'> ``` Added in v2.10.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'TaskOption'> ``` Added in v2.10.0 ## MonadIO **Signature** ```ts export declare const MonadIO: MonadIO1<'TaskOption'> ``` Added in v2.10.0 ## MonadTask **Signature** ```ts export declare const MonadTask: MonadTask1<'TaskOption'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'TaskOption'> ``` Added in v2.10.0 ## Zero **Signature** ```ts export declare const Zero: Zero1<'TaskOption'> ``` Added in v2.11.0 # interop ## tryCatch Transforms a `Promise` that may reject to a `Promise` that never rejects and returns an `Option` instead. See also [`tryCatchK`](#trycatchk). **Signature** ```ts export declare const tryCatch: (f: LazyArg>) => TaskOption ``` Added in v2.10.0 ## tryCatchK Converts a function returning a `Promise` to one returning a `TaskOption`. **Signature** ```ts export declare const tryCatchK: ( f: (...a: A) => Promise ) => (...a: A) => TaskOption ``` Added in v2.10.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => TaskOption) => (ma: TaskOption) => TaskOption ``` Added in v2.10.0 ## chainFirst Alias of `tap`. **Signature** ```ts export declare const chainFirst: (f: (a: A) => TaskOption) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## chainFirstEitherK Alias of `tapEither`. **Signature** ```ts export declare const chainFirstEitherK: (f: (a: A) => Either) => (ma: TaskOption) => TaskOption ``` Added in v2.12.0 ## chainFirstIOK Alias of `tapIO`. **Signature** ```ts export declare const chainFirstIOK: (f: (a: A) => IO) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## chainFirstTaskK Alias of `tapTask`. **Signature** ```ts export declare const chainFirstTaskK: (f: (a: A) => T.Task) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## chainIOK Alias of `flatMapIO`. **Signature** ```ts export declare const chainIOK: (f: (a: A) => IO) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## chainTaskK Alias of `flatMapTask`. **Signature** ```ts export declare const chainTaskK: (f: (a: A) => T.Task) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 # lifting ## fromEitherK **Signature** ```ts export declare const fromEitherK: ( f: (...a: A) => Either ) => (...a: A) => TaskOption ``` Added in v2.12.0 ## fromIOK **Signature** ```ts export declare const fromIOK: (f: (...a: A) => IO) => (...a: A) => TaskOption ``` Added in v2.10.0 ## fromNullableK **Signature** ```ts export declare const fromNullableK: ( f: (...a: A) => B | null | undefined ) => (...a: A) => TaskOption> ``` Added in v2.10.0 ## fromOptionK **Signature** ```ts export declare const fromOptionK: ( f: (...a: A) => O.Option ) => (...a: A) => TaskOption ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement): (a: A) => TaskOption (predicate: Predicate): (b: B) => TaskOption (predicate: Predicate): (a: A) => TaskOption } ``` Added in v2.10.0 ## fromTaskK **Signature** ```ts export declare const fromTaskK: ( f: (...a: A) => T.Task ) => (...a: A) => TaskOption ``` Added in v2.10.0 # mapping ## as Maps the `Some` value of this `TaskOption` to the specified constant value. **Signature** ```ts export declare const as: { (a: A): <_>(self: TaskOption<_>) => TaskOption <_, A>(self: TaskOption<_>, a: A): TaskOption } ``` Added in v2.16.0 ## asUnit Maps the `Some` value of this `TaskOption` to the void constant value. **Signature** ```ts export declare const asUnit: <_>(self: TaskOption<_>) => TaskOption ``` Added in v2.16.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: TaskOption<(a: A) => B>) => TaskOption ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: TaskOption) => TaskOption ``` Added in v2.10.0 # model ## TaskOption (interface) **Signature** ```ts export interface TaskOption extends Task> {} ``` Added in v2.10.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: ( onNone: () => T.Task, onSome: (a: A) => T.Task ) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 ## foldW Alias of [`matchEW`](#matchew). **Signature** ```ts export declare const foldW: ( onNone: () => T.Task, onSome: (a: A) => T.Task ) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: (onNone: () => B, onSome: (a: A) => B) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`). **Signature** ```ts export declare const matchE: ( onNone: () => T.Task, onSome: (a: A) => T.Task ) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onNone: () => T.Task, onSome: (a: A) => T.Task ) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: (onNone: () => B, onSome: (a: A) => C) => (ma: TaskOption) => T.Task ``` Added in v2.10.0 # sequencing ## chainEitherK **Signature** ```ts export declare const chainEitherK: (f: (a: A) => Either) => (ma: TaskOption) => TaskOption ``` Added in v2.12.0 ## chainNullableK **Signature** ```ts export declare const chainNullableK: ( f: (a: A) => B | null | undefined ) => (ma: TaskOption) => TaskOption> ``` Added in v2.10.0 ## chainOptionK **Signature** ```ts export declare const chainOptionK: (f: (a: A) => O.Option) => (ma: TaskOption) => TaskOption ``` Added in v2.10.0 ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => TaskOption): (ma: TaskOption) => TaskOption (ma: TaskOption, f: (a: A) => TaskOption): TaskOption } ``` Added in v2.14.0 ## flatMapIO **Signature** ```ts export declare const flatMapIO: { (f: (a: A) => IO): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => IO): TaskOption } ``` Added in v2.16.0 ## flatMapTask **Signature** ```ts export declare const flatMapTask: { (f: (a: A) => T.Task): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => T.Task): TaskOption } ``` Added in v2.16.0 ## flatten **Signature** ```ts export declare const flatten: (mma: TaskOption>) => TaskOption ``` Added in v2.10.0 # traversing ## sequenceArray Equivalent to `ReadonlyArray#sequence(Applicative)`. **Signature** ```ts export declare const sequenceArray: (as: readonly TaskOption[]) => TaskOption ``` Added in v2.10.0 ## sequenceSeqArray Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. **Signature** ```ts export declare const sequenceSeqArray: (as: readonly TaskOption[]) => TaskOption ``` Added in v2.10.0 ## traverseArray Equivalent to `ReadonlyArray#traverse(Applicative)`. **Signature** ```ts export declare const traverseArray: (f: (a: A) => TaskOption) => (as: readonly A[]) => TaskOption ``` Added in v2.10.0 ## traverseArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. **Signature** ```ts export declare const traverseArrayWithIndex: ( f: (index: number, a: A) => TaskOption ) => (as: readonly A[]) => TaskOption ``` Added in v2.10.0 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( f: (index: number, a: A) => TaskOption ) => (as: readonly A[]) => TaskOption ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( f: (index: number, a: A) => TaskOption ) => (as: readonly A[]) => TaskOption ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => TaskOption ) => (as: ReadonlyNonEmptyArray) => TaskOption> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( f: (index: number, a: A) => TaskOption ) => (as: ReadonlyNonEmptyArray) => TaskOption> ``` Added in v2.11.0 ## traverseSeqArray Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArray: ( f: (a: A) => TaskOption ) => (as: readonly A[]) => TaskOption ``` Added in v2.10.0 ## traverseSeqArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. **Signature** ```ts export declare const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => TaskOption ) => (as: readonly A[]) => TaskOption ``` Added in v2.10.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'TaskOption' ``` Added in v2.10.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.10.0 # utils ## ApT **Signature** ```ts export declare const ApT: TaskOption ``` Added in v2.11.0 ## ap **Signature** ```ts export declare const ap: (fa: TaskOption) => (fab: TaskOption<(a: A) => B>) => TaskOption ``` Added in v2.10.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: TaskOption) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: TaskOption) => (first: TaskOption) => TaskOption ``` Added in v2.10.0 ## zero **Signature** ```ts export declare const zero: () => TaskOption ``` Added in v2.10.0 ================================================ FILE: docs/modules/TaskThese.ts.md ================================================ --- title: TaskThese.ts nav_order: 108 parent: Modules --- ## TaskThese overview Added in v2.4.0 ---

Table of contents

- [constructors](#constructors) - [both](#both) - [left](#left) - [leftIO](#leftio) - [leftTask](#lefttask) - [of](#of) - [right](#right) - [rightIO](#rightio) - [rightTask](#righttask) - [conversions](#conversions) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromIOEither](#fromioeither) - [fromOption](#fromoption) - [fromTask](#fromtask) - [fromThese](#fromthese) - [error handling](#error-handling) - [mapLeft](#mapleft) - [instances](#instances) - [Bifunctor](#bifunctor) - [FromEither](#fromeither) - [FromIO](#fromio) - [FromTask](#fromtask) - [FromThese](#fromthese) - [Functor](#functor) - [Pointed](#pointed) - [getApplicative](#getapplicative) - [getApply](#getapply) - [getChain](#getchain) - [getMonad](#getmonad) - [lifting](#lifting) - [fromIOK](#fromiok) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [fromTaskK](#fromtaskk) - [fromTheseK](#fromthesek) - [mapping](#mapping) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [model](#model) - [TaskThese (interface)](#taskthese-interface) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchE](#matche) - [matchEW](#matchew) - [matchW](#matchw) - [traversing](#traversing) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyArrayWithIndexSeq](#traversereadonlyarraywithindexseq) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndexSeq](#traversereadonlynonemptyarraywithindexseq) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [swap](#swap) - [toTuple2](#totuple2) - [zone of death](#zone-of-death) - [~~bifunctorTaskThese~~](#bifunctortaskthese) - [~~functorTaskThese~~](#functortaskthese) - [~~getSemigroup~~](#getsemigroup) - [~~taskThese~~](#taskthese) - [~~toTuple~~](#totuple) --- # constructors ## both **Signature** ```ts export declare const both: (e: E, a: A) => TaskThese ``` Added in v2.4.0 ## left **Signature** ```ts export declare const left: (e: E) => TaskThese ``` Added in v2.4.0 ## leftIO **Signature** ```ts export declare const leftIO: (me: IO) => TaskThese ``` Added in v2.4.0 ## leftTask **Signature** ```ts export declare const leftTask: (me: T.Task) => TaskThese ``` Added in v2.4.0 ## of **Signature** ```ts export declare const of: (a: A) => TaskThese ``` Added in v2.7.0 ## right **Signature** ```ts export declare const right: (a: A) => TaskThese ``` Added in v2.4.0 ## rightIO **Signature** ```ts export declare const rightIO: (ma: IO
) => TaskThese ``` Added in v2.4.0 ## rightTask **Signature** ```ts export declare const rightTask: (ma: T.Task) => TaskThese ``` Added in v2.4.0 # conversions ## fromEither **Signature** ```ts export declare const fromEither: (fa: Either) => TaskThese ``` Added in v2.10.0 ## fromIO **Signature** ```ts export declare const fromIO: (fa: IO) => TaskThese ``` Added in v2.7.0 ## fromIOEither **Signature** ```ts export declare const fromIOEither: (fa: IOEither) => TaskThese ``` Added in v2.4.0 ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option) => TaskThese ``` Added in v2.10.0 ## fromTask **Signature** ```ts export declare const fromTask: (fa: T.Task) => TaskThese ``` Added in v2.7.0 ## fromThese **Signature** ```ts export declare const fromThese: (fa: TH.These) => TaskThese ``` Added in v2.11.0 # error handling ## mapLeft Map a function over the first type argument of a bifunctor. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: TaskThese) => TaskThese ``` Added in v2.4.0 # instances ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'TaskThese'> ``` Added in v2.10.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither2<'TaskThese'> ``` Added in v2.10.0 ## FromIO **Signature** ```ts export declare const FromIO: FromIO2<'TaskThese'> ``` Added in v2.10.0 ## FromTask **Signature** ```ts export declare const FromTask: FromTask2<'TaskThese'> ``` Added in v2.10.0 ## FromThese **Signature** ```ts export declare const FromThese: FromThese2<'TaskThese'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'TaskThese'> ``` Added in v2.10.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'TaskThese'> ``` Added in v2.10.0 ## getApplicative **Signature** ```ts export declare function getApplicative(A: Apply1, S: Semigroup): Applicative2C ``` Added in v2.7.0 ## getApply **Signature** ```ts export declare const getApply: (A: Apply1, S: Semigroup) => Apply2C<'TaskThese', E> ``` Added in v2.10.0 ## getChain **Signature** ```ts export declare function getChain(S: Semigroup): Chain2C ``` Added in v2.10.0 ## getMonad **Signature** ```ts export declare function getMonad(S: Semigroup): Monad2C & MonadTask2C ``` Added in v2.4.0 # lifting ## fromIOK **Signature** ```ts export declare const fromIOK: ( f: (...a: A) => IO ) => (...a: A) => TaskThese ``` Added in v2.10.0 ## fromOptionK **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => TaskThese ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => TaskThese (predicate: Predicate, onFalse: (a: A) => E): (b: B) => TaskThese (predicate: Predicate, onFalse: (a: A) => E): (a: A) => TaskThese } ``` Added in v2.10.0 ## fromTaskK **Signature** ```ts export declare const fromTaskK: ( f: (...a: A) => T.Task ) => (...a: A) => TaskThese ``` Added in v2.10.0 ## fromTheseK **Signature** ```ts export declare const fromTheseK: ( f: (...a: A) => TH.These ) => (...a: A) => TaskThese ``` Added in v2.11.0 # mapping ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: TaskThese) => TaskThese ``` Added in v2.4.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: TaskThese B>) => TaskThese ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: TaskThese) => TaskThese ``` Added in v2.4.0 # model ## TaskThese (interface) **Signature** ```ts export interface TaskThese extends Task> {} ``` Added in v2.4.0 # pattern matching ## fold Alias of [`matchE`](#matche). **Signature** ```ts export declare const fold: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task, onBoth: (e: E, a: A) => T.Task ) => (fa: TaskThese) => T.Task ``` Added in v2.4.0 ## foldW Alias of [`matchEW`](#matchew). **Signature** ```ts export declare const foldW: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task, onBoth: (e: E, a: A) => T.Task ) => (fa: TaskThese) => T.Task ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (fa: TaskThese) => T.Task ``` Added in v2.10.0 ## matchE The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`). **Signature** ```ts export declare const matchE: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task, onBoth: (e: E, a: A) => T.Task ) => (fa: TaskThese) => T.Task ``` Added in v2.10.0 ## matchEW Less strict version of [`matchE`](#matche). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchEW: ( onLeft: (e: E) => T.Task, onRight: (a: A) => T.Task, onBoth: (e: E, a: A) => T.Task ) => (fa: TaskThese) => T.Task ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C, onBoth: (e: E, a: A) => D ) => (ma: TaskThese) => T.Task ``` Added in v2.10.0 # traversing ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(getApplicative(T.ApplicativePar, S))`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( S: Semigroup ) => (f: (index: number, a: A) => TaskThese) => (as: readonly A[]) => TaskThese ``` Added in v2.11.0 ## traverseReadonlyArrayWithIndexSeq Equivalent to `ReadonlyArray#traverseWithIndex(getApplicative(T.ApplicativeSeq, S))`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndexSeq: ( S: Semigroup ) => (f: (index: number, a: A) => TaskThese) => (as: readonly A[]) => TaskThese ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(getApplicative(T.ApplicativePar, S))`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( S: Semigroup ) => ( f: (index: number, a: A) => TaskThese ) => (as: ReadonlyNonEmptyArray) => TaskThese> ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndexSeq Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(getApplicative(T.ApplicativeSeq, S))`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndexSeq: ( S: Semigroup ) => ( f: (index: number, a: A) => TaskThese ) => (as: ReadonlyNonEmptyArray) => TaskThese> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'TaskThese' ``` Added in v2.4.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.4.0 # utils ## ApT **Signature** ```ts export declare const ApT: TaskThese ``` Added in v2.11.0 ## swap **Signature** ```ts export declare const swap: (fa: TaskThese) => TaskThese ``` Added in v2.4.0 ## toTuple2 **Signature** ```ts export declare const toTuple2: (e: LazyArg, a: LazyArg) => (fa: TaskThese) => T.Task ``` Added in v2.10.0 # zone of death ## ~~bifunctorTaskThese~~ Use [`Bifunctor`](#bifunctor) instead. **Signature** ```ts export declare const bifunctorTaskThese: Bifunctor2<'TaskThese'> ``` Added in v2.7.0 ## ~~functorTaskThese~~ Use [`Functor`](#functor) instead. **Signature** ```ts export declare const functorTaskThese: Functor2<'TaskThese'> ``` Added in v2.7.0 ## ~~getSemigroup~~ Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. **Signature** ```ts export declare const getSemigroup: (SE: Semigroup, SA: Semigroup) => Semigroup> ``` Added in v2.4.0 ## ~~taskThese~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `TT.Functor` instead of `TT.taskThese` (where `TT` is from `import TT from 'fp-ts/TaskThese'`) **Signature** ```ts export declare const taskThese: Functor2<'TaskThese'> & Bifunctor2<'TaskThese'> ``` Added in v2.4.0 ## ~~toTuple~~ Use [`toTuple2`](#totuple2) instead. **Signature** ```ts export declare const toTuple: (e: E, a: A) => (fa: TaskThese) => T.Task<[E, A]> ``` Added in v2.4.0 ================================================ FILE: docs/modules/These.ts.md ================================================ --- title: These.ts nav_order: 109 parent: Modules --- ## These overview A data structure providing "inclusive-or" as opposed to `Either`'s "exclusive-or". If you interpret `Either` as suggesting the computation may either fail or succeed (exclusively), then `These` may fail, succeed, or do both at the same time. There are a few ways to interpret the both case: - You can think of a computation that has a non-fatal error. - You can think of a computation that went as far as it could before erroring. - You can think of a computation that keeps track of errors as it completes. Another way you can think of `These` is saying that we want to handle `E` kind of data, `A` kind of data, or both `E` and `A` kind of data at the same time. This is particularly useful when it comes to displaying UI's. (description adapted from https://package.elm-lang.org/packages/joneshf/elm-these) Adapted from https://github.com/purescript-contrib/purescript-these Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [both](#both) - [left](#left) - [leftOrBoth](#leftorboth) - [of](#of) - [right](#right) - [rightOrBoth](#rightorboth) - [conversions](#conversions) - [fromOption](#fromoption) - [fromOptions](#fromoptions) - [getLeft](#getleft) - [getLeftOnly](#getleftonly) - [getRight](#getright) - [getRightOnly](#getrightonly) - [toTuple2](#totuple2) - [error handling](#error-handling) - [mapLeft](#mapleft) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Bifunctor](#bifunctor) - [Foldable](#foldable) - [FromEither](#fromeither) - [FromThese](#fromthese) - [Functor](#functor) - [Pointed](#pointed) - [Traversable](#traversable) - [getApplicative](#getapplicative) - [getApply](#getapply) - [getChain](#getchain) - [getEq](#geteq) - [getMonad](#getmonad) - [getSemigroup](#getsemigroup) - [getShow](#getshow) - [lifting](#lifting) - [fromOptionK](#fromoptionk) - [fromPredicate](#frompredicate) - [mapping](#mapping) - [bimap](#bimap) - [flap](#flap) - [map](#map) - [model](#model) - [Both (interface)](#both-interface) - [These (type alias)](#these-type-alias) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchW](#matchw) - [refinements](#refinements) - [isBoth](#isboth) - [isLeft](#isleft) - [isRight](#isright) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [traverseReadonlyArrayWithIndex](#traversereadonlyarraywithindex) - [traverseReadonlyNonEmptyArrayWithIndex](#traversereadonlynonemptyarraywithindex) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ApT](#apt) - [elem](#elem) - [exists](#exists) - [swap](#swap) - [zone of death](#zone-of-death) - [~~these~~](#these) - [~~toTuple~~](#totuple) --- # constructors ## both **Signature** ```ts export declare function both(left: E, right: A): These ``` Added in v2.0.0 ## left **Signature** ```ts export declare function left(left: E): These ``` Added in v2.0.0 ## leftOrBoth **Signature** ```ts export declare function leftOrBoth(e: E):
(ma: Option) => These ``` **Example** ```ts import { leftOrBoth, left, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(leftOrBoth('a')(none), left('a')) assert.deepStrictEqual(leftOrBoth('a')(some(1)), both('a', 1)) ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (right: A) => These ``` Added in v2.0.0 ## right **Signature** ```ts export declare function right(right: A): These ``` Added in v2.0.0 ## rightOrBoth **Signature** ```ts export declare function rightOrBoth(a: A): (me: Option) => These ``` **Example** ```ts import { rightOrBoth, right, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(rightOrBoth(1)(none), right(1)) assert.deepStrictEqual(rightOrBoth(1)(some('a')), both('a', 1)) ``` Added in v2.0.0 # conversions ## fromOption **Signature** ```ts export declare const fromOption: (onNone: LazyArg) => (fa: Option) => These ``` Added in v2.10.0 ## fromOptions Takes a pair of `Option`s and attempts to create a `These` from them **Signature** ```ts export declare const fromOptions: (fe: Option, fa: Option) => Option> ``` **Example** ```ts import { fromOptions, left, right, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(fromOptions(none, none), none) assert.deepStrictEqual(fromOptions(some('a'), none), some(left('a'))) assert.deepStrictEqual(fromOptions(none, some(1)), some(right(1))) assert.deepStrictEqual(fromOptions(some('a'), some(1)), some(both('a', 1))) ``` Added in v2.0.0 ## getLeft Returns an `E` value if possible **Signature** ```ts export declare function getLeft(fa: These): Option ``` **Example** ```ts import { getLeft, left, right, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(getLeft(left('a')), some('a')) assert.deepStrictEqual(getLeft(right(1)), none) assert.deepStrictEqual(getLeft(both('a', 1)), some('a')) ``` Added in v2.0.0 ## getLeftOnly Returns the `E` value if and only if the value is constructed with `Left` **Signature** ```ts export declare function getLeftOnly(fa: These): Option ``` **Example** ```ts import { getLeftOnly, left, right, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(getLeftOnly(left('a')), some('a')) assert.deepStrictEqual(getLeftOnly(right(1)), none) assert.deepStrictEqual(getLeftOnly(both('a', 1)), none) ``` Added in v2.0.0 ## getRight Returns an `A` value if possible **Signature** ```ts export declare function getRight(fa: These): Option ``` **Example** ```ts import { getRight, left, right, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(getRight(left('a')), none) assert.deepStrictEqual(getRight(right(1)), some(1)) assert.deepStrictEqual(getRight(both('a', 1)), some(1)) ``` Added in v2.0.0 ## getRightOnly Returns the `A` value if and only if the value is constructed with `Right` **Signature** ```ts export declare function getRightOnly(fa: These): Option ``` **Example** ```ts import { getRightOnly, left, right, both } from 'fp-ts/These' import { none, some } from 'fp-ts/Option' assert.deepStrictEqual(getRightOnly(left('a')), none) assert.deepStrictEqual(getRightOnly(right(1)), some(1)) assert.deepStrictEqual(getRightOnly(both('a', 1)), none) ``` Added in v2.0.0 ## toTuple2 **Signature** ```ts export declare const toTuple2: (e: LazyArg, a: LazyArg) => (fa: These) => readonly [E, A] ``` **Example** ```ts import { toTuple2, left, right, both } from 'fp-ts/These' assert.deepStrictEqual( toTuple2( () => 'a', () => 1 )(left('b')), ['b', 1] ) assert.deepStrictEqual( toTuple2( () => 'a', () => 1 )(right(2)), ['a', 2] ) assert.deepStrictEqual( toTuple2( () => 'a', () => 1 )(both('b', 2)), ['b', 2] ) ``` Added in v2.10.0 # error handling ## mapLeft Map a function over the first type argument of a bifunctor. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: These) => These ``` Added in v2.0.0 # folding ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: These) => M ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: These) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: These) => B ``` Added in v2.0.0 # instances ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'These'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable2<'These'> ``` Added in v2.7.0 ## FromEither **Signature** ```ts export declare const FromEither: FromEither2<'These'> ``` Added in v2.10.0 ## FromThese **Signature** ```ts export declare const FromThese: FromThese2<'These'> ``` Added in v2.11.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'These'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed2<'These'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable2<'These'> ``` Added in v2.7.0 ## getApplicative **Signature** ```ts export declare function getApplicative(S: Semigroup): Applicative2C ``` Added in v2.7.0 ## getApply **Signature** ```ts export declare const getApply: (S: Semigroup) => Apply2C<'These', E> ``` Added in v2.10.0 ## getChain **Signature** ```ts export declare function getChain(S: Semigroup): Chain2C ``` Added in v2.10.0 ## getEq **Signature** ```ts export declare function getEq(EE: Eq, EA: Eq): Eq> ``` Added in v2.0.0 ## getMonad **Signature** ```ts export declare function getMonad(S: Semigroup): Monad2C & MonadThrow2C ``` Added in v2.0.0 ## getSemigroup **Signature** ```ts export declare function getSemigroup(SE: Semigroup, SA: Semigroup): Semigroup> ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare function getShow(SE: Show, SA: Show): Show> ``` Added in v2.0.0 # lifting ## fromOptionK **Signature** ```ts export declare const fromOptionK: ( onNone: LazyArg ) => (f: (...a: A) => Option) => (...a: A) => These ``` Added in v2.10.0 ## fromPredicate **Signature** ```ts export declare const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => These (predicate: Predicate, onFalse: (a: A) => E): (b: B) => These (predicate: Predicate, onFalse: (a: A) => E): (a: A) => These } ``` Added in v2.13.0 # mapping ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: These) => These ``` Added in v2.0.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: These B>) => These ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: These) => These ``` Added in v2.0.0 # model ## Both (interface) **Signature** ```ts export interface Both { readonly _tag: 'Both' readonly left: E readonly right: A } ``` Added in v2.0.0 ## These (type alias) **Signature** ```ts export type These = Either | Both ``` Added in v2.0.0 # pattern matching ## fold Alias of [`match`](#match). **Signature** ```ts export declare const fold: ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (fa: These) => B ``` Added in v2.0.0 ## foldW Alias of [`matchW`](#matchw). **Signature** ```ts export declare const foldW: ( onLeft: (e: E) => B, onRight: (a: A) => C, onBoth: (e: E, a: A) => D ) => (fa: These) => B | C | D ``` Added in v2.10.0 ## match **Signature** ```ts export declare const match: ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (fa: These) => B ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C, onBoth: (e: E, a: A) => D ) => (fa: These) => B | C | D ``` Added in v2.10.0 # refinements ## isBoth Returns `true` if the these is an instance of `Both`, `false` otherwise **Signature** ```ts export declare function isBoth(fa: These): fa is Both ``` Added in v2.0.0 ## isLeft Returns `true` if the these is an instance of `Left`, `false` otherwise **Signature** ```ts export declare const isLeft: (fa: These) => fa is Left ``` Added in v2.0.0 ## isRight Returns `true` if the these is an instance of `Right`, `false` otherwise **Signature** ```ts export declare const isRight: (fa: These) => fa is Right ``` Added in v2.0.0 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence2<'These'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse2<'These'> ``` Added in v2.6.3 ## traverseReadonlyArrayWithIndex Equivalent to `ReadonlyArray#traverseWithIndex(getApplicative(S))`. **Signature** ```ts export declare const traverseReadonlyArrayWithIndex: ( S: Semigroup ) => (f: (index: number, a: A) => These) => (as: readonly A[]) => These ``` Added in v2.11.0 ## traverseReadonlyNonEmptyArrayWithIndex Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(getApplicative(S))`. **Signature** ```ts export declare const traverseReadonlyNonEmptyArrayWithIndex: ( S: Semigroup ) => ( f: (index: number, a: A) => These ) => (as: ReadonlyNonEmptyArray) => These> ``` Added in v2.11.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'These' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ApT **Signature** ```ts export declare const ApT: These ``` Added in v2.11.0 ## elem **Signature** ```ts export declare const elem: (E: Eq) => (a: A) => (ma: These) => boolean ``` Added in v2.11.0 ## exists **Signature** ```ts export declare const exists: (predicate: Predicate) => (ma: These) => boolean ``` Added in v2.11.0 ## swap **Signature** ```ts export declare const swap: (fa: These) => These ``` Added in v2.4.0 # zone of death ## ~~these~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.these` (where `T` is from `import T from 'fp-ts/These'`) **Signature** ```ts export declare const these: Functor2<'These'> & Bifunctor2<'These'> & Foldable2<'These'> & Traversable2<'These'> ``` Added in v2.0.0 ## ~~toTuple~~ Use [`toTuple2`](#totuple2) instead. **Signature** ```ts export declare const toTuple: (e: E, a: A) => (fa: These) => [E, A] ``` Added in v2.0.0 ================================================ FILE: docs/modules/TheseT.ts.md ================================================ --- title: TheseT.ts nav_order: 110 parent: Modules --- ## TheseT overview Added in v2.4.0 ---

Table of contents

- [utils](#utils) - [ap](#ap) - [bimap](#bimap) - [both](#both) - [chain](#chain) - [left](#left) - [leftF](#leftf) - [map](#map) - [mapLeft](#mapleft) - [match](#match) - [matchE](#matche) - [right](#right) - [rightF](#rightf) - [swap](#swap) - [toTuple2](#totuple2) - [zone of death](#zone-of-death) - [~~TheseM1~~ (interface)](#thesem1-interface) - [~~TheseM2~~ (interface)](#thesem2-interface) - [~~TheseM~~ (interface)](#thesem-interface) - [~~TheseT1~~ (type alias)](#theset1-type-alias) - [~~TheseT2~~ (type alias)](#theset2-type-alias) - [~~TheseT~~ (interface)](#theset-interface) - [~~getTheseM~~](#getthesem) --- # utils ## ap **Signature** ```ts export declare function ap( F: Apply3, S: Semigroup ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply3C, S: Semigroup ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export declare function ap( F: Apply2, S: Semigroup ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply2C, S: Semigroup ):
(fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export declare function ap( F: Apply1, S: Semigroup ): (fa: Kind>) => (fab: Kind B>>) => Kind> export declare function ap( F: Apply, S: Semigroup ): (fa: HKT>) => (fab: HKT B>>) => HKT> ``` Added in v2.10.0 ## bimap **Signature** ```ts export declare function bimap( F: Functor3 ): ( f: (e: E) => G, g: (a: A) => B ) => (fea: Kind3>) => Kind3> export declare function bimap( F: Functor3C ): ( f: (e: E) => G, g: (a: A) => B ) => (fea: Kind3>) => Kind3> export declare function bimap( F: Functor2 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2>) => Kind2> export declare function bimap( F: Functor2C ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2>) => Kind2> export declare function bimap( F: Functor1 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind>) => Kind> export declare function bimap( F: Functor ): (f: (e: E) => G, g: (a: A) => B) => (fea: HKT>) => HKT> ``` Added in v2.10.0 ## both **Signature** ```ts export declare function both(F: Pointed3): (e: E, a: A) => Kind3> export declare function both(F: Pointed3C): (e: E, a: A) => Kind3> export declare function both(F: Pointed2): (e: E, a: A) => Kind2> export declare function both(F: Pointed2C): (e: E, a: A) => Kind2> export declare function both(F: Pointed1): (e: E, a: A) => Kind> export declare function both(F: Pointed): (e: E, a: A) => HKT> ``` Added in v2.10.0 ## chain **Signature** ```ts export declare function chain( M: Monad3, S: Semigroup ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function chain( M: Monad3C, S: Semigroup ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export declare function chain( M: Monad2, S: Semigroup ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export declare function chain( M: Monad2C, S: Semigroup ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export declare function chain( M: Monad1, S: Semigroup ): (f: (a: A) => Kind>) => (ma: Kind>) => Kind> export declare function chain( M: Monad, S: Semigroup ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> ``` Added in v2.10.0 ## left **Signature** ```ts export declare function left( F: Pointed3 ): (e: E) => Kind3> export declare function left( F: Pointed3C ): (e: E) => Kind3> export declare function left(F: Pointed2): (e: E) => Kind2> export declare function left( F: Pointed2C ): (e: E) => Kind2> export declare function left(F: Pointed1): (e: E) => Kind> export declare function left(F: Pointed): (e: E) => HKT> ``` Added in v2.10.0 ## leftF **Signature** ```ts export declare function leftF( F: Functor3 ): (fe: Kind3) => Kind3> export declare function leftF( F: Functor3C ): (fe: Kind3) => Kind3> export declare function leftF( F: Functor2 ): (fe: Kind2) => Kind2> export declare function leftF( F: Functor2C ): (fe: Kind2) => Kind2> export declare function leftF(F: Functor1): (fe: Kind) => Kind> export declare function leftF(F: Functor): (fe: HKT) => HKT> ``` Added in v2.10.0 ## map **Signature** ```ts export declare function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export declare function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export declare function map( F: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export declare function map( F: Functor ): (f: (a: A) => B) => (fa: HKT>) => HKT> ``` Added in v2.10.0 ## mapLeft **Signature** ```ts export declare function mapLeft( F: Functor3 ): (f: (e: E) => G) => (fea: Kind3>) => Kind3> export declare function mapLeft( F: Functor3C ): (f: (e: E) => G) => (fea: Kind3>) => Kind3> export declare function mapLeft( F: Functor2 ): (f: (e: E) => G) => (fea: Kind2>) => Kind2> export declare function mapLeft( F: Functor2C ): (f: (e: E) => G) => (fea: Kind2>) => Kind2> export declare function mapLeft( F: Functor1 ): (f: (e: E) => G) => (fea: Kind>) => Kind> export declare function mapLeft( F: Functor ): (f: (e: E) => G) => (fea: HKT>) => HKT> ``` Added in v2.10.0 ## match **Signature** ```ts export declare function match( F: Functor3 ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind3>) => Kind3 export declare function match( F: Functor3C ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind3>) => Kind3 export declare function match( F: Functor2 ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind2>) => Kind2 export declare function match( F: Functor2C ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind2>) => Kind2 export declare function match( F: Functor1 ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind>) => Kind export declare function match( F: Functor ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: HKT>) => HKT ``` Added in v2.10.0 ## matchE **Signature** ```ts export declare function matchE( M: Chain3 ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3, onBoth: (e: E, a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export declare function matchE( M: Chain3C ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3, onBoth: (e: E, a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export declare function matchE( M: Chain2 ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2, onBoth: (e: E, a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export declare function matchE( M: Chain2C ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2, onBoth: (e: E, a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export declare function matchE( M: Chain1 ): ( onLeft: (e: E) => Kind, onRight: (a: A) => Kind, onBoth: (e: E, a: A) => Kind ) => (ma: Kind>) => Kind export declare function matchE( M: Chain ): ( onLeft: (e: E) => HKT, onRight: (a: A) => HKT, onBoth: (e: E, a: A) => HKT ) => (ma: HKT>) => HKT ``` Added in v2.10.0 ## right **Signature** ```ts export declare function right( F: Pointed3 ): (a: A) => Kind3> export declare function right( F: Pointed3C ): (a: A) => Kind3> export declare function right(F: Pointed2): (a: A) => Kind2> export declare function right( F: Pointed2C ): (a: A) => Kind2> export declare function right(F: Pointed1): (a: A) => Kind> export declare function right(F: Pointed): (a: A) => HKT> ``` Added in v2.10.0 ## rightF **Signature** ```ts export declare function rightF( F: Functor3 ): (fa: Kind3) => Kind3> export declare function rightF( F: Functor3C ): (fa: Kind3) => Kind3> export declare function rightF( F: Functor2 ): (fa: Kind2) => Kind2> export declare function rightF( F: Functor2C ): (fa: Kind2) => Kind2> export declare function rightF(F: Functor1): (fa: Kind) => Kind> export declare function rightF(F: Functor): (fa: HKT) => HKT> ``` Added in v2.10.0 ## swap **Signature** ```ts export declare function swap( F: Functor3 ): (ma: Kind3>) => Kind3> export declare function swap( F: Functor3C ): (ma: Kind3>) => Kind3> export declare function swap( F: Functor2 ): (ma: Kind2>) => Kind2> export declare function swap( F: Functor2C ): (ma: Kind2>) => Kind2> export declare function swap(F: Functor1): (ma: Kind>) => Kind> export declare function swap(F: Functor): (ma: HKT>) => HKT> ``` Added in v2.10.0 ## toTuple2 **Signature** ```ts export declare function toTuple2( F: Functor3 ): (e: LazyArg, a: LazyArg) => (fa: Kind3>) => Kind3 export declare function toTuple2( F: Functor3C ): (e: LazyArg, a: LazyArg) => (fa: Kind3>) => Kind3 export declare function toTuple2( F: Functor2 ): (e: LazyArg, a: LazyArg) => (fa: Kind2>) => Kind2 export declare function toTuple2( F: Functor2C ): (e: LazyArg, a: LazyArg) => (fa: Kind2>) => Kind2 export declare function toTuple2( F: Functor1 ): (e: LazyArg, a: LazyArg) => (fa: Kind>) => Kind export declare function toTuple2( F: Functor ): (e: LazyArg, a: LazyArg) => (fa: HKT>) => HKT ``` Added in v2.10.0 # zone of death ## ~~TheseM1~~ (interface) **Signature** ```ts export interface TheseM1 { readonly map: (fa: TheseT1, f: (a: A) => B) => TheseT1 readonly bimap: (fa: TheseT1, f: (e: E) => N, g: (a: A) => B) => TheseT1 readonly mapLeft: (fa: TheseT1, f: (e: E) => N) => TheseT1 readonly fold: ( fa: TheseT1, onLeft: (e: E) => Kind, onRight: (a: A) => Kind, onBoth: (e: E, a: A) => Kind ) => Kind readonly swap: (fa: TheseT1) => TheseT1 readonly rightM: (ma: Kind) => TheseT1 readonly leftM: (me: Kind) => TheseT1 readonly left: (e: E) => TheseT1 readonly right: (a: A) => TheseT1 readonly both: (e: E, a: A) => TheseT1 readonly toTuple: (fa: TheseT1, e: E, a: A) => Kind readonly getMonad: (S: Semigroup) => { readonly _E: E readonly map: (ma: TheseT1, f: (a: A) => B) => TheseT1 readonly of: (a: A) => TheseT1 readonly ap: (mab: TheseT1 B>, ma: TheseT1) => TheseT1 readonly chain: (ma: TheseT1, f: (a: A) => TheseT1) => TheseT1 } } ``` Added in v2.4.0 ## ~~TheseM2~~ (interface) **Signature** ```ts export interface TheseM2 { readonly map: (fa: TheseT2, f: (a: A) => B) => TheseT2 readonly bimap: (fa: TheseT2, f: (e: E) => N, g: (a: A) => B) => TheseT2 readonly mapLeft: (fa: TheseT2, f: (e: E) => N) => TheseT2 readonly fold: ( fa: TheseT2, onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2, onBoth: (e: E, a: A) => Kind2 ) => Kind2 readonly swap: (fa: TheseT2) => TheseT2 readonly rightM: (ma: Kind2) => TheseT2 readonly leftM: (me: Kind2) => TheseT2 readonly left: (e: E) => TheseT2 readonly right: (a: A) => TheseT2 readonly both: (e: E, a: A) => TheseT2 readonly toTuple: (fa: TheseT2, e: E, a: A) => Kind2 readonly getMonad: (S: Semigroup) => { readonly _E: E readonly map: (ma: TheseT2, f: (a: A) => B) => TheseT2 readonly of: (a: A) => TheseT2 readonly ap: (mab: TheseT2 B>, ma: TheseT2) => TheseT2 readonly chain: (ma: TheseT2, f: (a: A) => TheseT2) => TheseT2 } } ``` Added in v2.4.0 ## ~~TheseM~~ (interface) **Signature** ```ts export interface TheseM { readonly map: (fa: TheseT, f: (a: A) => B) => TheseT readonly bimap: (fa: TheseT, f: (e: E) => N, g: (a: A) => B) => TheseT readonly mapLeft: (fa: TheseT, f: (e: E) => N) => TheseT readonly fold: ( fa: TheseT, onLeft: (e: E) => HKT, onRight: (a: A) => HKT, onBoth: (e: E, a: A) => HKT ) => HKT readonly swap: (fa: TheseT) => TheseT readonly rightM: (ma: HKT) => TheseT readonly leftM: (me: HKT) => TheseT readonly left: (e: E) => TheseT readonly right: (a: A) => TheseT readonly both: (e: E, a: A) => TheseT readonly toTuple: (fa: TheseT, e: E, a: A) => HKT readonly getMonad: (S: Semigroup) => { readonly _E: E readonly map: (ma: TheseT, f: (a: A) => B) => TheseT readonly of: (a: A) => TheseT readonly ap: (mab: TheseT B>, ma: TheseT) => TheseT readonly chain: (ma: TheseT, f: (a: A) => TheseT) => TheseT } } ``` Added in v2.4.0 ## ~~TheseT1~~ (type alias) **Signature** ```ts export type TheseT1 = Kind> ``` Added in v2.4.0 ## ~~TheseT2~~ (type alias) **Signature** ```ts export type TheseT2 = Kind2> ``` Added in v2.4.0 ## ~~TheseT~~ (interface) **Signature** ```ts export interface TheseT extends HKT> {} ``` Added in v2.4.0 ## ~~getTheseM~~ **Signature** ```ts export declare function getTheseM(M: Monad2): TheseM2 export declare function getTheseM(M: Monad1): TheseM1 export declare function getTheseM(M: Monad): TheseM ``` Added in v2.4.0 ================================================ FILE: docs/modules/Traced.ts.md ================================================ --- title: Traced.ts nav_order: 111 parent: Modules --- ## Traced overview Added in v2.0.0 ---

Table of contents

- [instances](#instances) - [Functor](#functor) - [getComonad](#getcomonad) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [Traced (interface)](#traced-interface) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [censor](#censor) - [listen](#listen) - [listens](#listens) - [tracks](#tracks) - [zone of death](#zone-of-death) - [~~traced~~](#traced) --- # instances ## Functor **Signature** ```ts export declare const Functor: Functor2<'Traced'> ``` Added in v2.7.0 ## getComonad **Signature** ```ts export declare function getComonad

(monoid: Monoid

): Comonad2C ``` Added in v2.0.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Traced B>) => Traced ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Traced) => Traced ``` Added in v2.0.0 # model ## Traced (interface) **Signature** ```ts export interface Traced { (p: P): A } ``` Added in v2.0.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Traced' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## censor Apply a function to the current position **Signature** ```ts export declare function censor

(f: (p: P) => P): (wa: Traced) => Traced ``` Added in v2.0.0 ## listen Get the current position **Signature** ```ts export declare function listen(wa: Traced): Traced ``` Added in v2.0.0 ## listens Get a value which depends on the current position **Signature** ```ts export declare function listens(f: (p: P) => B): (wa: Traced) => Traced ``` Added in v2.0.0 ## tracks Extracts a value at a relative position which depends on the current value. **Signature** ```ts export declare function tracks(M: Monoid

, f: (a: A) => P): (wa: Traced) => A ``` Added in v2.0.0 # zone of death ## ~~traced~~ Use [`Functor`](#functor) instead. **Signature** ```ts export declare const traced: Functor2<'Traced'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Traversable.ts.md ================================================ --- title: Traversable.ts nav_order: 112 parent: Modules --- ## Traversable overview `Traversable` represents data structures which can be _traversed_ accumulating results and effects in some `Applicative` functor. - `traverse` runs an action for every element in a data structure, and accumulates the results. - `sequence` runs the actions _contained_ in a data structure, and accumulates the results. The `traverse` and `sequence` functions should be compatible in the following sense: - `traverse(A)(xs, f) <-> sequence(A)(A.map(xs, f))` - `sequence(A)(xs) <-> traverse(A)(xs, identity)` where `A` is an `Applicative` instance `Traversable` instances should also be compatible with the corresponding `Foldable` instances, in the following sense: ```ts import { getApplicative, make } from 'fp-ts/Const' const A = getApplicative(M) foldMap(M)(xs, f) = traverse(A)(xs, (a) => make(f(a))) ``` where `M` is a `Monoid` instance Added in v2.0.0 ---

Table of contents

- [model](#model) - [Traversable (interface)](#traversable-interface) - [Traversable1 (interface)](#traversable1-interface) - [Traversable2 (interface)](#traversable2-interface) - [Traversable2C (interface)](#traversable2c-interface) - [Traversable3 (interface)](#traversable3-interface) - [utils](#utils) - [PipeableTraverse1 (interface)](#pipeabletraverse1-interface) - [PipeableTraverse2 (interface)](#pipeabletraverse2-interface) - [Sequence (interface)](#sequence-interface) - [Sequence1 (interface)](#sequence1-interface) - [Sequence2 (interface)](#sequence2-interface) - [Sequence2C (interface)](#sequence2c-interface) - [Sequence3 (interface)](#sequence3-interface) - [Traverse (interface)](#traverse-interface) - [Traverse1 (interface)](#traverse1-interface) - [Traverse2 (interface)](#traverse2-interface) - [Traverse2C (interface)](#traverse2c-interface) - [Traverse3 (interface)](#traverse3-interface) - [sequence](#sequence) - [traverse](#traverse) - [zone of death](#zone-of-death) - [~~SequenceComposition11~~ (interface)](#sequencecomposition11-interface) - [~~TraversableComposition11~~ (interface)](#traversablecomposition11-interface) - [~~TraversableComposition~~ (interface)](#traversablecomposition-interface) - [~~TraverseComposition11~~ (interface)](#traversecomposition11-interface) - [~~getTraversableComposition~~](#gettraversablecomposition) --- # model ## Traversable (interface) **Signature** ```ts export interface Traversable extends Functor, Foldable { /** * Runs an action for every element in a data structure and accumulates the results */ readonly traverse: Traverse readonly sequence: Sequence } ``` Added in v2.0.0 ## Traversable1 (interface) **Signature** ```ts export interface Traversable1 extends Functor1, Foldable1 { readonly traverse: Traverse1 readonly sequence: Sequence1 } ``` Added in v2.0.0 ## Traversable2 (interface) **Signature** ```ts export interface Traversable2 extends Functor2, Foldable2 { readonly traverse: Traverse2 readonly sequence: Sequence2 } ``` Added in v2.0.0 ## Traversable2C (interface) **Signature** ```ts export interface Traversable2C extends Functor2C, Foldable2C { readonly traverse: Traverse2C readonly sequence: Sequence2C } ``` Added in v2.0.0 ## Traversable3 (interface) **Signature** ```ts export interface Traversable3 extends Functor3, Foldable3 { readonly traverse: Traverse3 readonly sequence: Sequence3 } ``` Added in v2.0.0 # utils ## PipeableTraverse1 (interface) **Signature** ```ts export interface PipeableTraverse1 { (F: Applicative3): ( f: (a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative3C): ( f: (a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative1): (f: (a: A) => Kind) => (ta: Kind) => Kind> (F: Applicative): (f: (a: A) => HKT) => (ta: Kind) => HKT> } ``` Added in v2.6.3 ## PipeableTraverse2 (interface) **Signature** ```ts export interface PipeableTraverse2 { (F: Applicative3): ( f: (a: A) => Kind3 ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (a: A) => Kind ) => (ta: Kind2) => Kind> (F: Applicative): (f: (a: A) => HKT) => (ta: Kind2) => HKT> } ``` Added in v2.6.3 ## Sequence (interface) **Signature** ```ts export interface Sequence { (F: Applicative4): (ta: HKT>) => Kind4> (F: Applicative3): (ta: HKT>) => Kind3> (F: Applicative3C): (ta: HKT>) => Kind3> (F: Applicative2): (ta: HKT>) => Kind2> (F: Applicative2C): (ta: HKT>) => Kind2> (F: Applicative1): (ta: HKT>) => Kind> (F: Applicative): (ta: HKT>) => HKT> } ``` Added in v2.0.0 ## Sequence1 (interface) **Signature** ```ts export interface Sequence1 { (F: Applicative4): ( ta: Kind> ) => Kind4> (F: Applicative3): (ta: Kind>) => Kind3> (F: Applicative3C): (ta: Kind>) => Kind3> (F: Applicative2): (ta: Kind>) => Kind2> (F: Applicative2C): (ta: Kind>) => Kind2> (F: Applicative1): (ta: Kind>) => Kind> (F: Applicative): (ta: Kind>) => HKT> } ``` Added in v2.0.0 ## Sequence2 (interface) **Signature** ```ts export interface Sequence2 { (F: Applicative4): ( ta: Kind2> ) => Kind4> (F: Applicative3): ( ta: Kind2> ) => Kind3> (F: Applicative3C): ( ta: Kind2> ) => Kind3> (F: Applicative2): (ta: Kind2>) => Kind2> (F: Applicative2C): ( ta: Kind2> ) => Kind2> (F: Applicative1): (ta: Kind2>) => Kind> (F: Applicative): (ta: Kind2>) => HKT> } ``` Added in v2.0.0 ## Sequence2C (interface) **Signature** ```ts export interface Sequence2C { (F: Applicative4): ( ta: Kind2> ) => Kind4> (F: Applicative3): ( ta: Kind2> ) => Kind3> (F: Applicative3C): ( ta: Kind2> ) => Kind3> (F: Applicative2): (ta: Kind2>) => Kind2> (F: Applicative2C): (ta: Kind2>) => Kind2> (F: Applicative1): (ta: Kind2>) => Kind> (F: Applicative): (ta: Kind2>) => HKT> } ``` Added in v2.0.0 ## Sequence3 (interface) **Signature** ```ts export interface Sequence3 { (F: Applicative4): ( ta: Kind3> ) => Kind4> (F: Applicative3): ( ta: Kind3> ) => Kind3> (F: Applicative3C): ( ta: Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind3> ) => Kind2> (F: Applicative2C): ( ta: Kind3> ) => Kind2> (F: Applicative1): (ta: Kind3>) => Kind> (F: Applicative): (ta: Kind3>) => HKT> } ``` Added in v2.0.0 ## Traverse (interface) **Signature** ```ts export interface Traverse { (F: Applicative4): ( ta: HKT, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: HKT, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: HKT, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): (ta: HKT, f: (a: A) => Kind2) => Kind2> (F: Applicative2C): ( ta: HKT, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: HKT, f: (a: A) => Kind) => Kind> (F: Applicative): (ta: HKT, f: (a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## Traverse1 (interface) **Signature** ```ts export interface Traverse1 { (F: Applicative4): ( ta: Kind, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: Kind, f: (a: A) => Kind) => Kind> (F: Applicative): (ta: Kind, f: (a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## Traverse2 (interface) **Signature** ```ts export interface Traverse2 { (F: Applicative4): ( ta: Kind2, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## Traverse2C (interface) **Signature** ```ts export interface Traverse2C { (F: Applicative4): ( ta: Kind2, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: Kind2, f: (a: A) => Kind) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## Traverse3 (interface) **Signature** ```ts export interface Traverse3 { (F: Applicative4): ( ta: Kind3, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind3, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind3, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind3, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind3, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind3, f: (a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind3, f: (a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## sequence `sequence` composition. **Signature** ```ts export declare function sequence( T: Traversable1, G: Traversable2 ): { (F: Applicative4): ( tgfa: Kind>> ) => Kind4>> (F: Applicative3): ( tgfa: Kind>> ) => Kind3>> (F: Applicative3C): ( tgfa: Kind>> ) => Kind3>> (F: Applicative2): ( tgfa: Kind>> ) => Kind2>> (F: Applicative2C): ( tgfa: Kind>> ) => Kind2>> (F: Applicative1): ( tgfa: Kind>> ) => Kind>> (F: Applicative): (tgfa: HKT>>) => HKT>> } export declare function sequence( T: Traversable1, G: Traversable1 ): { (F: Applicative4): ( tgfa: Kind>> ) => Kind4>> (F: Applicative3): ( tgfa: Kind>> ) => Kind3>> (F: Applicative3C): ( tgfa: Kind>> ) => Kind3>> (F: Applicative2): ( tgfa: Kind>> ) => Kind2>> (F: Applicative2C): ( tgfa: Kind>> ) => Kind2>> (F: Applicative1): (tgfa: Kind>>) => Kind>> (F: Applicative): (tgfa: HKT>>) => HKT>> } export declare function sequence( T: Traversable, G: Traversable ): (F: Applicative) => (tgfa: HKT>>) => HKT>> ``` Added in v2.10.0 ## traverse `traverse` composition. **Signature** ```ts export declare function traverse( T: Traversable1, G: Traversable2 ): { (F: Applicative4): ( f: (a: A) => Kind4 ) => (tga: Kind>) => Kind4>> (F: Applicative3): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative3C): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative2): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative1): ( f: (a: A) => Kind ) => (tga: Kind>) => Kind>> (F: Applicative): ( f: (a: A) => HKT ) => (tga: Kind>) => HKT>> } export declare function traverse( T: Traversable1, G: Traversable1 ): { (F: Applicative4): ( f: (a: A) => Kind4 ) => (tga: Kind>) => Kind4>> (F: Applicative3): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative3C): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative2): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative1): ( f: (a: A) => Kind ) => (tga: Kind>) => Kind>> (F: Applicative): (f: (a: A) => HKT) => (tga: Kind>) => HKT>> } export declare function traverse( T: Traversable, G: Traversable ): (F: Applicative) => (f: (a: A) => HKT) => (tga: HKT>) => HKT>> ``` Added in v2.10.0 # zone of death ## ~~SequenceComposition11~~ (interface) **Signature** ```ts export interface SequenceComposition11 { (H: Applicative3): ( fga: Kind>> ) => Kind3>> (H: Applicative2): ( fga: Kind>> ) => Kind2>> (H: Applicative2C): ( fga: Kind>> ) => Kind2>> (H: Applicative1): (fga: Kind>>) => Kind>> (H: Applicative): (fga: Kind>>) => HKT>> } ``` Added in v2.0.0 ## ~~TraversableComposition11~~ (interface) **Signature** ```ts export interface TraversableComposition11 extends FoldableComposition11, FunctorComposition11 { readonly traverse: TraverseComposition11 readonly sequence: SequenceComposition11 } ``` Added in v2.0.0 ## ~~TraversableComposition~~ (interface) **Signature** ```ts export interface TraversableComposition extends FoldableComposition, FunctorComposition { readonly traverse: ( H: Applicative ) => (fga: HKT>, f: (a: A) => HKT) => HKT>> readonly sequence: (H: Applicative) => (fga: HKT>>) => HKT>> } ``` Added in v2.0.0 ## ~~TraverseComposition11~~ (interface) **Signature** ```ts export interface TraverseComposition11 { (H: Applicative3): ( fga: Kind>, f: (a: A) => Kind3 ) => Kind3>> (H: Applicative2): ( fga: Kind>, f: (a: A) => Kind2 ) => Kind2>> (H: Applicative2C): ( fga: Kind>, f: (a: A) => Kind2 ) => Kind2>> (H: Applicative1): ( fga: Kind>, f: (a: A) => Kind ) => Kind>> (H: Applicative): (fga: Kind>, f: (a: A) => HKT) => HKT>> } ``` Added in v2.0.0 ## ~~getTraversableComposition~~ Use - [`traverse`](#traverse) - [`sequence`](#sequence) instead. **Signature** ```ts export declare function getTraversableComposition( F: Traversable1, G: Traversable1 ): TraversableComposition11 export declare function getTraversableComposition( F: Traversable, G: Traversable ): TraversableComposition ``` Added in v2.0.0 ================================================ FILE: docs/modules/TraversableWithIndex.ts.md ================================================ --- title: TraversableWithIndex.ts nav_order: 113 parent: Modules --- ## TraversableWithIndex overview A `Traversable` with an additional index. A `TraversableWithIndex` instance must be compatible with its `Traversable` instance ```ts traverse(F)(ta, f) = traverseWithIndex(F)(ta, (_, a) => f(a)) ``` with its `FoldableWithIndex` instance ```ts foldMapWithIndex(M)(ta, f) = traverseWithIndex(getApplicative(M))(ta, (i, a) => new Const(f(i, a))).value ``` and with its `FunctorWithIndex` instance ```purescript mapWithIndex(ta, f) = traverseWithIndex(identity)(ta, (i, a) => new Identity(f(i, a))).value ``` Added in v2.0.0 ---

Table of contents

- [utils](#utils) - [PipeableTraverseWithIndex1 (interface)](#pipeabletraversewithindex1-interface) - [PipeableTraverseWithIndex2 (interface)](#pipeabletraversewithindex2-interface) - [TraversableWithIndex (interface)](#traversablewithindex-interface) - [TraversableWithIndex1 (interface)](#traversablewithindex1-interface) - [TraversableWithIndex2 (interface)](#traversablewithindex2-interface) - [TraversableWithIndex2C (interface)](#traversablewithindex2c-interface) - [TraverseWithIndex (interface)](#traversewithindex-interface) - [TraverseWithIndex1 (interface)](#traversewithindex1-interface) - [TraverseWithIndex2 (interface)](#traversewithindex2-interface) - [TraverseWithIndex2C (interface)](#traversewithindex2c-interface) --- # utils ## PipeableTraverseWithIndex1 (interface) **Signature** ```ts export interface PipeableTraverseWithIndex1 { (F: Applicative3): ( f: (i: I, a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative3C): ( f: (i: I, a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative2): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative2C): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative1): (f: (i: I, a: A) => Kind) => (ta: Kind) => Kind> (F: Applicative): (f: (i: I, a: A) => HKT) => (ta: Kind) => HKT> } ``` Added in v2.6.3 ## PipeableTraverseWithIndex2 (interface) **Signature** ```ts export interface PipeableTraverseWithIndex2 { (F: Applicative3): ( f: (i: I, a: A) => Kind3 ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (i: I, a: A) => Kind ) => (ta: Kind2) => Kind> (F: Applicative): (f: (i: I, a: A) => HKT) => (ta: Kind2) => HKT> } ``` Added in v2.6.3 ## TraversableWithIndex (interface) **Signature** ```ts export interface TraversableWithIndex extends FunctorWithIndex, FoldableWithIndex, Traversable { readonly traverseWithIndex: TraverseWithIndex } ``` Added in v2.0.0 ## TraversableWithIndex1 (interface) **Signature** ```ts export interface TraversableWithIndex1 extends FunctorWithIndex1, FoldableWithIndex1, Traversable1 { readonly traverseWithIndex: TraverseWithIndex1 } ``` Added in v2.0.0 ## TraversableWithIndex2 (interface) **Signature** ```ts export interface TraversableWithIndex2 extends FunctorWithIndex2, FoldableWithIndex2, Traversable2 { readonly traverseWithIndex: TraverseWithIndex2 } ``` Added in v2.0.0 ## TraversableWithIndex2C (interface) **Signature** ```ts export interface TraversableWithIndex2C extends FunctorWithIndex2C, FoldableWithIndex2C, Traversable2C { readonly traverseWithIndex: TraverseWithIndex2C } ``` Added in v2.0.0 ## TraverseWithIndex (interface) **Signature** ```ts export interface TraverseWithIndex { (F: Applicative3): ( ta: HKT, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: HKT, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: HKT, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: HKT, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: HKT, f: (i: I, a: A) => Kind) => Kind> (F: Applicative): (ta: HKT, f: (i: I, a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## TraverseWithIndex1 (interface) **Signature** ```ts export interface TraverseWithIndex1 { (F: Applicative3): ( ta: Kind, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: Kind, f: (i: I, a: A) => Kind) => Kind> (F: Applicative): (ta: Kind, f: (i: I, a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## TraverseWithIndex2 (interface) **Signature** ```ts export interface TraverseWithIndex2 { (F: Applicative3): ( ta: Kind2, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (i: I, a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind2, f: (i: I, a: A) => HKT) => HKT> } ``` Added in v2.0.0 ## TraverseWithIndex2C (interface) **Signature** ```ts export interface TraverseWithIndex2C { (F: Applicative3): ( ta: Kind2, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind2, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (i: I, a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind2, f: (i: I, a: A) => HKT) => HKT> } ``` Added in v2.0.0 ================================================ FILE: docs/modules/Tree.ts.md ================================================ --- title: Tree.ts nav_order: 114 parent: Modules --- ## Tree overview Multi-way trees (aka rose trees) and forests, where a forest is ```ts type Forest
= Array> ``` Added in v2.0.0 ---

Table of contents

- [Extract](#extract) - [extract](#extract) - [constructors](#constructors) - [make](#make) - [of](#of) - [unfoldForest](#unfoldforest) - [unfoldForestM](#unfoldforestm) - [unfoldTree](#unfoldtree) - [unfoldTreeM](#unfoldtreem) - [do notation](#do-notation) - [Do](#do) - [apS](#aps) - [bind](#bind) - [bindTo](#bindto) - [let](#let) - [folding](#folding) - [fold](#fold) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Applicative](#applicative) - [Apply](#apply) - [Chain](#chain) - [Comonad](#comonad) - [Foldable](#foldable) - [Functor](#functor) - [Monad](#monad) - [Pointed](#pointed) - [Traversable](#traversable) - [getEq](#geteq) - [getShow](#getshow) - [legacy](#legacy) - [chain](#chain) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [Forest (type alias)](#forest-type-alias) - [Tree (interface)](#tree-interface) - [sequencing](#sequencing) - [flatMap](#flatmap) - [flatten](#flatten) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [ap](#ap) - [apFirst](#apfirst) - [apSecond](#apsecond) - [chainFirst](#chainfirst) - [drawForest](#drawforest) - [drawTree](#drawtree) - [duplicate](#duplicate) - [elem](#elem) - [exists](#exists) - [extend](#extend) - [zone of death](#zone-of-death) - [~~tree~~](#tree) --- # Extract ## extract **Signature** ```ts export declare const extract:
(wa: Tree) => A ``` Added in v2.6.2 # constructors ## make **Signature** ```ts export declare function make(value: A, forest: Forest = []): Tree ``` Added in v2.0.0 ## of **Signature** ```ts export declare const of: (a: A) => Tree ``` Added in v2.7.0 ## unfoldForest Build a (possibly infinite) forest from a list of seed values in breadth-first order. **Signature** ```ts export declare function unfoldForest(bs: Array, f: (b: B) => [A, Array]): Forest ``` Added in v2.0.0 ## unfoldForestM Monadic forest builder, in depth-first order **Signature** ```ts export declare function unfoldForestM( M: Monad4 ): (bs: Array, f: (b: B) => Kind4]>) => Kind4> export declare function unfoldForestM( M: Monad3 ): (bs: Array, f: (b: B) => Kind3]>) => Kind3> export declare function unfoldForestM( M: Monad3C ): (bs: Array, f: (b: B) => Kind3]>) => Kind3> export declare function unfoldForestM( M: Monad2 ): (bs: Array, f: (b: B) => Kind2]>) => Kind2> export declare function unfoldForestM( M: Monad2C ): (bs: Array, f: (b: B) => Kind2]>) => Kind2> export declare function unfoldForestM( M: Monad1 ): (bs: Array, f: (b: B) => Kind]>) => Kind> export declare function unfoldForestM( M: MonadHKT ): (bs: Array, f: (b: B) => HKT]>) => HKT> ``` Added in v2.0.0 ## unfoldTree Build a (possibly infinite) tree from a seed value in breadth-first order. **Signature** ```ts export declare function unfoldTree(b: B, f: (b: B) => [A, Array]): Tree ``` Added in v2.0.0 ## unfoldTreeM Monadic tree builder, in depth-first order **Signature** ```ts export declare function unfoldTreeM( M: Monad4 ): (b: B, f: (b: B) => Kind4]>) => Kind4> export declare function unfoldTreeM( M: Monad3 ): (b: B, f: (b: B) => Kind3]>) => Kind3> export declare function unfoldTreeM( M: Monad3C ): (b: B, f: (b: B) => Kind3]>) => Kind3> export declare function unfoldTreeM( M: Monad2 ): (b: B, f: (b: B) => Kind2]>) => Kind2> export declare function unfoldTreeM( M: Monad2C ): (b: B, f: (b: B) => Kind2]>) => Kind2> export declare function unfoldTreeM( M: Monad1 ): (b: B, f: (b: B) => Kind]>) => Kind> export declare function unfoldTreeM( M: MonadHKT ): (b: B, f: (b: B) => HKT]>) => HKT> ``` Added in v2.0.0 # do notation ## Do **Signature** ```ts export declare const Do: Tree<{}> ``` Added in v2.9.0 ## apS **Signature** ```ts export declare const apS: ( name: Exclude, fb: Tree ) => (fa: Tree) => Tree<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bind **Signature** ```ts export declare const bind: ( name: Exclude, f: (a: A) => Tree ) => (ma: Tree) => Tree<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.8.0 ## bindTo **Signature** ```ts export declare const bindTo: (name: N) => (fa: Tree) => Tree<{ readonly [K in N]: A }> ``` Added in v2.8.0 ## let **Signature** ```ts export declare const let: ( name: Exclude, f: (a: A) => B ) => (fa: Tree) => Tree<{ readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> ``` Added in v2.13.0 # folding ## fold Fold a tree into a "summary" value in depth-first order. For each node in the tree, apply `f` to the `value` and the result of applying `f` to each `forest`. This is also known as the catamorphism on trees. **Signature** ```ts export declare function fold(f: (a: A, bs: Array) => B): (tree: Tree) => B ``` **Example** ```ts import { fold, make } from 'fp-ts/Tree' import { concatAll } from 'fp-ts/Monoid' import { MonoidSum } from 'fp-ts/number' const t = make(1, [make(2), make(3)]) const sum = concatAll(MonoidSum) // Sum the values in a tree: assert.deepStrictEqual(fold((a: number, bs: Array) => a + sum(bs))(t), 6) // Find the maximum value in the tree: assert.deepStrictEqual(fold((a: number, bs: Array) => bs.reduce((b, acc) => Math.max(b, acc), a))(t), 3) // Count the number of leaves in the tree: assert.deepStrictEqual(fold((_: number, bs: Array) => (bs.length === 0 ? 1 : sum(bs)))(t), 2) ``` Added in v2.6.0 ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Tree) => M ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Tree) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Tree) => B ``` Added in v2.0.0 # instances ## Applicative **Signature** ```ts export declare const Applicative: Applicative1<'Tree'> ``` Added in v2.7.0 ## Apply **Signature** ```ts export declare const Apply: Apply1<'Tree'> ``` Added in v2.10.0 ## Chain **Signature** ```ts export declare const Chain: Chain1<'Tree'> ``` Added in v2.10.0 ## Comonad **Signature** ```ts export declare const Comonad: Comonad1<'Tree'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable1<'Tree'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor1<'Tree'> ``` Added in v2.7.0 ## Monad **Signature** ```ts export declare const Monad: Monad1<'Tree'> ``` Added in v2.7.0 ## Pointed **Signature** ```ts export declare const Pointed: Pointed1<'Tree'> ``` Added in v2.10.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable1<'Tree'> ``` Added in v2.7.0 ## getEq **Signature** ```ts export declare function getEq(E: Eq): Eq> ``` Added in v2.0.0 ## getShow **Signature** ```ts export declare function getShow(S: Show): Show> ``` Added in v2.0.0 # legacy ## chain Alias of `flatMap`. **Signature** ```ts export declare const chain: (f: (a: A) => Tree) => (ma: Tree) => Tree ``` Added in v2.0.0 # mapping ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: Tree<(a: A) => B>) => Tree ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Tree) => Tree ``` Added in v2.0.0 # model ## Forest (type alias) **Signature** ```ts export type Forest = Array> ``` Added in v2.0.0 ## Tree (interface) **Signature** ```ts export interface Tree { readonly value: A readonly forest: Forest } ``` Added in v2.0.0 # sequencing ## flatMap **Signature** ```ts export declare const flatMap: { (f: (a: A) => Tree): (ma: Tree) => Tree (ma: Tree, f: (a: A) => Tree): Tree } ``` Added in v2.14.0 ## flatten **Signature** ```ts export declare const flatten: (mma: Tree>) => Tree ``` Added in v2.0.0 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence1<'Tree'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse1<'Tree'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Tree' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## ap **Signature** ```ts export declare const ap: (fa: Tree) => (fab: Tree<(a: A) => B>) => Tree ``` Added in v2.0.0 ## apFirst Combine two effectful actions, keeping only the result of the first. **Signature** ```ts export declare const apFirst: (second: Tree) => (first: Tree) => Tree ``` Added in v2.0.0 ## apSecond Combine two effectful actions, keeping only the result of the second. **Signature** ```ts export declare const apSecond: (second: Tree) => (first: Tree) => Tree ``` Added in v2.0.0 ## chainFirst Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. **Signature** ```ts export declare const chainFirst: (f: (a: A) => Tree) => (first: Tree) => Tree ``` Added in v2.0.0 ## drawForest Neat 2-dimensional drawing of a forest **Signature** ```ts export declare function drawForest(forest: Forest): string ``` Added in v2.0.0 ## drawTree Neat 2-dimensional drawing of a tree **Signature** ```ts export declare function drawTree(tree: Tree): string ``` **Example** ```ts import { make, drawTree } from 'fp-ts/Tree' const fa = make('a', [make('b'), make('c'), make('d', [make('e'), make('f')])]) assert.strictEqual( drawTree(fa), `a ├─ b ├─ c └─ d ├─ e └─ f` ) ``` Added in v2.0.0 ## duplicate **Signature** ```ts export declare const duplicate: (wa: Tree) => Tree> ``` Added in v2.0.0 ## elem **Signature** ```ts export declare function elem(E: Eq): (a: A, fa: Tree) => boolean ``` Added in v2.0.0 ## exists **Signature** ```ts export declare const exists: (predicate: Predicate) => (ma: Tree) => boolean ``` Added in v2.11.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: Tree) => B) => (wa: Tree) => Tree ``` Added in v2.0.0 # zone of death ## ~~tree~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.tree` (where `T` is from `import T from 'fp-ts/Tree'`) **Signature** ```ts export declare const tree: Monad1<'Tree'> & Foldable1<'Tree'> & Traversable1<'Tree'> & Comonad1<'Tree'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Tuple.ts.md ================================================ --- title: Tuple.ts nav_order: 115 parent: Modules --- ## Tuple overview Added in v2.0.0 ---

Table of contents

- [Extract](#extract) - [extract](#extract) - [folding](#folding) - [foldMap](#foldmap) - [reduce](#reduce) - [reduceRight](#reduceright) - [instances](#instances) - [Bifunctor](#bifunctor) - [Comonad](#comonad) - [Foldable](#foldable) - [Functor](#functor) - [Semigroupoid](#semigroupoid) - [Traversable](#traversable) - [getApplicative](#getapplicative) - [getApply](#getapply) - [getChain](#getchain) - [getChainRec](#getchainrec) - [getMonad](#getmonad) - [mapping](#mapping) - [bimap](#bimap) - [flap](#flap) - [mapFst](#mapfst) - [mapSnd](#mapsnd) - [traversing](#traversing) - [sequence](#sequence) - [traverse](#traverse) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [compose](#compose) - [duplicate](#duplicate) - [extend](#extend) - [fst](#fst) - [snd](#snd) - [swap](#swap) - [zone of death](#zone-of-death) - [~~mapLeft~~](#mapleft) - [~~map~~](#map) - [~~tuple~~](#tuple) --- # Extract ## extract **Signature** ```ts export declare const extract: (wa: [A, E]) => A ``` Added in v2.6.2 # folding ## foldMap **Signature** ```ts export declare const foldMap: (M: Monoid) =>
(f: (a: A) => M) => (fa: [A, E]) => M ``` Added in v2.0.0 ## reduce **Signature** ```ts export declare const reduce: (b: B, f: (b: B, a: A) => B) => (fa: [A, E]) => B ``` Added in v2.0.0 ## reduceRight **Signature** ```ts export declare const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: [A, E]) => B ``` Added in v2.0.0 # instances ## Bifunctor **Signature** ```ts export declare const Bifunctor: Bifunctor2<'Tuple'> ``` Added in v2.7.0 ## Comonad **Signature** ```ts export declare const Comonad: Comonad2<'Tuple'> ``` Added in v2.7.0 ## Foldable **Signature** ```ts export declare const Foldable: Foldable2<'Tuple'> ``` Added in v2.7.0 ## Functor **Signature** ```ts export declare const Functor: Functor2<'Tuple'> ``` Added in v2.7.0 ## Semigroupoid **Signature** ```ts export declare const Semigroupoid: Semigroupoid2<'Tuple'> ``` Added in v2.7.0 ## Traversable **Signature** ```ts export declare const Traversable: Traversable2<'Tuple'> ``` Added in v2.7.0 ## getApplicative **Signature** ```ts export declare function getApplicative(M: Monoid): Applicative2C ``` Added in v2.0.0 ## getApply **Signature** ```ts export declare function getApply(S: Semigroup): Apply2C ``` Added in v2.0.0 ## getChain **Signature** ```ts export declare function getChain(S: Semigroup): Chain2C ``` Added in v2.0.0 ## getChainRec **Signature** ```ts export declare function getChainRec(M: Monoid): ChainRec2C ``` Added in v2.0.0 ## getMonad **Signature** ```ts export declare function getMonad(M: Monoid): Monad2C ``` Added in v2.0.0 # mapping ## bimap Map a pair of functions over the two type arguments of the bifunctor. **Signature** ```ts export declare const bimap: (mapSnd: (e: E) => G, mapFst: (a: A) => B) => (fa: [A, E]) => [B, G] ``` Added in v2.0.0 ## flap **Signature** ```ts export declare const flap: (a: A) => (fab: [(a: A) => B, E]) => [B, E] ``` Added in v2.10.0 ## mapFst Map a function over the first component of a `Tuple`. This is the `map` operation of the `Functor` instance. **Signature** ```ts export declare const mapFst: (f: (a: A) => B) => (fa: [A, E]) => [B, E] ``` Added in v2.0.0 ## mapSnd Map a function over the second component of a `Tuple`. This is the `mapLeft` operation of the `Bifunctor` instance. **Signature** ```ts export declare const mapSnd: (f: (e: E) => G) => (fa: [A, E]) => [A, G] ``` Added in v2.10.0 # traversing ## sequence **Signature** ```ts export declare const sequence: Sequence2<'Tuple'> ``` Added in v2.6.3 ## traverse **Signature** ```ts export declare const traverse: PipeableTraverse2<'Tuple'> ``` Added in v2.6.3 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Tuple' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## compose **Signature** ```ts export declare const compose: (ab: [B, A]) => (bc: [C, B]) => [C, A] ``` Added in v2.0.0 ## duplicate **Signature** ```ts export declare const duplicate: (wa: [A, E]) => [[A, E], E] ``` Added in v2.0.0 ## extend **Signature** ```ts export declare const extend: (f: (wa: [A, E]) => B) => (wa: [A, E]) => [B, E] ``` Added in v2.0.0 ## fst **Signature** ```ts export declare const fst: (ea: [A, E]) => A ``` Added in v2.0.0 ## snd **Signature** ```ts export declare const snd: (ea: [A, E]) => E ``` Added in v2.0.0 ## swap **Signature** ```ts export declare const swap: (ea: [A, E]) => [E, A] ``` Added in v2.0.0 # zone of death ## ~~mapLeft~~ Use [`mapSnd`](#mapsnd) instead. **Signature** ```ts export declare const mapLeft: (f: (e: E) => G) => (fa: [A, E]) => [A, G] ``` Added in v2.0.0 ## ~~map~~ Use [`mapFst`](#mapfst) instead. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: [A, E]) => [B, E] ``` Added in v2.0.0 ## ~~tuple~~ This instance is deprecated, use small, specific instances instead. For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.tuple` (where `T` is from `import T from 'fp-ts/Tuple'`) **Signature** ```ts export declare const tuple: Semigroupoid2<'Tuple'> & Bifunctor2<'Tuple'> & Comonad2<'Tuple'> & Foldable2<'Tuple'> & Traversable2<'Tuple'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/Unfoldable.ts.md ================================================ --- title: Unfoldable.ts nav_order: 116 parent: Modules --- ## Unfoldable overview This class identifies data structures which can be _unfolded_, generalizing `unfold` on arrays. Added in v2.0.0 ---

Table of contents

- [model](#model) - [Unfoldable (interface)](#unfoldable-interface) - [Unfoldable1 (interface)](#unfoldable1-interface) - [Unfoldable2 (interface)](#unfoldable2-interface) - [Unfoldable2C (interface)](#unfoldable2c-interface) - [Unfoldable3 (interface)](#unfoldable3-interface) - [Unfoldable3C (interface)](#unfoldable3c-interface) - [Unfoldable4 (interface)](#unfoldable4-interface) --- # model ## Unfoldable (interface) **Signature** ```ts export interface Unfoldable { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => HKT } ``` Added in v2.0.0 ## Unfoldable1 (interface) **Signature** ```ts export interface Unfoldable1 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind } ``` Added in v2.0.0 ## Unfoldable2 (interface) **Signature** ```ts export interface Unfoldable2 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind2 } ``` Added in v2.0.0 ## Unfoldable2C (interface) **Signature** ```ts export interface Unfoldable2C { readonly URI: F readonly _E: E readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind2 } ``` Added in v2.0.0 ## Unfoldable3 (interface) **Signature** ```ts export interface Unfoldable3 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind3 } ``` Added in v2.0.0 ## Unfoldable3C (interface) **Signature** ```ts export interface Unfoldable3C { readonly URI: F readonly _E: E readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind3 } ``` Added in v2.10.0 ## Unfoldable4 (interface) **Signature** ```ts export interface Unfoldable4 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind4 } ``` Added in v2.0.0 ================================================ FILE: docs/modules/ValidationT.ts.md ================================================ --- title: ValidationT.ts nav_order: 117 parent: Modules --- ## ValidationT overview Added in v2.0.0 ---

Table of contents

- [zone of death](#zone-of-death) - [~~ValidationM1~~ (interface)](#validationm1-interface) - [~~ValidationM2~~ (interface)](#validationm2-interface) - [~~ValidationM~~ (interface)](#validationm-interface) - [~~ValidationT1~~ (type alias)](#validationt1-type-alias) - [~~ValidationT2~~ (type alias)](#validationt2-type-alias) - [~~ValidationT~~ (interface)](#validationt-interface) - [~~getValidationM~~](#getvalidationm) --- # zone of death ## ~~ValidationM1~~ (interface) **Signature** ```ts export interface ValidationM1 extends ApplicativeComposition12C { readonly chain: (ma: ValidationT1, f: (a: A) => ValidationT1) => ValidationT1 readonly alt:
(fa: ValidationT1, that: LazyArg>) => ValidationT1 } ``` Added in v2.0.0 ## ~~ValidationM2~~ (interface) **Signature** ```ts export interface ValidationM2 extends ApplicativeComposition22C { readonly chain: ( ma: ValidationT2, f: (a: A) => ValidationT2 ) => ValidationT2 readonly alt: ( fa: ValidationT2, that: LazyArg> ) => ValidationT2 } ``` Added in v2.0.0 ## ~~ValidationM~~ (interface) **Signature** ```ts export interface ValidationM extends ApplicativeCompositionHKT2C { readonly chain: (ma: ValidationT, f: (a: A) => ValidationT) => ValidationT readonly alt: (fa: ValidationT, that: LazyArg>) => ValidationT } ``` Added in v2.0.0 ## ~~ValidationT1~~ (type alias) **Signature** ```ts export type ValidationT1 = Kind> ``` Added in v2.0.0 ## ~~ValidationT2~~ (type alias) **Signature** ```ts export type ValidationT2 = Kind2> ``` Added in v2.0.0 ## ~~ValidationT~~ (interface) **Signature** ```ts export interface ValidationT extends HKT> {} ``` Added in v2.0.0 ## ~~getValidationM~~ Use `EitherT` instead. **Signature** ```ts export declare function getValidationM(S: Semigroup, M: Monad2): ValidationM2 export declare function getValidationM(S: Semigroup, M: Monad1): ValidationM1 export declare function getValidationM(S: Semigroup, M: Monad): ValidationM ``` Added in v2.0.0 ================================================ FILE: docs/modules/Witherable.ts.md ================================================ --- title: Witherable.ts nav_order: 119 parent: Modules --- ## Witherable overview `Witherable` represents data structures which can be _partitioned_ with effects in some `Applicative` functor. Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Witherable.purs Added in v2.0.0 ---

Table of contents

- [defaults](#defaults) - [wiltDefault](#wiltdefault) - [witherDefault](#witherdefault) - [model](#model) - [Witherable (interface)](#witherable-interface) - [Witherable1 (interface)](#witherable1-interface) - [Witherable2 (interface)](#witherable2-interface) - [Witherable2C (interface)](#witherable2c-interface) - [Witherable3 (interface)](#witherable3-interface) - [utils](#utils) - [FilterE1 (interface)](#filtere1-interface) - [PipeableWilt (interface)](#pipeablewilt-interface) - [PipeableWilt1 (interface)](#pipeablewilt1-interface) - [PipeableWilt2 (interface)](#pipeablewilt2-interface) - [PipeableWilt2C (interface)](#pipeablewilt2c-interface) - [PipeableWilt3 (interface)](#pipeablewilt3-interface) - [PipeableWither (interface)](#pipeablewither-interface) - [PipeableWither1 (interface)](#pipeablewither1-interface) - [PipeableWither2 (interface)](#pipeablewither2-interface) - [PipeableWither2C (interface)](#pipeablewither2c-interface) - [PipeableWither3 (interface)](#pipeablewither3-interface) - [Wilt (interface)](#wilt-interface) - [Wilt1 (interface)](#wilt1-interface) - [Wilt2 (interface)](#wilt2-interface) - [Wilt2C (interface)](#wilt2c-interface) - [Wilt3 (interface)](#wilt3-interface) - [Wither (interface)](#wither-interface) - [Wither1 (interface)](#wither1-interface) - [Wither2 (interface)](#wither2-interface) - [Wither2C (interface)](#wither2c-interface) - [Wither3 (interface)](#wither3-interface) - [filterE](#filtere) --- # defaults ## wiltDefault Return a `wilt` implementation from `Traversable` and `Compactable`. **Signature** ```ts export declare function wiltDefault( T: Traversable2C, C: Compactable2 ): Witherable2C['wilt'] export declare function wiltDefault( T: Traversable2, C: Compactable2C ): Witherable2C['wilt'] export declare function wiltDefault(T: Traversable1, C: Compactable1): Witherable1['wilt'] export declare function wiltDefault(T: Traversable, C: Compactable): Witherable['wilt'] ``` Added in v2.11.0 ## witherDefault Return a `wither` implementation from `Traversable` and `Compactable`. **Signature** ```ts export declare function witherDefault( T: Traversable2C, C: Compactable2 ): Witherable2C['wither'] export declare function witherDefault( T: Traversable2, C: Compactable2C ): Witherable2C['wither'] export declare function witherDefault(T: Traversable1, C: Compactable1): Witherable1['wither'] export declare function witherDefault(T: Traversable, C: Compactable): Witherable['wither'] ``` Added in v2.11.0 # model ## Witherable (interface) **Signature** ```ts export interface Witherable extends Traversable, Filterable { /** * Partition a structure with effects */ readonly wilt: Wilt /** * Filter a structure with effects */ readonly wither: Wither } ``` Added in v2.0.0 ## Witherable1 (interface) **Signature** ```ts export interface Witherable1 extends Traversable1, Filterable1 { readonly wilt: Wilt1 readonly wither: Wither1 } ``` Added in v2.0.0 ## Witherable2 (interface) **Signature** ```ts export interface Witherable2 extends Traversable2, Filterable2 { readonly wilt: Wilt2 readonly wither: Wither2 } ``` Added in v2.0.0 ## Witherable2C (interface) **Signature** ```ts export interface Witherable2C extends Traversable2C, Filterable2C { readonly wilt: Wilt2C readonly wither: Wither2C } ``` Added in v2.0.0 ## Witherable3 (interface) **Signature** ```ts export interface Witherable3 extends Traversable3, Filterable3 { readonly wilt: Wilt3 readonly wither: Wither3 } ``` Added in v2.0.0 # utils ## FilterE1 (interface) **Signature** ```ts export interface FilterE1 { (F: Applicative3): ( predicate: (a: A) => Kind3 ) => (ga: Kind) => Kind3> (F: Applicative3C): ( predicate: (a: A) => Kind3 ) => (ga: Kind) => Kind3> (F: Applicative2): ( predicate: (a: A) => Kind2 ) => (ga: Kind) => Kind2> (F: Applicative2C):
( predicate: (a: A) => Kind2 ) => (ga: Kind) => Kind2> (F: Applicative1): ( predicate: (a: A) => Kind ) => (ga: Kind) => Kind> (F: Applicative): (predicate: (a: A) => HKT) => (ga: Kind) => HKT> } ``` Added in v2.11.0 ## PipeableWilt (interface) **Signature** ```ts export interface PipeableWilt { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: HKT) => Kind3, HKT>> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (wa: HKT) => Kind3, HKT>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: HKT) => Kind2, HKT>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: HKT) => Kind2, HKT>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: HKT) => Kind, HKT>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: HKT) => HKT, HKT>> } ``` Added in v2.6.5 ## PipeableWilt1 (interface) **Signature** ```ts export interface PipeableWilt1 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind) => Kind3, Kind>> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (wa: Kind) => Kind3, Kind>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind) => Kind2, Kind>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind) => Kind2, Kind>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind) => Kind, Kind>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind) => HKT, Kind>> } ``` Added in v2.6.5 ## PipeableWilt2 (interface) **Signature** ```ts export interface PipeableWilt2 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind2) => Kind3, Kind2>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind2) => Kind, Kind2>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind2) => HKT, Kind2>> } ``` Added in v2.6.5 ## PipeableWilt2C (interface) **Signature** ```ts export interface PipeableWilt2C { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind2) => Kind3, Kind2>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind2) => Kind, Kind2>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind2) => HKT, Kind2>> } ``` Added in v2.6.5 ## PipeableWilt3 (interface) **Signature** ```ts export interface PipeableWilt3 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind3) => Kind3, Kind3>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind3) => Kind2, Kind3>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind3) => Kind2, Kind3>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind3) => Kind, Kind3>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind3) => HKT, Kind3>> } ``` Added in v2.6.5 ## PipeableWither (interface) **Signature** ```ts export interface PipeableWither { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: HKT) => Kind3> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (ta: HKT) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: HKT) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: HKT) => Kind2> (F: Applicative1): (f: (a: A) => Kind>) => (ta: HKT) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: HKT) => HKT> } ``` Added in v2.6.5 ## PipeableWither1 (interface) **Signature** ```ts export interface PipeableWither1 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind) => Kind3> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (ta: Kind) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: Kind) => HKT> } ``` Added in v2.6.5 ## PipeableWither2 (interface) **Signature** ```ts export interface PipeableWither2 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind2) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: Kind2) => HKT> } ``` Added in v2.6.5 ## PipeableWither2C (interface) **Signature** ```ts export interface PipeableWither2C { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind2) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: Kind2) => HKT> } ``` Added in v2.6.5 ## PipeableWither3 (interface) **Signature** ```ts export interface PipeableWither3 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind3) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind3) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind3) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind3) => Kind> (F: Applicative): ( f: (a: A) => HKT> ) => (ta: Kind3) => HKT> } ``` Added in v2.6.5 ## Wilt (interface) **Signature** ```ts export interface Wilt { (F: Applicative3): ( wa: HKT, f: (a: A) => Kind3> ) => Kind3, HKT>> (F: Applicative3C): ( wa: HKT, f: (a: A) => Kind3> ) => Kind3, HKT>> (F: Applicative2): ( wa: HKT, f: (a: A) => Kind2> ) => Kind2, HKT>> (F: Applicative2C): ( wa: HKT, f: (a: A) => Kind2> ) => Kind2, HKT>> (F: Applicative1): ( wa: HKT, f: (a: A) => Kind> ) => Kind, HKT>> (F: Applicative): ( wa: HKT, f: (a: A) => HKT> ) => HKT, HKT>> } ``` Added in v2.0.0 ## Wilt1 (interface) **Signature** ```ts export interface Wilt1 { (F: Applicative3): ( wa: Kind, f: (a: A) => Kind3> ) => Kind3, Kind>> (F: Applicative3C): ( wa: Kind, f: (a: A) => Kind3> ) => Kind3, Kind>> (F: Applicative2): ( wa: Kind, f: (a: A) => Kind2> ) => Kind2, Kind>> (F: Applicative2C): ( wa: Kind, f: (a: A) => Kind2> ) => Kind2, Kind>> (F: Applicative1): ( wa: Kind, f: (a: A) => Kind> ) => Kind, Kind>> (F: Applicative): ( wa: Kind, f: (a: A) => HKT> ) => HKT, Kind>> } ``` Added in v2.0.0 ## Wilt2 (interface) **Signature** ```ts export interface Wilt2 { (F: Applicative3): ( wa: Kind2, f: (a: A) => Kind3> ) => Kind3, Kind2>> (F: Applicative2): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative2C): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative1): ( wa: Kind2, f: (a: A) => Kind> ) => Kind, Kind2>> (F: Applicative): ( wa: Kind2, f: (a: A) => HKT> ) => HKT, Kind2>> } ``` Added in v2.0.0 ## Wilt2C (interface) **Signature** ```ts export interface Wilt2C { (F: Applicative3): ( wa: Kind2, f: (a: A) => Kind3> ) => Kind3, Kind2>> (F: Applicative2): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative2C): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative1): ( wa: Kind2, f: (a: A) => Kind> ) => Kind, Kind2>> (F: Applicative): ( wa: Kind2, f: (a: A) => HKT> ) => HKT, Kind2>> } ``` Added in v2.0.0 ## Wilt3 (interface) **Signature** ```ts export interface Wilt3 { (F: Applicative3): ( wa: Kind3, f: (a: A) => Kind3> ) => Kind3, Kind3>> (F: Applicative2): ( wa: Kind3, f: (a: A) => Kind2> ) => Kind2, Kind3>> (F: Applicative2C): ( wa: Kind3, f: (a: A) => Kind2> ) => Kind2, Kind3>> (F: Applicative1): ( wa: Kind3, f: (a: A) => Kind> ) => Kind, Kind3>> (F: Applicative): ( wa: Kind3, f: (a: A) => HKT> ) => HKT, Kind3>> } ``` Added in v2.0.0 ## Wither (interface) **Signature** ```ts export interface Wither { (F: Applicative3): ( ta: HKT, f: (a: A) => Kind3> ) => Kind3> (F: Applicative3C): ( ta: HKT, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: HKT, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: HKT, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): (ta: HKT, f: (a: A) => Kind>) => Kind> (F: Applicative): (ta: HKT, f: (a: A) => HKT>) => HKT> } ``` Added in v2.0.0 ## Wither1 (interface) **Signature** ```ts export interface Wither1 { (F: Applicative3): ( ta: Kind, f: (a: A) => Kind3> ) => Kind3> (F: Applicative3C): ( ta: Kind, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): (ta: Kind, f: (a: A) => Kind>) => Kind> (F: Applicative): (ta: Kind, f: (a: A) => HKT>) => HKT> } ``` Added in v2.0.0 ## Wither2 (interface) **Signature** ```ts export interface Wither2 { (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (a: A) => Kind> ) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT>) => HKT> } ``` Added in v2.0.0 ## Wither2C (interface) **Signature** ```ts export interface Wither2C { (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (a: A) => Kind> ) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT>) => HKT> } ``` Added in v2.0.0 ## Wither3 (interface) **Signature** ```ts export interface Wither3 { (F: Applicative3): ( ta: Kind3, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind3, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind3, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): ( ta: Kind3, f: (a: A) => Kind> ) => Kind> (F: Applicative): ( ta: Kind3, f: (a: A) => HKT> ) => HKT> } ``` Added in v2.0.0 ## filterE Filter values inside a `F` context. See `ReadonlyArray`'s `filterE` for an example of usage. **Signature** ```ts export declare function filterE(W: Witherable1): FilterE1 export declare function filterE( W: Witherable ): (F: Applicative) => (predicate: (a: A) => HKT) => (ga: HKT) => HKT> ``` Added in v2.11.0 ================================================ FILE: docs/modules/Writer.ts.md ================================================ --- title: Writer.ts nav_order: 120 parent: Modules --- ## Writer overview Added in v2.0.0 ---

Table of contents

- [constructors](#constructors) - [tell](#tell) - [instances](#instances) - [Functor](#functor) - [getApplicative](#getapplicative) - [getApply](#getapply) - [getChain](#getchain) - [getMonad](#getmonad) - [getPointed](#getpointed) - [mapping](#mapping) - [flap](#flap) - [map](#map) - [model](#model) - [Writer (interface)](#writer-interface) - [type lambdas](#type-lambdas) - [URI](#uri) - [URI (type alias)](#uri-type-alias) - [utils](#utils) - [censor](#censor) - [evaluate](#evaluate) - [execute](#execute) - [listen](#listen) - [listens](#listens) - [pass](#pass) - [zone of death](#zone-of-death) - [~~evalWriter~~](#evalwriter) - [~~execWriter~~](#execwriter) - [~~writer~~](#writer) --- # constructors ## tell Appends a value to the accumulator **Signature** ```ts export declare const tell: (w: W) => Writer ``` Added in v2.0.0 # instances ## Functor **Signature** ```ts export declare const Functor: Functor2<'Writer'> ``` Added in v2.7.0 ## getApplicative **Signature** ```ts export declare const getApplicative: (M: Monoid) => Applicative2C<'Writer', W> ``` Added in v2.10.0 ## getApply **Signature** ```ts export declare const getApply: (S: Semigroup) => Apply2C<'Writer', W> ``` Added in v2.10.0 ## getChain **Signature** ```ts export declare function getChain(S: Semigroup): Chain2C ``` Added in v2.10.0 ## getMonad **Signature** ```ts export declare function getMonad(M: Monoid): Monad2C ``` Added in v2.0.0 ## getPointed **Signature** ```ts export declare const getPointed: (M: Monoid) => Pointed2C<'Writer', W> ``` Added in v2.10.0 # mapping ## flap **Signature** ```ts export declare const flap:
(a: A) => (fab: Writer B>) => Writer ``` Added in v2.10.0 ## map `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types use the type constructor `F` to represent some computational context. **Signature** ```ts export declare const map: (f: (a: A) => B) => (fa: Writer) => Writer ``` Added in v2.0.0 # model ## Writer (interface) **Signature** ```ts export interface Writer { (): [A, W] } ``` Added in v2.0.0 # type lambdas ## URI **Signature** ```ts export declare const URI: 'Writer' ``` Added in v2.0.0 ## URI (type alias) **Signature** ```ts export type URI = typeof URI ``` Added in v2.0.0 # utils ## censor Modify the final accumulator value by applying a function **Signature** ```ts export declare const censor: (f: (w: W) => W) => (fa: Writer) => Writer ``` Added in v2.0.0 ## evaluate **Signature** ```ts export declare const evaluate: (fa: Writer) => A ``` Added in v2.8.0 ## execute **Signature** ```ts export declare const execute: (fa: Writer) => W ``` Added in v2.8.0 ## listen Modifies the result to include the changes to the accumulator **Signature** ```ts export declare const listen: (fa: Writer) => Writer ``` Added in v2.0.0 ## listens Projects a value from modifications made to the accumulator during an action **Signature** ```ts export declare const listens: (f: (w: W) => B) => (fa: Writer) => Writer ``` Added in v2.0.0 ## pass Applies the returned function to the accumulator **Signature** ```ts export declare const pass: (fa: Writer W]>) => Writer ``` Added in v2.0.0 # zone of death ## ~~evalWriter~~ Use [`evaluate`](#evaluate) instead **Signature** ```ts export declare const evalWriter: (fa: Writer) => A ``` Added in v2.0.0 ## ~~execWriter~~ Use [`execute`](#execute) instead **Signature** ```ts export declare const execWriter: (fa: Writer) => W ``` Added in v2.0.0 ## ~~writer~~ Use [`Functor`](#functor) instead. **Signature** ```ts export declare const writer: Functor2<'Writer'> ``` Added in v2.0.0 ================================================ FILE: docs/modules/WriterT.ts.md ================================================ --- title: WriterT.ts nav_order: 121 parent: Modules --- ## WriterT overview Added in v2.4.0 ---

Table of contents

- [model](#model) - [WriterT (interface)](#writert-interface) - [WriterT1 (interface)](#writert1-interface) - [WriterT2 (interface)](#writert2-interface) - [utils](#utils) - [WriterM (interface)](#writerm-interface) - [WriterM1 (interface)](#writerm1-interface) - [WriterM2 (interface)](#writerm2-interface) - [WriterM2C (interface)](#writerm2c-interface) - [WriterM3 (interface)](#writerm3-interface) - [WriterT3 (interface)](#writert3-interface) - [getWriterM](#getwriterm) --- # model ## WriterT (interface) **Signature** ```ts export interface WriterT { (): HKT } ``` Added in v2.4.0 ## WriterT1 (interface) **Signature** ```ts export interface WriterT1 { (): Kind } ``` Added in v2.4.0 ## WriterT2 (interface) **Signature** ```ts export interface WriterT2 { (): Kind2 } ``` Added in v2.4.0 # utils ## WriterM (interface) **Signature** ```ts export interface WriterM { readonly map: (fa: WriterT, f: (a: A) => B) => WriterT readonly evalWriter: (fa: WriterT) => HKT readonly execWriter: (fa: WriterT) => HKT readonly tell: (w: W) => WriterT readonly listen: (fa: WriterT) => WriterT readonly pass: (fa: WriterT W]>) => WriterT readonly listens: (fa: WriterT, f: (w: W) => B) => WriterT readonly censor: (fa: WriterT, f: (w: W) => W) => WriterT readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT, f: (a: A) => B) => WriterT readonly of:
(a: A) => WriterT readonly ap: (mab: WriterT B>, ma: WriterT) => WriterT readonly chain: (ma: WriterT, f: (a: A) => WriterT) => WriterT } } ``` Added in v2.4.0 ## WriterM1 (interface) **Signature** ```ts export interface WriterM1 { readonly map: (fa: WriterT1, f: (a: A) => B) => WriterT1 readonly evalWriter: (fa: WriterT1) => Kind readonly execWriter: (fa: WriterT1) => Kind readonly tell: (w: W) => WriterT1 readonly listen: (fa: WriterT1) => WriterT1 readonly pass: (fa: WriterT1 W]>) => WriterT1 readonly listens: (fa: WriterT1, f: (w: W) => B) => WriterT1 readonly censor: (fa: WriterT1, f: (w: W) => W) => WriterT1 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT1, f: (a: A) => B) => WriterT1 readonly of: (a: A) => WriterT1 readonly ap: (mab: WriterT1 B>, ma: WriterT1) => WriterT1 readonly chain: (ma: WriterT1, f: (a: A) => WriterT1) => WriterT1 } } ``` Added in v2.4.0 ## WriterM2 (interface) **Signature** ```ts export interface WriterM2 { readonly map: (fa: WriterT2, f: (a: A) => B) => WriterT2 readonly evalWriter: (fa: WriterT2) => Kind2 readonly execWriter: (fa: WriterT2) => Kind2 readonly tell: (w: W) => WriterT2 readonly listen: (fa: WriterT2) => WriterT2 readonly pass: (fa: WriterT2 W]>) => WriterT2 readonly listens: (fa: WriterT2, f: (w: W) => B) => WriterT2 readonly censor: (fa: WriterT2, f: (w: W) => W) => WriterT2 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT2, f: (a: A) => B) => WriterT2 readonly of: (a: A) => WriterT2 readonly ap: (mab: WriterT2 B>, ma: WriterT2) => WriterT2 readonly chain: (ma: WriterT2, f: (a: A) => WriterT2) => WriterT2 } } ``` Added in v2.4.0 ## WriterM2C (interface) **Signature** ```ts export interface WriterM2C { readonly map: (fa: WriterT2, f: (a: A) => B) => WriterT2 readonly evalWriter: (fa: WriterT2) => Kind2 readonly execWriter: (fa: WriterT2) => Kind2 readonly tell: (w: W) => WriterT2 readonly listen: (fa: WriterT2) => WriterT2 readonly pass: (fa: WriterT2 W]>) => WriterT2 readonly listens: (fa: WriterT2, f: (w: W) => B) => WriterT2 readonly censor: (fa: WriterT2, f: (w: W) => W) => WriterT2 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT2, f: (a: A) => B) => WriterT2 readonly of: (a: A) => WriterT2 readonly ap: (mab: WriterT2 B>, ma: WriterT2) => WriterT2 readonly chain: (ma: WriterT2, f: (a: A) => WriterT2) => WriterT2 } } ``` Added in v2.4.0 ## WriterM3 (interface) **Signature** ```ts export interface WriterM3 { readonly map: (fa: WriterT3, f: (a: A) => B) => WriterT3 readonly evalWriter: (fa: WriterT3) => Kind3 readonly execWriter: (fa: WriterT3) => Kind3 readonly tell: (w: W) => WriterT3 readonly listen: (fa: WriterT3) => WriterT3 readonly pass: (fa: WriterT3 W]>) => WriterT3 readonly listens: (fa: WriterT3, f: (w: W) => B) => WriterT3 readonly censor: (fa: WriterT3, f: (w: W) => W) => WriterT3 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT3, f: (a: A) => B) => WriterT3 readonly of: (a: A) => WriterT3 readonly ap: ( mab: WriterT3 B>, ma: WriterT3 ) => WriterT3 readonly chain: ( ma: WriterT3, f: (a: A) => WriterT3 ) => WriterT3 } } ``` Added in v2.4.0 ## WriterT3 (interface) **Signature** ```ts export interface WriterT3 { (): Kind3 } ``` Added in v2.4.0 ## getWriterM **Signature** ```ts export declare function getWriterM(M: Monad3): WriterM3 export declare function getWriterM(M: Monad2): WriterM2 export declare function getWriterM(M: Monad2C): WriterM2C export declare function getWriterM(M: Monad1): WriterM1 export declare function getWriterM(M: Monad): WriterM ``` Added in v2.4.0 ================================================ FILE: docs/modules/Zero.ts.md ================================================ --- title: Zero.ts nav_order: 122 parent: Modules --- ## Zero overview Added in v2.11.0 ---

Table of contents

- [do notation](#do-notation) - [guard](#guard) - [model](#model) - [Zero (interface)](#zero-interface) - [Zero1 (interface)](#zero1-interface) - [Zero2 (interface)](#zero2-interface) - [Zero2C (interface)](#zero2c-interface) - [Zero3 (interface)](#zero3-interface) - [Zero3C (interface)](#zero3c-interface) - [Zero4 (interface)](#zero4-interface) --- # do notation ## guard **Signature** ```ts export declare function guard( F: Zero4, P: Pointed4 ): (b: boolean) => Kind4 export declare function guard(F: Zero3, P: Pointed3): (b: boolean) => Kind3 export declare function guard( F: Zero3C, P: Pointed3C ): (b: boolean) => Kind3 export declare function guard(F: Zero2, P: Pointed2): (b: boolean) => Kind2 export declare function guard( F: Zero2C, P: Pointed2C ): (b: boolean) => Kind2 export declare function guard(F: Zero1, P: Pointed1): (b: boolean) => Kind export declare function guard(F: Zero, P: Pointed): (b: boolean) => HKT ``` Added in v2.11.0 # model ## Zero (interface) **Signature** ```ts export interface Zero { readonly URI: F readonly zero:
() => HKT } ``` Added in v2.11.0 ## Zero1 (interface) **Signature** ```ts export interface Zero1 { readonly URI: F readonly zero: () => Kind } ``` Added in v2.11.0 ## Zero2 (interface) **Signature** ```ts export interface Zero2 { readonly URI: F readonly zero: () => Kind2 } ``` Added in v2.11.0 ## Zero2C (interface) **Signature** ```ts export interface Zero2C { readonly URI: F readonly _E: E readonly zero: () => Kind2 } ``` Added in v2.11.0 ## Zero3 (interface) **Signature** ```ts export interface Zero3 { readonly URI: F readonly zero: () => Kind3 } ``` Added in v2.11.0 ## Zero3C (interface) **Signature** ```ts export interface Zero3C { readonly URI: F readonly _E: E readonly zero: () => Kind3 } ``` Added in v2.11.0 ## Zero4 (interface) **Signature** ```ts export interface Zero4 { readonly URI: F readonly zero: () => Kind4 } ``` Added in v2.11.0 ================================================ FILE: docs/modules/boolean.ts.md ================================================ --- title: boolean.ts nav_order: 7 parent: Modules --- ## boolean overview Added in v2.2.0 ---

Table of contents

- [instances](#instances) - [BooleanAlgebra](#booleanalgebra) - [Eq](#eq) - [MonoidAll](#monoidall) - [MonoidAny](#monoidany) - [Ord](#ord) - [SemigroupAll](#semigroupall) - [SemigroupAny](#semigroupany) - [Show](#show) - [pattern matching](#pattern-matching) - [fold](#fold) - [foldW](#foldw) - [match](#match) - [matchW](#matchw) - [refinements](#refinements) - [isBoolean](#isboolean) --- # instances ## BooleanAlgebra **Signature** ```ts export declare const BooleanAlgebra: BA.BooleanAlgebra ``` Added in v2.10.0 ## Eq **Signature** ```ts export declare const Eq: E.Eq ``` Added in v2.10.0 ## MonoidAll `boolean` monoid under conjunction. The `empty` value is `true`. **Signature** ```ts export declare const MonoidAll: Monoid ``` **Example** ```ts import { MonoidAll } from 'fp-ts/boolean' assert.deepStrictEqual(MonoidAll.concat(true, true), true) assert.deepStrictEqual(MonoidAll.concat(true, false), false) ``` Added in v2.10.0 ## MonoidAny `boolean` monoid under disjunction. The `empty` value is `false`. **Signature** ```ts export declare const MonoidAny: Monoid ``` **Example** ```ts import { MonoidAny } from 'fp-ts/boolean' assert.deepStrictEqual(MonoidAny.concat(true, true), true) assert.deepStrictEqual(MonoidAny.concat(true, false), true) assert.deepStrictEqual(MonoidAny.concat(false, false), false) ``` Added in v2.10.0 ## Ord **Signature** ```ts export declare const Ord: O.Ord ``` Added in v2.10.0 ## SemigroupAll `boolean` semigroup under conjunction. **Signature** ```ts export declare const SemigroupAll: Semigroup ``` **Example** ```ts import { SemigroupAll } from 'fp-ts/boolean' assert.deepStrictEqual(SemigroupAll.concat(true, true), true) assert.deepStrictEqual(SemigroupAll.concat(true, false), false) ``` Added in v2.10.0 ## SemigroupAny `boolean` semigroup under disjunction. **Signature** ```ts export declare const SemigroupAny: Semigroup ``` **Example** ```ts import { SemigroupAny } from 'fp-ts/boolean' assert.deepStrictEqual(SemigroupAny.concat(true, true), true) assert.deepStrictEqual(SemigroupAny.concat(true, false), true) assert.deepStrictEqual(SemigroupAny.concat(false, false), false) ``` Added in v2.10.0 ## Show **Signature** ```ts export declare const Show: S.Show ``` Added in v2.10.0 # pattern matching ## fold Alias of [`match`](#match). **Signature** ```ts export declare const fold:
(onFalse: LazyArg, onTrue: LazyArg) => (value: boolean) => A ``` Added in v2.2.0 ## foldW Alias of [`matchW`](#matchw). **Signature** ```ts export declare const foldW: (onFalse: LazyArg, onTrue: LazyArg) => (value: boolean) => A | B ``` Added in v2.10.0 ## match Defines the fold over a boolean value. Takes two thunks `onTrue`, `onFalse` and a `boolean` value. If `value` is false, `onFalse()` is returned, otherwise `onTrue()`. **Signature** ```ts export declare const match: (onFalse: LazyArg, onTrue: LazyArg) => (value: boolean) => A ``` **Example** ```ts import { some, map } from 'fp-ts/Option' import { pipe } from 'fp-ts/function' import { match } from 'fp-ts/boolean' assert.deepStrictEqual( pipe( some(true), map( match( () => 'false', () => 'true' ) ) ), some('true') ) ``` Added in v2.10.0 ## matchW Less strict version of [`match`](#match). The `W` suffix (short for **W**idening) means that the handler return types will be merged. **Signature** ```ts export declare const matchW: (onFalse: LazyArg, onTrue: LazyArg) => (value: boolean) => A | B ``` Added in v2.10.0 # refinements ## isBoolean **Signature** ```ts export declare const isBoolean: Refinement ``` Added in v2.11.0 ================================================ FILE: docs/modules/function.ts.md ================================================ --- title: function.ts nav_order: 41 parent: Modules --- ## function overview Added in v2.0.0 ---

Table of contents

- [instances](#instances) - [getBooleanAlgebra](#getbooleanalgebra) - [getMonoid](#getmonoid) - [getRing](#getring) - [getSemigroup](#getsemigroup) - [getSemiring](#getsemiring) - [lagacy](#lagacy) - [Lazy (interface)](#lazy-interface) - [utils](#utils) - [FunctionN (interface)](#functionn-interface) - [LazyArg (interface)](#lazyarg-interface) - [SK](#sk) - [absurd](#absurd) - [apply](#apply) - [constFalse](#constfalse) - [constNull](#constnull) - [constTrue](#consttrue) - [constUndefined](#constundefined) - [constVoid](#constvoid) - [constant](#constant) - [decrement](#decrement) - [flip](#flip) - [flow](#flow) - [hole](#hole) - [identity](#identity) - [increment](#increment) - [pipe](#pipe) - [tuple](#tuple) - [tupled](#tupled) - [unsafeCoerce](#unsafecoerce) - [untupled](#untupled) - [zone of death](#zone-of-death) - [~~Endomorphism~~ (interface)](#endomorphism-interface) - [~~Predicate~~ (interface)](#predicate-interface) - [~~Refinement~~ (interface)](#refinement-interface) - [~~getEndomorphismMonoid~~](#getendomorphismmonoid) - [~~not~~](#not) --- # instances ## getBooleanAlgebra **Signature** ```ts export declare const getBooleanAlgebra: (B: BooleanAlgebra) =>
() => BooleanAlgebra<(a: A) => B> ``` Added in v2.10.0 ## getMonoid Unary functions form a monoid as long as you can provide a monoid for the codomain. **Signature** ```ts export declare const getMonoid: (M: Monoid) => () => Monoid<(a: A) => M> ``` **Example** ```ts import { Predicate } from 'fp-ts/Predicate' import { getMonoid } from 'fp-ts/function' import * as B from 'fp-ts/boolean' const f: Predicate = (n) => n <= 2 const g: Predicate = (n) => n >= 0 const M1 = getMonoid(B.MonoidAll)() assert.deepStrictEqual(M1.concat(f, g)(1), true) assert.deepStrictEqual(M1.concat(f, g)(3), false) const M2 = getMonoid(B.MonoidAny)() assert.deepStrictEqual(M2.concat(f, g)(1), true) assert.deepStrictEqual(M2.concat(f, g)(3), true) ``` Added in v2.10.0 ## getRing **Signature** ```ts export declare const getRing: (R: Ring) => Ring<(a: A) => B> ``` Added in v2.10.0 ## getSemigroup Unary functions form a semigroup as long as you can provide a semigroup for the codomain. **Signature** ```ts export declare const getSemigroup: (S: Semigroup) => () => Semigroup<(a: A) => S> ``` **Example** ```ts import { Predicate, getSemigroup } from 'fp-ts/function' import * as B from 'fp-ts/boolean' const f: Predicate = (n) => n <= 2 const g: Predicate = (n) => n >= 0 const S1 = getSemigroup(B.SemigroupAll)() assert.deepStrictEqual(S1.concat(f, g)(1), true) assert.deepStrictEqual(S1.concat(f, g)(3), false) const S2 = getSemigroup(B.SemigroupAny)() assert.deepStrictEqual(S2.concat(f, g)(1), true) assert.deepStrictEqual(S2.concat(f, g)(3), true) ``` Added in v2.10.0 ## getSemiring **Signature** ```ts export declare const getSemiring: (S: Semiring) => Semiring<(a: A) => B> ``` Added in v2.10.0 # lagacy ## Lazy (interface) Use `LazyArg` instead. **Signature** ```ts export interface Lazy { (): A } ``` Added in v2.0.0 # utils ## FunctionN (interface) **Signature** ```ts export interface FunctionN, B> { (...args: A): B } ``` **Example** ```ts import { FunctionN } from 'fp-ts/function' export const sum: FunctionN<[number, number], number> = (a, b) => a + b ``` Added in v2.0.0 ## LazyArg (interface) A lazy argument. **Signature** ```ts export interface LazyArg { (): A } ``` Added in v2.15.0 ## SK **Signature** ```ts export declare const SK: (_: A, b: B) => B ``` Added in v2.11.0 ## absurd **Signature** ```ts export declare function absurd(_: never): A ``` Added in v2.0.0 ## apply **Signature** ```ts export declare const apply: (a: A) => (f: (a: A) => B) => B ``` Added in v2.11.0 ## constFalse A thunk that returns always `false`. **Signature** ```ts export declare const constFalse: LazyArg ``` Added in v2.0.0 ## constNull A thunk that returns always `null`. **Signature** ```ts export declare const constNull: LazyArg ``` Added in v2.0.0 ## constTrue A thunk that returns always `true`. **Signature** ```ts export declare const constTrue: LazyArg ``` Added in v2.0.0 ## constUndefined A thunk that returns always `undefined`. **Signature** ```ts export declare const constUndefined: LazyArg ``` Added in v2.0.0 ## constVoid A thunk that returns always `void`. **Signature** ```ts export declare const constVoid: LazyArg ``` Added in v2.0.0 ## constant **Signature** ```ts export declare function constant(a: A): LazyArg ``` Added in v2.0.0 ## decrement **Signature** ```ts export declare function decrement(n: number): number ``` Added in v2.0.0 ## flip Flips the arguments of a curried function. **Signature** ```ts export declare function flip(f: (a: A) => (b: B) => C): (b: B) => (a: A) => C export declare function flip(f: (a: A, b: B) => C): (b: B, a: A) => C ``` **Example** ```ts import { flip } from 'fp-ts/function' const f = (a: number) => (b: string) => a - b.length assert.strictEqual(flip(f)('aaa')(2), -1) ``` Added in v2.0.0 ## flow Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary. See also [`pipe`](#pipe). **Signature** ```ts export declare function flow, B>(ab: (...a: A) => B): (...a: A) => B export declare function flow, B, C>( ab: (...a: A) => B, bc: (b: B) => C ): (...a: A) => C export declare function flow, B, C, D>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D ): (...a: A) => D export declare function flow, B, C, D, E>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E ): (...a: A) => E export declare function flow, B, C, D, E, F>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F ): (...a: A) => F export declare function flow, B, C, D, E, F, G>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G ): (...a: A) => G export declare function flow, B, C, D, E, F, G, H>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H ): (...a: A) => H export declare function flow, B, C, D, E, F, G, H, I>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I ): (...a: A) => I export declare function flow, B, C, D, E, F, G, H, I, J>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J ): (...a: A) => J ``` **Example** ```ts import { flow } from 'fp-ts/function' const len = (s: string): number => s.length const double = (n: number): number => n * 2 const f = flow(len, double) assert.strictEqual(f('aaa'), 6) ``` Added in v2.0.0 ## hole Type hole simulation **Signature** ```ts export declare const hole: () => T ``` Added in v2.7.0 ## identity **Signature** ```ts export declare function identity(a: A): A ``` Added in v2.0.0 ## increment **Signature** ```ts export declare function increment(n: number): number ``` Added in v2.0.0 ## pipe Pipes the value of an expression into a pipeline of functions. See also [`flow`](#flow). **Signature** ```ts export declare function pipe(a: A): A export declare function pipe(a: A, ab: (a: A) => B): B export declare function pipe(a: A, ab: (a: A) => B, bc: (b: B) => C): C export declare function pipe(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D export declare function pipe(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): E export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F ): F export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G ): G export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H ): H export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I ): I export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J ): J export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K ): K export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L ): L export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M ): M export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N ): N export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O ): O export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P ): P export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q ): Q export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R ): R export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S ): S export declare function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S, st: (s: S) => T ): T ``` **Example** ```ts import { pipe } from 'fp-ts/function' const len = (s: string): number => s.length const double = (n: number): number => n * 2 // without pipe assert.strictEqual(double(len('aaa')), 6) // with pipe assert.strictEqual(pipe('aaa', len, double), 6) ``` Added in v2.6.3 ## tuple **Signature** ```ts export declare function tuple>(...t: T): T ``` Added in v2.0.0 ## tupled Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. **Signature** ```ts export declare function tupled, B>(f: (...a: A) => B): (a: A) => B ``` **Example** ```ts import { tupled } from 'fp-ts/function' const add = tupled((x: number, y: number): number => x + y) assert.strictEqual(add([1, 2]), 3) ``` Added in v2.4.0 ## unsafeCoerce **Signature** ```ts export declare const unsafeCoerce: (a: A) => B ``` Added in v2.0.0 ## untupled Inverse function of `tupled` **Signature** ```ts export declare function untupled, B>(f: (a: A) => B): (...a: A) => B ``` Added in v2.4.0 # zone of death ## ~~Endomorphism~~ (interface) Use `Endomorphism` module instead. **Signature** ```ts export interface Endomorphism { (a: A): A } ``` Added in v2.0.0 ## ~~Predicate~~ (interface) Use `Predicate` module instead. **Signature** ```ts export interface Predicate { (a: A): boolean } ``` Added in v2.0.0 ## ~~Refinement~~ (interface) Use `Refinement` module instead. **Signature** ```ts export interface Refinement { (a: A): a is B } ``` Added in v2.0.0 ## ~~getEndomorphismMonoid~~ Use `Endomorphism` module instead. **Signature** ```ts export declare const getEndomorphismMonoid: () => Monoid> ``` Added in v2.10.0 ## ~~not~~ Use `Predicate` module instead. **Signature** ```ts export declare function not(predicate: Predicate): Predicate ``` Added in v2.0.0 ================================================ FILE: docs/modules/index.md ================================================ --- title: Modules permalink: /modules/ nav_order: 4 has_children: true has_toc: true --- # Modules This section provides technical reference material for the functions, data types, and type classes provided by `fp-ts`. ================================================ FILE: docs/modules/index.ts.md ================================================ --- title: index.ts nav_order: 48 parent: Modules --- ## index overview Added in v2.0.0 ---

Table of contents

- [data types](#data-types) - [array](#array) - [const](#const) - [either](#either) - [endomorphism](#endomorphism) - [identity](#identity) - [io](#io) - [ioEither](#ioeither) - [ioOption](#iooption) - [map](#map) - [nonEmptyArray](#nonemptyarray) - [option](#option) - [predicate](#predicate) - [reader](#reader) - [readerEither](#readereither) - [readerIO](#readerio) - [readerTask](#readertask) - [readerTaskEither](#readertaskeither) - [readonlyArray](#readonlyarray) - [readonlyMap](#readonlymap) - [readonlyNonEmptyArray](#readonlynonemptyarray) - [readonlyRecord](#readonlyrecord) - [readonlySet](#readonlyset) - [readonlyTuple](#readonlytuple) - [record](#record) - [refinement](#refinement) - [separated](#separated) - [set](#set) - [state](#state) - [stateReaderTaskEither](#statereadertaskeither) - [store](#store) - [task](#task) - [taskEither](#taskeither) - [taskOption](#taskoption) - [taskThese](#taskthese) - [these](#these) - [traced](#traced) - [tree](#tree) - [tuple](#tuple) - [validationT](#validationt) - [writer](#writer) - [model](#model) - [alt](#alt) - [alternative](#alternative) - [applicative](#applicative) - [apply](#apply) - [bifunctor](#bifunctor) - [booleanAlgebra](#booleanalgebra) - [bounded](#bounded) - [boundedDistributiveLattice](#boundeddistributivelattice) - [boundedJoinSemilattice](#boundedjoinsemilattice) - [boundedLattice](#boundedlattice) - [boundedMeetSemilattice](#boundedmeetsemilattice) - [category](#category) - [chain](#chain) - [chainRec](#chainrec) - [choice](#choice) - [comonad](#comonad) - [compactable](#compactable) - [contravariant](#contravariant) - [distributiveLattice](#distributivelattice) - [eq](#eq) - [extend](#extend) - [field](#field) - [filterable](#filterable) - [filterableWithIndex](#filterablewithindex) - [foldable](#foldable) - [foldableWithIndex](#foldablewithindex) - [fromEither](#fromeither) - [fromIO](#fromio) - [fromReader](#fromreader) - [fromState](#fromstate) - [fromTask](#fromtask) - [fromThese](#fromthese) - [functor](#functor) - [functorWithIndex](#functorwithindex) - [group](#group) - [heytingAlgebra](#heytingalgebra) - [invariant](#invariant) - [joinSemilattice](#joinsemilattice) - [lattice](#lattice) - [magma](#magma) - [meetSemilattice](#meetsemilattice) - [monad](#monad) - [monadIO](#monadio) - [monadTask](#monadtask) - [monadThrow](#monadthrow) - [monoid](#monoid) - [ord](#ord) - [pointed](#pointed) - [profunctor](#profunctor) - [ring](#ring) - [semigroup](#semigroup) - [semigroupoid](#semigroupoid) - [semiring](#semiring) - [show](#show) - [strong](#strong) - [traversable](#traversable) - [traversableWithIndex](#traversablewithindex) - [unfoldable](#unfoldable) - [witherable](#witherable) - [zero](#zero) - [monad transformers](#monad-transformers) - [eitherT](#eithert) - [optionT](#optiont) - [readerT](#readert) - [stateT](#statet) - [theseT](#theset) - [writerT](#writert) - [utils](#utils) - [boolean](#boolean) - [console](#console) - [date](#date) - [function](#function) - [hkt](#hkt) - [ioRef](#ioref) - [json](#json) - [naturalTransformation](#naturaltransformation) - [number](#number) - [ordering](#ordering) - [pipeable](#pipeable) - [random](#random) - [string](#string) - [struct](#struct) - [zone of death](#zone-of-death) - [~~void~~](#void) --- # data types ## array **Signature** ```ts export declare const array: typeof array ``` Added in v2.0.0 ## const **Signature** ```ts export declare const const: typeof const_ ``` Added in v2.0.0 ## either **Signature** ```ts export declare const either: typeof either ``` Added in v2.0.0 ## endomorphism **Signature** ```ts export declare const endomorphism: typeof endomorphism ``` Added in v2.11.0 ## identity **Signature** ```ts export declare const identity: typeof identity ``` Added in v2.0.0 ## io **Signature** ```ts export declare const io: typeof io ``` Added in v2.0.0 ## ioEither **Signature** ```ts export declare const ioEither: typeof ioEither ``` Added in v2.0.0 ## ioOption **Signature** ```ts export declare const ioOption: typeof ioOption ``` Added in v2.12.0 ## map **Signature** ```ts export declare const map: typeof map ``` Added in v2.0.0 ## nonEmptyArray **Signature** ```ts export declare const nonEmptyArray: typeof nonEmptyArray ``` Added in v2.0.0 ## option **Signature** ```ts export declare const option: typeof option ``` Added in v2.0.0 ## predicate **Signature** ```ts export declare const predicate: typeof predicate ``` Added in v2.11.0 ## reader **Signature** ```ts export declare const reader: typeof reader ``` Added in v2.0.0 ## readerEither **Signature** ```ts export declare const readerEither: typeof readerEither ``` Added in v2.0.0 ## readerIO **Signature** ```ts export declare const readerIO: typeof readerIO ``` Added in v2.0.0 ## readerTask **Signature** ```ts export declare const readerTask: typeof readerTask ``` Added in v2.3.0 ## readerTaskEither **Signature** ```ts export declare const readerTaskEither: typeof readerTaskEither ``` Added in v2.0.0 ## readonlyArray **Signature** ```ts export declare const readonlyArray: typeof readonlyArray ``` Added in v2.5.0 ## readonlyMap **Signature** ```ts export declare const readonlyMap: typeof readonlyMap ``` Added in v2.5.0 ## readonlyNonEmptyArray **Signature** ```ts export declare const readonlyNonEmptyArray: typeof readonlyNonEmptyArray ``` Added in v2.5.0 ## readonlyRecord **Signature** ```ts export declare const readonlyRecord: typeof readonlyRecord ``` Added in v2.5.0 ## readonlySet **Signature** ```ts export declare const readonlySet: typeof readonlySet ``` Added in v2.5.0 ## readonlyTuple **Signature** ```ts export declare const readonlyTuple: typeof readonlyTuple ``` Added in v2.5.0 ## record **Signature** ```ts export declare const record: typeof record ``` Added in v2.0.0 ## refinement **Signature** ```ts export declare const refinement: typeof refinement ``` Added in v2.11.0 ## separated **Signature** ```ts export declare const separated: typeof separated ``` Added in v2.10.0 ## set **Signature** ```ts export declare const set: typeof set ``` Added in v2.0.0 ## state **Signature** ```ts export declare const state: typeof state ``` Added in v2.0.0 ## stateReaderTaskEither **Signature** ```ts export declare const stateReaderTaskEither: typeof stateReaderTaskEither ``` Added in v2.0.0 ## store **Signature** ```ts export declare const store: typeof store ``` Added in v2.0.0 ## task **Signature** ```ts export declare const task: typeof task ``` Added in v2.0.0 ## taskEither **Signature** ```ts export declare const taskEither: typeof taskEither ``` Added in v2.0.0 ## taskOption **Signature** ```ts export declare const taskOption: typeof taskOption ``` Added in v2.10.0 ## taskThese **Signature** ```ts export declare const taskThese: typeof taskThese ``` Added in v2.4.0 ## these **Signature** ```ts export declare const these: typeof these ``` Added in v2.0.0 ## traced **Signature** ```ts export declare const traced: typeof traced ``` Added in v2.0.0 ## tree **Signature** ```ts export declare const tree: typeof tree ``` Added in v2.0.0 ## tuple **Signature** ```ts export declare const tuple: typeof tuple ``` Added in v2.0.0 ## validationT **Signature** ```ts export declare const validationT: typeof validationT ``` Added in v2.0.0 ## writer **Signature** ```ts export declare const writer: typeof writer ``` Added in v2.0.0 # model ## alt **Signature** ```ts export declare const alt: typeof alt ``` Added in v2.0.0 ## alternative **Signature** ```ts export declare const alternative: typeof alternative ``` Added in v2.0.0 ## applicative **Signature** ```ts export declare const applicative: typeof applicative ``` Added in v2.0.0 ## apply **Signature** ```ts export declare const apply: typeof apply ``` Added in v2.0.0 ## bifunctor **Signature** ```ts export declare const bifunctor: typeof bifunctor ``` Added in v2.0.0 ## booleanAlgebra **Signature** ```ts export declare const booleanAlgebra: typeof booleanAlgebra ``` Added in v2.0.0 ## bounded **Signature** ```ts export declare const bounded: typeof bounded ``` Added in v2.0.0 ## boundedDistributiveLattice **Signature** ```ts export declare const boundedDistributiveLattice: typeof boundedDistributiveLattice ``` Added in v2.0.0 ## boundedJoinSemilattice **Signature** ```ts export declare const boundedJoinSemilattice: typeof boundedJoinSemilattice ``` Added in v2.0.0 ## boundedLattice **Signature** ```ts export declare const boundedLattice: typeof boundedLattice ``` Added in v2.0.0 ## boundedMeetSemilattice **Signature** ```ts export declare const boundedMeetSemilattice: typeof boundedMeetSemilattice ``` Added in v2.0.0 ## category **Signature** ```ts export declare const category: typeof category ``` Added in v2.0.0 ## chain **Signature** ```ts export declare const chain: typeof chain ``` Added in v2.0.0 ## chainRec **Signature** ```ts export declare const chainRec: typeof chainRec ``` Added in v2.0.0 ## choice **Signature** ```ts export declare const choice: typeof choice ``` Added in v2.0.0 ## comonad **Signature** ```ts export declare const comonad: typeof comonad ``` Added in v2.0.0 ## compactable **Signature** ```ts export declare const compactable: typeof compactable ``` Added in v2.0.0 ## contravariant **Signature** ```ts export declare const contravariant: typeof contravariant ``` Added in v2.0.0 ## distributiveLattice **Signature** ```ts export declare const distributiveLattice: typeof distributiveLattice ``` Added in v2.0.0 ## eq **Signature** ```ts export declare const eq: typeof eq ``` Added in v2.0.0 ## extend **Signature** ```ts export declare const extend: typeof extend ``` Added in v2.0.0 ## field **Signature** ```ts export declare const field: typeof field ``` Added in v2.0.0 ## filterable **Signature** ```ts export declare const filterable: typeof filterable ``` Added in v2.0.0 ## filterableWithIndex **Signature** ```ts export declare const filterableWithIndex: typeof filterableWithIndex ``` Added in v2.0.0 ## foldable **Signature** ```ts export declare const foldable: typeof foldable ``` Added in v2.0.0 ## foldableWithIndex **Signature** ```ts export declare const foldableWithIndex: typeof foldableWithIndex ``` Added in v2.0.0 ## fromEither **Signature** ```ts export declare const fromEither: typeof fromEither ``` Added in v2.10.0 ## fromIO **Signature** ```ts export declare const fromIO: typeof fromIO ``` Added in v2.10.0 ## fromReader **Signature** ```ts export declare const fromReader: typeof fromReader ``` Added in v2.11.0 ## fromState **Signature** ```ts export declare const fromState: typeof fromState ``` Added in v2.11.0 ## fromTask **Signature** ```ts export declare const fromTask: typeof fromTask ``` Added in v2.10.0 ## fromThese **Signature** ```ts export declare const fromThese: typeof fromThese ``` Added in v2.11.0 ## functor **Signature** ```ts export declare const functor: typeof functor ``` Added in v2.0.0 ## functorWithIndex **Signature** ```ts export declare const functorWithIndex: typeof functorWithIndex ``` Added in v2.0.0 ## group **Signature** ```ts export declare const group: typeof group ``` Added in v2.0.0 ## heytingAlgebra **Signature** ```ts export declare const heytingAlgebra: typeof heytingAlgebra ``` Added in v2.0.0 ## invariant **Signature** ```ts export declare const invariant: typeof invariant ``` Added in v2.0.0 ## joinSemilattice **Signature** ```ts export declare const joinSemilattice: typeof joinSemilattice ``` Added in v2.0.0 ## lattice **Signature** ```ts export declare const lattice: typeof lattice ``` Added in v2.0.0 ## magma **Signature** ```ts export declare const magma: typeof magma ``` Added in v2.0.0 ## meetSemilattice **Signature** ```ts export declare const meetSemilattice: typeof meetSemilattice ``` Added in v2.0.0 ## monad **Signature** ```ts export declare const monad: typeof monad ``` Added in v2.0.0 ## monadIO **Signature** ```ts export declare const monadIO: typeof monadIO ``` Added in v2.0.0 ## monadTask **Signature** ```ts export declare const monadTask: typeof monadTask ``` Added in v2.0.0 ## monadThrow **Signature** ```ts export declare const monadThrow: typeof monadThrow ``` Added in v2.0.0 ## monoid **Signature** ```ts export declare const monoid: typeof monoid ``` Added in v2.0.0 ## ord **Signature** ```ts export declare const ord: typeof ord ``` Added in v2.0.0 ## pointed **Signature** ```ts export declare const pointed: typeof pointed ``` Added in v2.10.0 ## profunctor **Signature** ```ts export declare const profunctor: typeof profunctor ``` Added in v2.0.0 ## ring **Signature** ```ts export declare const ring: typeof ring ``` Added in v2.0.0 ## semigroup **Signature** ```ts export declare const semigroup: typeof semigroup ``` Added in v2.0.0 ## semigroupoid **Signature** ```ts export declare const semigroupoid: typeof semigroupoid ``` Added in v2.0.0 ## semiring **Signature** ```ts export declare const semiring: typeof semiring ``` Added in v2.0.0 ## show **Signature** ```ts export declare const show: typeof show ``` Added in v2.0.0 ## strong **Signature** ```ts export declare const strong: typeof strong ``` Added in v2.0.0 ## traversable **Signature** ```ts export declare const traversable: typeof traversable ``` Added in v2.0.0 ## traversableWithIndex **Signature** ```ts export declare const traversableWithIndex: typeof traversableWithIndex ``` Added in v2.0.0 ## unfoldable **Signature** ```ts export declare const unfoldable: typeof unfoldable ``` Added in v2.0.0 ## witherable **Signature** ```ts export declare const witherable: typeof witherable ``` Added in v2.0.0 ## zero **Signature** ```ts export declare const zero: typeof zero ``` Added in v2.11.0 # monad transformers ## eitherT **Signature** ```ts export declare const eitherT: typeof eitherT ``` Added in v2.0.0 ## optionT **Signature** ```ts export declare const optionT: typeof optionT ``` Added in v2.0.0 ## readerT **Signature** ```ts export declare const readerT: typeof readerT ``` Added in v2.0.0 ## stateT **Signature** ```ts export declare const stateT: typeof stateT ``` Added in v2.0.0 ## theseT **Signature** ```ts export declare const theseT: typeof theseT ``` Added in v2.4.0 ## writerT **Signature** ```ts export declare const writerT: typeof writerT ``` Added in v2.4.0 # utils ## boolean **Signature** ```ts export declare const boolean: typeof boolean ``` Added in v2.2.0 ## console **Signature** ```ts export declare const console: typeof console ``` Added in v2.0.0 ## date **Signature** ```ts export declare const date: typeof date ``` Added in v2.0.0 ## function **Signature** ```ts export declare const function: typeof function_ ``` Added in v2.0.0 ## hkt **Signature** ```ts export declare const hkt: typeof hkt ``` Added in v2.0.0 ## ioRef **Signature** ```ts export declare const ioRef: typeof ioRef ``` Added in v2.0.0 ## json **Signature** ```ts export declare const json: typeof json ``` Added in v2.10.0 ## naturalTransformation **Signature** ```ts export declare const naturalTransformation: typeof naturalTransformation ``` Added in v2.11.0 ## number **Signature** ```ts export declare const number: typeof number ``` Added in v2.10.0 ## ordering **Signature** ```ts export declare const ordering: typeof ordering ``` Added in v2.0.0 ## pipeable **Signature** ```ts export declare const pipeable: typeof pipeable ``` Added in v2.0.0 ## random **Signature** ```ts export declare const random: typeof random ``` Added in v2.0.0 ## string **Signature** ```ts export declare const string: typeof string ``` Added in v2.10.0 ## struct **Signature** ```ts export declare const struct: typeof struct ``` Added in v2.10.0 # zone of death ## ~~void~~ **Signature** ```ts export declare const void: typeof void_ ``` Added in v2.11.0 ================================================ FILE: docs/modules/number.ts.md ================================================ --- title: number.ts nav_order: 67 parent: Modules --- ## number overview Added in v2.10.0 ---

Table of contents

- [instances](#instances) - [Bounded](#bounded) - [Eq](#eq) - [Field](#field) - [MagmaSub](#magmasub) - [MonoidProduct](#monoidproduct) - [MonoidSum](#monoidsum) - [Ord](#ord) - [SemigroupProduct](#semigroupproduct) - [SemigroupSum](#semigroupsum) - [Show](#show) - [refinements](#refinements) - [isNumber](#isnumber) --- # instances ## Bounded **Signature** ```ts export declare const Bounded: B.Bounded ``` Added in v2.10.0 ## Eq **Signature** ```ts export declare const Eq: E.Eq ``` Added in v2.10.0 ## Field **Signature** ```ts export declare const Field: F.Field ``` Added in v2.10.0 ## MagmaSub **Signature** ```ts export declare const MagmaSub: Magma ``` Added in v2.11.0 ## MonoidProduct `number` monoid under multiplication. The `empty` value is `1`. **Signature** ```ts export declare const MonoidProduct: Monoid ``` **Example** ```ts import { MonoidProduct } from 'fp-ts/number' assert.deepStrictEqual(MonoidProduct.concat(2, MonoidProduct.empty), 2) ``` Added in v2.10.0 ## MonoidSum `number` monoid under addition. The `empty` value is `0`. **Signature** ```ts export declare const MonoidSum: Monoid ``` **Example** ```ts import { MonoidSum } from 'fp-ts/number' assert.deepStrictEqual(MonoidSum.concat(2, MonoidSum.empty), 2) ``` Added in v2.10.0 ## Ord **Signature** ```ts export declare const Ord: O.Ord ``` Added in v2.10.0 ## SemigroupProduct `number` semigroup under multiplication. **Signature** ```ts export declare const SemigroupProduct: Semigroup ``` **Example** ```ts import { SemigroupProduct } from 'fp-ts/number' assert.deepStrictEqual(SemigroupProduct.concat(2, 3), 6) ``` Added in v2.10.0 ## SemigroupSum `number` semigroup under addition. **Signature** ```ts export declare const SemigroupSum: Semigroup ``` **Example** ```ts import { SemigroupSum } from 'fp-ts/number' assert.deepStrictEqual(SemigroupSum.concat(2, 3), 5) ``` Added in v2.10.0 ## Show **Signature** ```ts export declare const Show: S.Show ``` Added in v2.10.0 # refinements ## isNumber **Signature** ```ts export declare const isNumber: Refinement ``` Added in v2.11.0 ================================================ FILE: docs/modules/pipeable.ts.md ================================================ --- title: pipeable.ts nav_order: 72 parent: Modules --- ## pipeable overview Added in v2.0.0 ---

Table of contents

- [pipeable helper](#pipeable-helper) - [alt](#alt) - [ap](#ap) - [bimap](#bimap) - [chain](#chain) - [compose](#compose) - [contramap](#contramap) - [extend](#extend) - [filter](#filter) - [filterMap](#filtermap) - [filterMapWithIndex](#filtermapwithindex) - [filterWithIndex](#filterwithindex) - [foldMap](#foldmap) - [foldMapWithIndex](#foldmapwithindex) - [map](#map) - [mapLeft](#mapleft) - [mapWithIndex](#mapwithindex) - [partition](#partition) - [partitionMap](#partitionmap) - [partitionMapWithIndex](#partitionmapwithindex) - [partitionWithIndex](#partitionwithindex) - [promap](#promap) - [reduce](#reduce) - [reduceRight](#reduceright) - [reduceRightWithIndex](#reducerightwithindex) - [reduceWithIndex](#reducewithindex) - [utils](#utils) - [~~PipeableAlt3C~~ (interface)](#pipeablealt3c-interface) - [~~PipeableApply3C~~ (interface)](#pipeableapply3c-interface) - [~~PipeableBifunctor3C~~ (interface)](#pipeablebifunctor3c-interface) - [~~PipeableChain3C~~ (interface)](#pipeablechain3c-interface) - [~~PipeableCompactable3C~~ (interface)](#pipeablecompactable3c-interface) - [~~PipeableContravariant3C~~ (interface)](#pipeablecontravariant3c-interface) - [~~PipeableExtend3C~~ (interface)](#pipeableextend3c-interface) - [~~PipeableFilterable3C~~ (interface)](#pipeablefilterable3c-interface) - [~~PipeableFilterableWithIndex3C~~ (interface)](#pipeablefilterablewithindex3c-interface) - [~~PipeableFoldable3C~~ (interface)](#pipeablefoldable3c-interface) - [~~PipeableFoldableWithIndex3C~~ (interface)](#pipeablefoldablewithindex3c-interface) - [~~PipeableFunctor3C~~ (interface)](#pipeablefunctor3c-interface) - [~~PipeableFunctorWithIndex3C~~ (interface)](#pipeablefunctorwithindex3c-interface) - [~~PipeableMonadThrow3C~~ (interface)](#pipeablemonadthrow3c-interface) - [~~PipeableProfunctor3C~~ (interface)](#pipeableprofunctor3c-interface) - [~~PipeableSemigroupoid3C~~ (interface)](#pipeablesemigroupoid3c-interface) - [~~pipe~~](#pipe) - [zone of death](#zone-of-death) - [~~PipeableAlt1~~ (interface)](#pipeablealt1-interface) - [~~PipeableAlt2C~~ (interface)](#pipeablealt2c-interface) - [~~PipeableAlt2~~ (interface)](#pipeablealt2-interface) - [~~PipeableAlt3~~ (interface)](#pipeablealt3-interface) - [~~PipeableAlt4~~ (interface)](#pipeablealt4-interface) - [~~PipeableAlt~~ (interface)](#pipeablealt-interface) - [~~PipeableApply1~~ (interface)](#pipeableapply1-interface) - [~~PipeableApply2C~~ (interface)](#pipeableapply2c-interface) - [~~PipeableApply2~~ (interface)](#pipeableapply2-interface) - [~~PipeableApply3~~ (interface)](#pipeableapply3-interface) - [~~PipeableApply4~~ (interface)](#pipeableapply4-interface) - [~~PipeableApply~~ (interface)](#pipeableapply-interface) - [~~PipeableBifunctor2~~ (interface)](#pipeablebifunctor2-interface) - [~~PipeableBifunctor3~~ (interface)](#pipeablebifunctor3-interface) - [~~PipeableBifunctor4~~ (interface)](#pipeablebifunctor4-interface) - [~~PipeableBifunctor~~ (interface)](#pipeablebifunctor-interface) - [~~PipeableChain1~~ (interface)](#pipeablechain1-interface) - [~~PipeableChain2C~~ (interface)](#pipeablechain2c-interface) - [~~PipeableChain2~~ (interface)](#pipeablechain2-interface) - [~~PipeableChain3~~ (interface)](#pipeablechain3-interface) - [~~PipeableChain4~~ (interface)](#pipeablechain4-interface) - [~~PipeableChain~~ (interface)](#pipeablechain-interface) - [~~PipeableCompactable1~~ (interface)](#pipeablecompactable1-interface) - [~~PipeableCompactable2C~~ (interface)](#pipeablecompactable2c-interface) - [~~PipeableCompactable2~~ (interface)](#pipeablecompactable2-interface) - [~~PipeableCompactable3~~ (interface)](#pipeablecompactable3-interface) - [~~PipeableCompactable4~~ (interface)](#pipeablecompactable4-interface) - [~~PipeableCompactable~~ (interface)](#pipeablecompactable-interface) - [~~PipeableContravariant1~~ (interface)](#pipeablecontravariant1-interface) - [~~PipeableContravariant2C~~ (interface)](#pipeablecontravariant2c-interface) - [~~PipeableContravariant2~~ (interface)](#pipeablecontravariant2-interface) - [~~PipeableContravariant3~~ (interface)](#pipeablecontravariant3-interface) - [~~PipeableContravariant4~~ (interface)](#pipeablecontravariant4-interface) - [~~PipeableContravariant~~ (interface)](#pipeablecontravariant-interface) - [~~PipeableExtend1~~ (interface)](#pipeableextend1-interface) - [~~PipeableExtend2C~~ (interface)](#pipeableextend2c-interface) - [~~PipeableExtend2~~ (interface)](#pipeableextend2-interface) - [~~PipeableExtend3~~ (interface)](#pipeableextend3-interface) - [~~PipeableExtend4~~ (interface)](#pipeableextend4-interface) - [~~PipeableExtend~~ (interface)](#pipeableextend-interface) - [~~PipeableFilterable1~~ (interface)](#pipeablefilterable1-interface) - [~~PipeableFilterable2C~~ (interface)](#pipeablefilterable2c-interface) - [~~PipeableFilterable2~~ (interface)](#pipeablefilterable2-interface) - [~~PipeableFilterable3~~ (interface)](#pipeablefilterable3-interface) - [~~PipeableFilterable4~~ (interface)](#pipeablefilterable4-interface) - [~~PipeableFilterableWithIndex1~~ (interface)](#pipeablefilterablewithindex1-interface) - [~~PipeableFilterableWithIndex2C~~ (interface)](#pipeablefilterablewithindex2c-interface) - [~~PipeableFilterableWithIndex2~~ (interface)](#pipeablefilterablewithindex2-interface) - [~~PipeableFilterableWithIndex3~~ (interface)](#pipeablefilterablewithindex3-interface) - [~~PipeableFilterableWithIndex4~~ (interface)](#pipeablefilterablewithindex4-interface) - [~~PipeableFilterableWithIndex~~ (interface)](#pipeablefilterablewithindex-interface) - [~~PipeableFilterable~~ (interface)](#pipeablefilterable-interface) - [~~PipeableFoldable1~~ (interface)](#pipeablefoldable1-interface) - [~~PipeableFoldable2C~~ (interface)](#pipeablefoldable2c-interface) - [~~PipeableFoldable2~~ (interface)](#pipeablefoldable2-interface) - [~~PipeableFoldable3~~ (interface)](#pipeablefoldable3-interface) - [~~PipeableFoldable4~~ (interface)](#pipeablefoldable4-interface) - [~~PipeableFoldableWithIndex1~~ (interface)](#pipeablefoldablewithindex1-interface) - [~~PipeableFoldableWithIndex2C~~ (interface)](#pipeablefoldablewithindex2c-interface) - [~~PipeableFoldableWithIndex2~~ (interface)](#pipeablefoldablewithindex2-interface) - [~~PipeableFoldableWithIndex3~~ (interface)](#pipeablefoldablewithindex3-interface) - [~~PipeableFoldableWithIndex4~~ (interface)](#pipeablefoldablewithindex4-interface) - [~~PipeableFoldableWithIndex~~ (interface)](#pipeablefoldablewithindex-interface) - [~~PipeableFoldable~~ (interface)](#pipeablefoldable-interface) - [~~PipeableFunctor1~~ (interface)](#pipeablefunctor1-interface) - [~~PipeableFunctor2C~~ (interface)](#pipeablefunctor2c-interface) - [~~PipeableFunctor2~~ (interface)](#pipeablefunctor2-interface) - [~~PipeableFunctor3~~ (interface)](#pipeablefunctor3-interface) - [~~PipeableFunctor4~~ (interface)](#pipeablefunctor4-interface) - [~~PipeableFunctorWithIndex1~~ (interface)](#pipeablefunctorwithindex1-interface) - [~~PipeableFunctorWithIndex2C~~ (interface)](#pipeablefunctorwithindex2c-interface) - [~~PipeableFunctorWithIndex2~~ (interface)](#pipeablefunctorwithindex2-interface) - [~~PipeableFunctorWithIndex3~~ (interface)](#pipeablefunctorwithindex3-interface) - [~~PipeableFunctorWithIndex4~~ (interface)](#pipeablefunctorwithindex4-interface) - [~~PipeableFunctorWithIndex~~ (interface)](#pipeablefunctorwithindex-interface) - [~~PipeableFunctor~~ (interface)](#pipeablefunctor-interface) - [~~PipeableMonadThrow1~~ (interface)](#pipeablemonadthrow1-interface) - [~~PipeableMonadThrow2C~~ (interface)](#pipeablemonadthrow2c-interface) - [~~PipeableMonadThrow2~~ (interface)](#pipeablemonadthrow2-interface) - [~~PipeableMonadThrow3~~ (interface)](#pipeablemonadthrow3-interface) - [~~PipeableMonadThrow4~~ (interface)](#pipeablemonadthrow4-interface) - [~~PipeableMonadThrow~~ (interface)](#pipeablemonadthrow-interface) - [~~PipeableProfunctor2C~~ (interface)](#pipeableprofunctor2c-interface) - [~~PipeableProfunctor2~~ (interface)](#pipeableprofunctor2-interface) - [~~PipeableProfunctor3~~ (interface)](#pipeableprofunctor3-interface) - [~~PipeableProfunctor4~~ (interface)](#pipeableprofunctor4-interface) - [~~PipeableProfunctor~~ (interface)](#pipeableprofunctor-interface) - [~~PipeableSemigroupoid2C~~ (interface)](#pipeablesemigroupoid2c-interface) - [~~PipeableSemigroupoid2~~ (interface)](#pipeablesemigroupoid2-interface) - [~~PipeableSemigroupoid3~~ (interface)](#pipeablesemigroupoid3-interface) - [~~PipeableSemigroupoid4~~ (interface)](#pipeablesemigroupoid4-interface) - [~~PipeableSemigroupoid~~ (interface)](#pipeablesemigroupoid-interface) - [~~pipeable~~](#pipeable) --- # pipeable helper ## alt Returns a pipeable `alt` **Signature** ```ts export declare function alt( F: Alt4 ): (that: LazyArg>) => (fa: Kind4) => Kind4 export declare function alt( F: Alt3 ): (that: LazyArg>) => (fa: Kind3) => Kind3 export declare function alt( F: Alt3C ): (that: LazyArg>) => (fa: Kind3) => Kind3 export declare function alt( F: Alt2 ): (that: LazyArg>) => (fa: Kind2) => Kind2 export declare function alt( F: Alt2C ):
(that: LazyArg>) => (fa: Kind2) => Kind2 export declare function alt( F: Alt1 ): (that: LazyArg>) => (fa: Kind) => Kind export declare function alt(F: Alt): (that: LazyArg>) => (fa: HKT) => HKT ``` Added in v2.13.0 ## ap Returns a pipeable `ap` **Signature** ```ts export declare function ap( F: Apply4 ): (fa: Kind4) => (fab: Kind4 B>) => Kind4 export declare function ap( F: Apply3 ): (fa: Kind3) => (fab: Kind3 B>) => Kind3 export declare function ap( F: Apply3C ): (fa: Kind3) => (fab: Kind3 B>) => Kind3 export declare function ap( F: Apply2 ): (fa: Kind2) => (fab: Kind2 B>) => Kind2 export declare function ap( F: Apply2C ): (fa: Kind2) => (fab: Kind2 B>) => Kind2 export declare function ap( F: Apply1 ): (fa: Kind) => (fab: Kind B>) => Kind export declare function ap(F: Apply): (fa: HKT) => (fab: HKT B>) => HKT ``` Added in v2.13.0 ## bimap Returns a pipeable `bimap` **Signature** ```ts export declare function bimap( F: Bifunctor4 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind4) => Kind4 export declare function bimap( F: Bifunctor3 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind3) => Kind3 export declare function bimap( F: Bifunctor3C ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind3) => Kind3 export declare function bimap( F: Bifunctor2 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2) => Kind2 export declare function bimap( F: Bifunctor2C ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2) => Kind2 export declare function bimap( F: Bifunctor ): (f: (e: E) => G, g: (a: A) => B) => (fea: HKT2) => HKT2 ``` Added in v2.13.0 ## chain Returns a pipeable `chain` **Signature** ```ts export declare function chain( F: Chain4 ): (f: (a: A) => Kind4) => (fa: Kind4) => Kind4 export declare function chain( F: Chain3 ): (f: (a: A) => Kind3) => (fa: Kind3) => Kind3 export declare function chain( F: Chain3C ): (f: (a: A) => Kind3) => (fa: Kind3) => Kind3 export declare function chain( F: Chain2 ): (f: (a: A) => Kind2) => (fa: Kind2) => Kind2 export declare function chain( F: Chain2C ): (f: (a: A) => Kind2) => (fa: Kind2) => Kind2 export declare function chain( F: Chain1 ): (f: (a: A) => Kind) => (fa: Kind) => Kind export declare function chain(F: Chain): (f: (a: A) => HKT) => (fa: HKT) => HKT ``` Added in v2.13.0 ## compose Returns a pipeable `compose` **Signature** ```ts export declare function compose( F: Semigroupoid4 ): (ea: Kind4) => (ab: Kind4) => Kind4 export declare function compose( F: Semigroupoid3 ): (ea: Kind3) => (ab: Kind3) => Kind3 export declare function compose( F: Semigroupoid3C ): (ea: Kind3) => (ab: Kind3) => Kind3 export declare function compose( F: Semigroupoid2 ): (ea: Kind2) => (ab: Kind2) => Kind2 export declare function compose( F: Semigroupoid2C ): (ea: Kind2) => (ab: Kind2) => Kind2 export declare function compose( F: Semigroupoid ): (ea: HKT2) => (ab: HKT2) => HKT2 ``` Added in v2.13.0 ## contramap Returns a pipeable `contramap` **Signature** ```ts export declare function contramap( F: Contravariant4 ): (f: (b: B) => A) => (fa: Kind4) => Kind4 export declare function contramap( F: Contravariant3 ): (f: (b: B) => A) => (fa: Kind3) => Kind3 export declare function contramap( F: Contravariant3C ): (f: (b: B) => A) => (fa: Kind3) => Kind3 export declare function contramap( F: Contravariant2 ): (f: (b: B) => A) => (fa: Kind2) => Kind2 export declare function contramap( F: Contravariant2C ): (f: (b: B) => A) => (fa: Kind2) => Kind2 export declare function contramap( F: Contravariant1 ): (f: (b: B) => A) => (fa: Kind) => Kind export declare function contramap(F: Contravariant): (f: (b: B) => A) => (fa: HKT) => HKT ``` Added in v2.13.0 ## extend Returns a pipeable `extend` **Signature** ```ts export declare function extend( F: Extend4 ): (f: (wa: Kind4) => B) => (wa: Kind4) => Kind4 export declare function extend( F: Extend3 ): (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 export declare function extend( F: Extend3C ): (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 export declare function extend( F: Extend2 ): (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 export declare function extend( F: Extend2C ): (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 export declare function extend( F: Extend1 ): (f: (wa: Kind) => B) => (wa: Kind) => Kind export declare function extend(F: Extend): (f: (wa: HKT) => B) => (wa: HKT) => HKT ``` Added in v2.13.0 ## filter Returns a pipeable `filter` **Signature** ```ts export declare function filter( F: Filterable4 ): { (refinement: Refinement): (fa: Kind4) => Kind4 (predicate: Predicate): (fa: Kind4) => Kind4 } export declare function filter( F: Filterable3 ): { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } export declare function filter( F: Filterable3C ): { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } export declare function filter( F: Filterable2 ): { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } export declare function filter( F: Filterable2C ): { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } export declare function filter( F: Filterable1 ): { (refinement: Refinement): (fa: Kind) => Kind (predicate: Predicate): (fa: Kind) => Kind } export declare function filter(F: Filterable): { (refinement: Refinement): (fa: HKT) => HKT (predicate: Predicate): (fa: HKT) => HKT } ``` Added in v2.13.0 ## filterMap Returns a pipeable `filterMap` **Signature** ```ts export declare function filterMap( F: Filterable4 ): (f: (a: A) => Option) => (fa: Kind4) => Kind4 export declare function filterMap( F: Filterable3 ): (f: (a: A) => Option) => (fa: Kind3) => Kind3 export declare function filterMap( F: Filterable3C ): (f: (a: A) => Option) => (fa: Kind3) => Kind3 export declare function filterMap( F: Filterable2 ): (f: (a: A) => Option) => (fa: Kind2) => Kind2 export declare function filterMap( F: Filterable2C ): (f: (a: A) => Option) => (fa: Kind2) => Kind2 export declare function filterMap( F: Filterable1 ): (f: (a: A) => Option) => (fa: Kind) => Kind export declare function filterMap(F: Filterable): (f: (a: A) => Option) => (fa: HKT) => HKT ``` Added in v2.13.0 ## filterMapWithIndex Returns a pipeable `filterMapWithIndex` **Signature** ```ts export declare function filterMapWithIndex( F: FilterableWithIndex4 ): (f: (i: I, a: A) => Option) => (fa: Kind4) => Kind4 export declare function filterMapWithIndex( F: FilterableWithIndex3 ): (f: (i: I, a: A) => Option) => (fa: Kind3) => Kind3 export declare function filterMapWithIndex( F: FilterableWithIndex3C ): (f: (i: I, a: A) => Option) => (fa: Kind3) => Kind3 export declare function filterMapWithIndex( F: FilterableWithIndex2 ): (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 export declare function filterMapWithIndex( F: FilterableWithIndex2C ): (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 export declare function filterMapWithIndex( F: FilterableWithIndex1 ): (f: (i: I, a: A) => Option) => (fa: Kind) => Kind export declare function filterMapWithIndex( F: FilterableWithIndex ): (f: (i: I, a: A) => Option) => (fa: HKT) => HKT ``` Added in v2.13.0 ## filterWithIndex Returns a pipeable `filterWithIndex` **Signature** ```ts export declare function filterWithIndex( F: FilterableWithIndex4 ): { (refinement: RefinementWithIndex): ( fa: Kind4 ) => Kind4 (predicate: PredicateWithIndex): (fa: Kind4) => Kind4 } export declare function filterWithIndex( F: FilterableWithIndex3 ): { (refinement: RefinementWithIndex): (fa: Kind3) => Kind3 (predicate: PredicateWithIndex): (fa: Kind3) => Kind3 } export declare function filterWithIndex( F: FilterableWithIndex3C ): { (refinement: RefinementWithIndex): (fa: Kind3) => Kind3 (predicate: PredicateWithIndex): (fa: Kind3) => Kind3 } export declare function filterWithIndex( F: FilterableWithIndex2 ): { (refinement: RefinementWithIndex): (fa: Kind2) => Kind2 (predicate: PredicateWithIndex): (fa: Kind2) => Kind2 } export declare function filterWithIndex( F: FilterableWithIndex2C ): { (refinement: RefinementWithIndex): (fa: Kind2) => Kind2 (predicate: PredicateWithIndex): (fa: Kind2) => Kind2 } export declare function filterWithIndex( F: FilterableWithIndex1 ): { (refinement: RefinementWithIndex): (fa: Kind) => Kind (predicate: PredicateWithIndex): (fa: Kind) => Kind } export declare function filterWithIndex( F: FilterableWithIndex ): { (refinement: RefinementWithIndex): (fa: HKT) => HKT (predicate: PredicateWithIndex): (fa: HKT) => HKT } ``` Added in v2.13.0 ## foldMap Returns a pipeable `foldMap` **Signature** ```ts export declare function foldMap( F: Foldable4 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind4) => M export declare function foldMap( F: Foldable3 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M export declare function foldMap( F: Foldable3C ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M export declare function foldMap( F: Foldable2 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M export declare function foldMap( F: Foldable2C ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M export declare function foldMap( F: Foldable1 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind) => M export declare function foldMap(F: Foldable): (M: Monoid) => (f: (a: A) => M) => (fa: HKT) => M ``` Added in v2.13.0 ## foldMapWithIndex Returns a pipeable `foldMapWithIndex` **Signature** ```ts export declare function foldMapWithIndex( F: FoldableWithIndex4 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind4) => M export declare function foldMapWithIndex( F: FoldableWithIndex3 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M export declare function foldMapWithIndex( F: FoldableWithIndex3C ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M export declare function foldMapWithIndex( F: FoldableWithIndex2 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M export declare function foldMapWithIndex( F: FoldableWithIndex2C ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M export declare function foldMapWithIndex( F: FoldableWithIndex1 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind) => M export declare function foldMapWithIndex( F: FoldableWithIndex ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: HKT) => M ``` Added in v2.13.0 ## map Returns a pipeable `map` **Signature** ```ts export declare function map( F: Functor4 ): (f: (a: A) => B) => (fa: Kind4) => Kind4 export declare function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3) => Kind3 export declare function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3) => Kind3 export declare function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2) => Kind2 export declare function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2) => Kind2 export declare function map(F: Functor1): (f: (a: A) => B) => (fa: Kind) => Kind export declare function map(F: Functor): (f: (a: A) => B) => (fa: HKT) => HKT ``` Added in v2.13.0 ## mapLeft Returns a pipeable `mapLeft` **Signature** ```ts export declare function mapLeft( F: Bifunctor4 ): (f: (e: E) => G) => (fea: Kind4) => Kind4 export declare function mapLeft( F: Bifunctor3 ): (f: (e: E) => G) => (fea: Kind3) => Kind3 export declare function mapLeft( F: Bifunctor3C ): (f: (e: E) => G) => (fea: Kind3) => Kind3 export declare function mapLeft( F: Bifunctor2 ): (f: (e: E) => G) => (fea: Kind2) => Kind2 export declare function mapLeft( F: Bifunctor2C ): (f: (e: E) => G) => (fea: Kind2) => Kind2 export declare function mapLeft(F: Bifunctor): (f: (e: E) => G) => (fea: HKT2) => HKT2 ``` Added in v2.13.0 ## mapWithIndex Returns a pipeable `mapWithIndex` **Signature** ```ts export declare function mapWithIndex( F: FunctorWithIndex4 ): (f: (i: I, a: A) => B) => (fa: Kind4) => Kind4 export declare function mapWithIndex( F: FunctorWithIndex3 ): (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 export declare function mapWithIndex( F: FunctorWithIndex3C ): (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 export declare function mapWithIndex( F: FunctorWithIndex2 ): (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 export declare function mapWithIndex( F: FunctorWithIndex2C ): (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 export declare function mapWithIndex( F: FunctorWithIndex1 ): (f: (i: I, a: A) => B) => (fa: Kind) => Kind export declare function mapWithIndex( F: FunctorWithIndex ): (f: (i: I, a: A) => B) => (fa: HKT) => HKT ``` Added in v2.13.0 ## partition Returns a pipeable `partition` **Signature** ```ts export declare function partition( F: Filterable4 ): { (refinement: Refinement): ( fa: Kind4 ) => Separated, Kind4> (predicate: Predicate): ( fa: Kind4 ) => Separated, Kind4> } export declare function partition( F: Filterable3 ): { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } export declare function partition( F: Filterable3C ): { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } export declare function partition( F: Filterable2 ): { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } export declare function partition( F: Filterable2C ): { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } export declare function partition( F: Filterable1 ): { (refinement: Refinement): (fa: Kind) => Separated, Kind> (predicate: Predicate): (fa: Kind) => Separated, Kind> } export declare function partition(F: Filterable): { (refinement: Refinement): (fa: HKT) => Separated, HKT> (predicate: Predicate): (fa: HKT) => Separated, HKT> } ``` Added in v2.13.0 ## partitionMap Returns a pipeable `partitionMap` **Signature** ```ts export declare function partitionMap( F: Filterable4 ): ( f: (a: A) => Either ) => (fa: Kind4) => Separated, Kind4> export declare function partitionMap( F: Filterable3 ): ( f: (a: A) => Either ) => (fa: Kind3) => Separated, Kind3> export declare function partitionMap( F: Filterable3C ): (f: (a: A) => Either) => (fa: Kind3) => Separated, Kind3> export declare function partitionMap( F: Filterable2 ): (f: (a: A) => Either) => (fa: Kind2) => Separated, Kind2> export declare function partitionMap( F: Filterable2C ): (f: (a: A) => Either) => (fa: Kind2) => Separated, Kind2> export declare function partitionMap( F: Filterable1 ): (f: (a: A) => Either) => (fa: Kind) => Separated, Kind> export declare function partitionMap( F: Filterable ): (f: (a: A) => Either) => (fa: HKT) => Separated, HKT> ``` Added in v2.13.0 ## partitionMapWithIndex Returns a pipeable `partitionMapWithIndex` **Signature** ```ts export declare function partitionMapWithIndex( F: FilterableWithIndex4 ): ( f: (i: I, a: A) => Either ) => (fa: Kind4) => Separated, Kind4> export declare function partitionMapWithIndex( F: FilterableWithIndex3 ): ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> export declare function partitionMapWithIndex( F: FilterableWithIndex3C ): ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> export declare function partitionMapWithIndex( F: FilterableWithIndex2 ): (f: (i: I, a: A) => Either) => (fa: Kind2) => Separated, Kind2> export declare function partitionMapWithIndex( F: FilterableWithIndex2C ): (f: (i: I, a: A) => Either) => (fa: Kind2) => Separated, Kind2> export declare function partitionMapWithIndex( F: FilterableWithIndex1 ): (f: (i: I, a: A) => Either) => (fa: Kind) => Separated, Kind> export declare function partitionMapWithIndex( F: FilterableWithIndex ): (f: (i: I, a: A) => Either) => (fa: HKT) => Separated, HKT> ``` Added in v2.13.0 ## partitionWithIndex Returns a pipeable `partitionWithIndex` **Signature** ```ts export declare function partitionWithIndex( F: FilterableWithIndex4 ): { (refinement: RefinementWithIndex): ( fa: Kind4 ) => Separated, Kind4> (predicate: PredicateWithIndex): ( fa: Kind4 ) => Separated, Kind4> } export declare function partitionWithIndex( F: FilterableWithIndex3 ): { (refinement: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicate: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } export declare function partitionWithIndex( F: FilterableWithIndex3C ): { (refinement: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicate: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } export declare function partitionWithIndex( F: FilterableWithIndex2 ): { (refinement: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicate: PredicateWithIndex): (fa: Kind2) => Separated, Kind2> } export declare function partitionWithIndex( F: FilterableWithIndex2C ): { (refinement: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicate: PredicateWithIndex): (fa: Kind2) => Separated, Kind2> } export declare function partitionWithIndex( F: FilterableWithIndex1 ): { (refinement: RefinementWithIndex): (fa: Kind) => Separated, Kind> (predicate: PredicateWithIndex): (fa: Kind) => Separated, Kind> } export declare function partitionWithIndex( F: FilterableWithIndex ): { (refinement: RefinementWithIndex): (fa: HKT) => Separated, HKT> (predicate: PredicateWithIndex): (fa: HKT) => Separated, HKT> } ``` Added in v2.13.0 ## promap Returns a pipeable `promap` **Signature** ```ts export declare function promap( F: Profunctor4 ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind4) => Kind4 export declare function promap( F: Profunctor3 ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 export declare function promap( F: Profunctor3C ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 export declare function promap( F: Profunctor2 ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 export declare function promap( F: Profunctor2C ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 export declare function promap( F: Profunctor ): (f: (d: D) => E, g: (a: A) => B) => (fbc: HKT2) => HKT2 ``` Added in v2.13.0 ## reduce Returns a pipeable `reduce` **Signature** ```ts export declare function reduce( F: Foldable4 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind4) => B export declare function reduce( F: Foldable3 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B export declare function reduce( F: Foldable3C ): (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B export declare function reduce( F: Foldable2 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B export declare function reduce( F: Foldable2C ): (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B export declare function reduce( F: Foldable1 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind) => B export declare function reduce(F: Foldable): (b: B, f: (b: B, a: A) => B) => (fa: HKT) => B ``` Added in v2.13.0 ## reduceRight Returns a pipeable `reduceRight` **Signature** ```ts export declare function reduceRight( F: Foldable4 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind4) => B export declare function reduceRight( F: Foldable3 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B export declare function reduceRight( F: Foldable3C ): (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B export declare function reduceRight( F: Foldable2 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B export declare function reduceRight( F: Foldable2C ): (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B export declare function reduceRight( F: Foldable1 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind) => B export declare function reduceRight(F: Foldable): (b: B, f: (a: A, b: B) => B) => (fa: HKT) => B ``` Added in v2.13.0 ## reduceRightWithIndex Returns a pipeable `reduceRightWithIndex` **Signature** ```ts export declare function reduceRightWithIndex( F: FoldableWithIndex4 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind4) => B export declare function reduceRightWithIndex( F: FoldableWithIndex3 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B export declare function reduceRightWithIndex( F: FoldableWithIndex3C ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B export declare function reduceRightWithIndex( F: FoldableWithIndex2 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B export declare function reduceRightWithIndex( F: FoldableWithIndex2C ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B export declare function reduceRightWithIndex( F: FoldableWithIndex1 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind) => B export declare function reduceRightWithIndex( F: FoldableWithIndex ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: HKT) => B ``` Added in v2.13.0 ## reduceWithIndex Returns a pipeable `reduceWithIndex` **Signature** ```ts export declare function reduceWithIndex( F: FoldableWithIndex4 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind4) => B export declare function reduceWithIndex( F: FoldableWithIndex3 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B export declare function reduceWithIndex( F: FoldableWithIndex3C ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B export declare function reduceWithIndex( F: FoldableWithIndex2 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B export declare function reduceWithIndex( F: FoldableWithIndex2C ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B export declare function reduceWithIndex( F: FoldableWithIndex1 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind) => B export declare function reduceWithIndex( F: FoldableWithIndex ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: HKT) => B ``` Added in v2.13.0 # utils ## ~~PipeableAlt3C~~ (interface) **Signature** ```ts export interface PipeableAlt3C { readonly alt: (that: LazyArg>) => (fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableApply3C~~ (interface) **Signature** ```ts export interface PipeableApply3C extends PipeableFunctor3C { readonly ap: (fa: Kind3) => (fab: Kind3 B>) => Kind3 readonly apFirst: (fb: Kind3) => (fa: Kind3) => Kind3 readonly apSecond: (fb: Kind3) => (fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableBifunctor3C~~ (interface) **Signature** ```ts export interface PipeableBifunctor3C { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Kind3) => Kind3 readonly mapLeft: (f: (e: E) => G) => (fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableChain3C~~ (interface) **Signature** ```ts export interface PipeableChain3C extends PipeableApply3C { readonly chain: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly chainFirst: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly flatten: (mma: Kind3>) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableCompactable3C~~ (interface) **Signature** ```ts export interface PipeableCompactable3C { readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => Separated, Kind3> } ``` Added in v2.2.0 ## ~~PipeableContravariant3C~~ (interface) **Signature** ```ts export interface PipeableContravariant3C { readonly contramap: (f: (b: B) => A) => (fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableExtend3C~~ (interface) **Signature** ```ts export interface PipeableExtend3C extends PipeableFunctor3C { readonly extend: (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 readonly duplicate: (wa: Kind3) => Kind3> } ``` Added in v2.2.0 ## ~~PipeableFilterable3C~~ (interface) **Signature** ```ts export interface PipeableFilterable3C extends PipeableCompactable3C { readonly filter: { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind3) => Kind3 readonly partition: { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } ``` Added in v2.2.0 ## ~~PipeableFilterableWithIndex3C~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex3C extends PipeableFilterable3C { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind3) => Kind3 (predicateWithIndex: PredicateWithIndex): (fa: Kind3) => Kind3 } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind3) => Kind3 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicateWithIndex: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } ``` Added in v2.2.0 ## ~~PipeableFoldable3C~~ (interface) **Signature** ```ts export interface PipeableFoldable3C { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B } ``` Added in v2.2.0 ## ~~PipeableFoldableWithIndex3C~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex3C extends PipeableFoldable3C { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B } ``` Added in v2.2.0 ## ~~PipeableFunctor3C~~ (interface) **Signature** ```ts export interface PipeableFunctor3C { readonly map: (f: (a: A) => B) => (fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableFunctorWithIndex3C~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex3C extends PipeableFunctor3C { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableMonadThrow3C~~ (interface) **Signature** ```ts export interface PipeableMonadThrow3C { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind3 readonly fromEither: (ma: Either) => Kind3 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind3 ) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } } ``` Added in v2.2.0 ## ~~PipeableProfunctor3C~~ (interface) **Signature** ```ts export interface PipeableProfunctor3C extends PipeableFunctor3C { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~PipeableSemigroupoid3C~~ (interface) **Signature** ```ts export interface PipeableSemigroupoid3C { readonly compose: (la: Kind3) => (ab: Kind3) => Kind3 } ``` Added in v2.2.0 ## ~~pipe~~ Use [`pipe`](https://gcanti.github.io/fp-ts/modules/function.ts.html#pipe) from `function` module instead. **Signature** ```ts export declare const pipe: typeof pipeFromFunctionModule ``` Added in v2.0.0 # zone of death ## ~~PipeableAlt1~~ (interface) **Signature** ```ts export interface PipeableAlt1 { readonly alt: (that: LazyArg>) => (fa: Kind) => Kind } ``` Added in v2.0.0 ## ~~PipeableAlt2C~~ (interface) **Signature** ```ts export interface PipeableAlt2C { readonly alt: (that: LazyArg>) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableAlt2~~ (interface) **Signature** ```ts export interface PipeableAlt2 { readonly alt: (that: LazyArg>) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableAlt3~~ (interface) **Signature** ```ts export interface PipeableAlt3 { readonly alt: (that: LazyArg>) => (fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableAlt4~~ (interface) **Signature** ```ts export interface PipeableAlt4 { readonly alt: (that: LazyArg>) => (fa: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableAlt~~ (interface) **Signature** ```ts export interface PipeableAlt { readonly alt: (that: LazyArg>) => (fa: HKT) => HKT } ``` Added in v2.0.0 ## ~~PipeableApply1~~ (interface) **Signature** ```ts export interface PipeableApply1 extends PipeableFunctor1 { readonly ap: (fa: Kind) => (fab: Kind B>) => Kind readonly apFirst: (fb: Kind) => (fa: Kind) => Kind readonly apSecond: (fb: Kind) => (fa: Kind) => Kind } ``` Added in v2.0.0 ## ~~PipeableApply2C~~ (interface) **Signature** ```ts export interface PipeableApply2C extends PipeableFunctor2C { readonly ap: (fa: Kind2) => (fab: Kind2 B>) => Kind2 readonly apFirst: (fb: Kind2) => (fa: Kind2) => Kind2 readonly apSecond: (fb: Kind2) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableApply2~~ (interface) **Signature** ```ts export interface PipeableApply2 extends PipeableFunctor2 { readonly ap: (fa: Kind2) => (fab: Kind2 B>) => Kind2 readonly apFirst: (fb: Kind2) => (fa: Kind2) => Kind2 readonly apSecond: (fb: Kind2) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableApply3~~ (interface) **Signature** ```ts export interface PipeableApply3 extends PipeableFunctor3 { readonly ap: (fa: Kind3) => (fab: Kind3 B>) => Kind3 readonly apFirst: (fb: Kind3) => (fa: Kind3) => Kind3 readonly apSecond: (fb: Kind3) => (fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableApply4~~ (interface) **Signature** ```ts export interface PipeableApply4 extends PipeableFunctor4 { readonly ap: ( fa: Kind4 ) => (fab: Kind4 B>) => Kind4 readonly apFirst: (fb: Kind4) => (fa: Kind4) => Kind4 readonly apSecond: (fb: Kind4) => (fa: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableApply~~ (interface) **Signature** ```ts export interface PipeableApply extends PipeableFunctor { readonly ap: (fa: HKT) => (fab: HKT B>) => HKT readonly apFirst: (fb: HKT) => (fa: HKT) => HKT readonly apSecond: (fb: HKT) => (fa: HKT) => HKT } ``` Added in v2.0.0 ## ~~PipeableBifunctor2~~ (interface) **Signature** ```ts export interface PipeableBifunctor2 { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Kind2) => Kind2 readonly mapLeft: (f: (e: E) => G) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableBifunctor3~~ (interface) **Signature** ```ts export interface PipeableBifunctor3 { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Kind3) => Kind3 readonly mapLeft: (f: (e: E) => G) => (fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableBifunctor4~~ (interface) **Signature** ```ts export interface PipeableBifunctor4 { readonly bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: Kind4) => Kind4 readonly mapLeft: (f: (e: E) => G) => (fa: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableBifunctor~~ (interface) **Signature** ```ts export interface PipeableBifunctor { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: HKT2) => HKT2 readonly mapLeft: (f: (e: E) => G) => (fa: HKT2) => HKT2 } ``` Added in v2.0.0 ## ~~PipeableChain1~~ (interface) **Signature** ```ts export interface PipeableChain1 extends PipeableApply1 { readonly chain: (f: (a: A) => Kind) => (ma: Kind) => Kind readonly chainFirst: (f: (a: A) => Kind) => (ma: Kind) => Kind readonly flatten: (mma: Kind>) => Kind } ``` Added in v2.0.0 ## ~~PipeableChain2C~~ (interface) **Signature** ```ts export interface PipeableChain2C extends PipeableApply2C { readonly chain: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly chainFirst: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly flatten: (mma: Kind2>) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableChain2~~ (interface) **Signature** ```ts export interface PipeableChain2 extends PipeableApply2 { readonly chain: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly chainFirst: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly flatten: (mma: Kind2>) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableChain3~~ (interface) **Signature** ```ts export interface PipeableChain3 extends PipeableApply3 { readonly chain: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly chainFirst: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly flatten: (mma: Kind3>) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableChain4~~ (interface) **Signature** ```ts export interface PipeableChain4 extends PipeableApply4 { readonly chain: ( f: (a: A) => Kind4 ) => (ma: Kind4) => Kind4 readonly chainFirst: ( f: (a: A) => Kind4 ) => (ma: Kind4) => Kind4 readonly flatten: (mma: Kind4>) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableChain~~ (interface) **Signature** ```ts export interface PipeableChain extends PipeableApply { readonly chain: (f: (a: A) => HKT) => (ma: HKT) => HKT readonly chainFirst: (f: (a: A) => HKT) => (ma: HKT) => HKT readonly flatten: (mma: HKT>) => HKT } ``` Added in v2.0.0 ## ~~PipeableCompactable1~~ (interface) **Signature** ```ts export interface PipeableCompactable1 { readonly compact: (fa: Kind>) => Kind readonly separate: (fa: Kind>) => Separated, Kind> } ``` Added in v2.0.0 ## ~~PipeableCompactable2C~~ (interface) **Signature** ```ts export interface PipeableCompactable2C { readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => Separated, Kind2> } ``` Added in v2.0.0 ## ~~PipeableCompactable2~~ (interface) **Signature** ```ts export interface PipeableCompactable2 { readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => Separated, Kind2> } ``` Added in v2.0.0 ## ~~PipeableCompactable3~~ (interface) **Signature** ```ts export interface PipeableCompactable3 { readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => Separated, Kind3> } ``` Added in v2.0.0 ## ~~PipeableCompactable4~~ (interface) **Signature** ```ts export interface PipeableCompactable4 { readonly compact: (fa: Kind4>) => Kind4 readonly separate: ( fa: Kind4> ) => Separated, Kind4> } ``` Added in v2.0.0 ## ~~PipeableCompactable~~ (interface) **Signature** ```ts export interface PipeableCompactable { readonly compact: (fa: HKT>) => HKT readonly separate: (fa: HKT>) => Separated, HKT> } ``` Added in v2.0.0 ## ~~PipeableContravariant1~~ (interface) **Signature** ```ts export interface PipeableContravariant1 { readonly contramap: (f: (b: B) => A) => (fa: Kind) => Kind } ``` Added in v2.0.0 ## ~~PipeableContravariant2C~~ (interface) **Signature** ```ts export interface PipeableContravariant2C { readonly contramap: (f: (b: B) => A) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableContravariant2~~ (interface) **Signature** ```ts export interface PipeableContravariant2 { readonly contramap: (f: (b: B) => A) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableContravariant3~~ (interface) **Signature** ```ts export interface PipeableContravariant3 { readonly contramap: (f: (b: B) => A) => (fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableContravariant4~~ (interface) **Signature** ```ts export interface PipeableContravariant4 { readonly contramap: (f: (b: B) => A) => (fa: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableContravariant~~ (interface) **Signature** ```ts export interface PipeableContravariant { readonly contramap: (f: (b: B) => A) => (fa: HKT) => HKT } ``` Added in v2.0.0 ## ~~PipeableExtend1~~ (interface) **Signature** ```ts export interface PipeableExtend1 extends PipeableFunctor1 { readonly extend: (f: (wa: Kind) => B) => (wa: Kind) => Kind readonly duplicate: (wa: Kind) => Kind> } ``` Added in v2.0.0 ## ~~PipeableExtend2C~~ (interface) **Signature** ```ts export interface PipeableExtend2C extends PipeableFunctor2C { readonly extend: (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 readonly duplicate: (wa: Kind2) => Kind2> } ``` Added in v2.0.0 ## ~~PipeableExtend2~~ (interface) **Signature** ```ts export interface PipeableExtend2 extends PipeableFunctor2 { readonly extend: (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 readonly duplicate: (wa: Kind2) => Kind2> } ``` Added in v2.0.0 ## ~~PipeableExtend3~~ (interface) **Signature** ```ts export interface PipeableExtend3 extends PipeableFunctor3 { readonly extend: (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 readonly duplicate: (wa: Kind3) => Kind3> } ``` Added in v2.0.0 ## ~~PipeableExtend4~~ (interface) **Signature** ```ts export interface PipeableExtend4 extends PipeableFunctor4 { readonly extend: ( f: (wa: Kind4) => B ) => (wa: Kind4) => Kind4 readonly duplicate: (wa: Kind4) => Kind4> } ``` Added in v2.0.0 ## ~~PipeableExtend~~ (interface) **Signature** ```ts export interface PipeableExtend extends PipeableFunctor { readonly extend: (f: (wa: HKT) => B) => (wa: HKT) => HKT readonly duplicate: (wa: HKT) => HKT> } ``` Added in v2.0.0 ## ~~PipeableFilterable1~~ (interface) **Signature** ```ts export interface PipeableFilterable1 extends PipeableCompactable1 { readonly filter: { (refinement: Refinement): (fa: Kind) => Kind (predicate: Predicate): (fa: Kind) => Kind } readonly filterMap: (f: (a: A) => Option) => (fa: Kind) => Kind readonly partition: { (refinement: Refinement): (fa: Kind) => Separated, Kind> (predicate: Predicate): (fa: Kind) => Separated, Kind> } readonly partitionMap: (f: (a: A) => Either) => (fa: Kind) => Separated, Kind> } ``` Added in v2.0.0 ## ~~PipeableFilterable2C~~ (interface) **Signature** ```ts export interface PipeableFilterable2C extends PipeableCompactable2C { readonly filter: { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind2) => Kind2 readonly partition: { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } ``` Added in v2.0.0 ## ~~PipeableFilterable2~~ (interface) **Signature** ```ts export interface PipeableFilterable2 extends PipeableCompactable2 { readonly filter: { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind2) => Kind2 readonly partition: { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } ``` Added in v2.0.0 ## ~~PipeableFilterable3~~ (interface) **Signature** ```ts export interface PipeableFilterable3 extends PipeableCompactable3 { readonly filter: { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind3) => Kind3 readonly partition: { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } ``` Added in v2.0.0 ## ~~PipeableFilterable4~~ (interface) **Signature** ```ts export interface PipeableFilterable4 extends PipeableCompactable4 { readonly filter: { (refinement: Refinement): (fa: Kind4) => Kind4 (predicate: Predicate): (fa: Kind4) => Kind4 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind4) => Kind4 readonly partition: { (refinement: Refinement): ( fa: Kind4 ) => Separated, Kind4> (predicate: Predicate): ( fa: Kind4 ) => Separated, Kind4> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind4) => Separated, Kind4> } ``` Added in v2.0.0 ## ~~PipeableFilterableWithIndex1~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex1 extends PipeableFilterable1 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind) => Kind (predicateWithIndex: PredicateWithIndex): (fa: Kind) => Kind } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind) => Kind readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind ) => Separated, Kind> (predicateWithIndex: PredicateWithIndex): (fa: Kind) => Separated, Kind> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind) => Separated, Kind> } ``` Added in v2.0.0 ## ~~PipeableFilterableWithIndex2C~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex2C extends PipeableFilterable2C { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind2) => Kind2 (predicateWithIndex: PredicateWithIndex): (fa: Kind2) => Kind2 } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicateWithIndex: PredicateWithIndex): (fa: Kind2) => Separated, Kind2> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } ``` Added in v2.0.0 ## ~~PipeableFilterableWithIndex2~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex2 extends PipeableFilterable2 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind2) => Kind2 (predicateWithIndex: PredicateWithIndex): (fa: Kind2) => Kind2 } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicateWithIndex: PredicateWithIndex): ( fa: Kind2 ) => Separated, Kind2> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } ``` Added in v2.0.0 ## ~~PipeableFilterableWithIndex3~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex3 extends PipeableFilterable3 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind3 ) => Kind3 (predicateWithIndex: PredicateWithIndex): (fa: Kind3) => Kind3 } readonly filterMapWithIndex: ( f: (i: I, a: A) => Option ) => (fa: Kind3) => Kind3 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicateWithIndex: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } ``` Added in v2.0.0 ## ~~PipeableFilterableWithIndex4~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex4 extends PipeableFilterable4 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind4 ) => Kind4 (predicateWithIndex: PredicateWithIndex): (fa: Kind4) => Kind4 } readonly filterMapWithIndex: ( f: (i: I, a: A) => Option ) => (fa: Kind4) => Kind4 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind4 ) => Separated, Kind4> (predicateWithIndex: PredicateWithIndex): ( fa: Kind4 ) => Separated, Kind4> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind4) => Separated, Kind4> } ``` Added in v2.0.0 ## ~~PipeableFilterableWithIndex~~ (interface) **Signature** ```ts export interface PipeableFilterableWithIndex extends PipeableFilterable { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: HKT) => HKT (predicateWithIndex: PredicateWithIndex): (fa: HKT) => HKT } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: HKT) => HKT readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: HKT ) => Separated, HKT> (predicateWithIndex: PredicateWithIndex): (fa: HKT) => Separated, HKT> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: HKT) => Separated, HKT> } ``` Added in v2.0.0 ## ~~PipeableFilterable~~ (interface) **Signature** ```ts export interface PipeableFilterable extends PipeableCompactable { readonly filter: { (refinement: Refinement): (fa: HKT) => HKT (predicate: Predicate): (fa: HKT) => HKT } readonly filterMap: (f: (a: A) => Option) => (fa: HKT) => HKT readonly partition: { (refinement: Refinement): (fa: HKT) => Separated, HKT> (predicate: Predicate): (fa: HKT) => Separated, HKT> } readonly partitionMap: (f: (a: A) => Either) => (fa: HKT) => Separated, HKT> } ``` Added in v2.0.0 ## ~~PipeableFoldable1~~ (interface) **Signature** ```ts export interface PipeableFoldable1 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind) => B } ``` Added in v2.0.0 ## ~~PipeableFoldable2C~~ (interface) **Signature** ```ts export interface PipeableFoldable2C { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B } ``` Added in v2.0.0 ## ~~PipeableFoldable2~~ (interface) **Signature** ```ts export interface PipeableFoldable2 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B } ``` Added in v2.0.0 ## ~~PipeableFoldable3~~ (interface) **Signature** ```ts export interface PipeableFoldable3 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B } ``` Added in v2.0.0 ## ~~PipeableFoldable4~~ (interface) **Signature** ```ts export interface PipeableFoldable4 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind4) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind4) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind4) => B } ``` Added in v2.0.0 ## ~~PipeableFoldableWithIndex1~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex1 extends PipeableFoldable1 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind) => B } ``` Added in v2.0.0 ## ~~PipeableFoldableWithIndex2C~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex2C extends PipeableFoldable2C { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B } ``` Added in v2.0.0 ## ~~PipeableFoldableWithIndex2~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex2 extends PipeableFoldable2 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B } ``` Added in v2.0.0 ## ~~PipeableFoldableWithIndex3~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex3 extends PipeableFoldable3 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B } ``` Added in v2.0.0 ## ~~PipeableFoldableWithIndex4~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex4 extends PipeableFoldable4 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind4) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind4) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind4) => B } ``` Added in v2.0.0 ## ~~PipeableFoldableWithIndex~~ (interface) **Signature** ```ts export interface PipeableFoldableWithIndex extends PipeableFoldable { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: HKT) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: HKT) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: HKT) => B } ``` Added in v2.0.0 ## ~~PipeableFoldable~~ (interface) **Signature** ```ts export interface PipeableFoldable { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: HKT) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: HKT) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: HKT) => B } ``` Added in v2.0.0 ## ~~PipeableFunctor1~~ (interface) **Signature** ```ts export interface PipeableFunctor1 { readonly map: (f: (a: A) => B) => (fa: Kind) => Kind } ``` Added in v2.0.0 ## ~~PipeableFunctor2C~~ (interface) **Signature** ```ts export interface PipeableFunctor2C { readonly map: (f: (a: A) => B) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableFunctor2~~ (interface) **Signature** ```ts export interface PipeableFunctor2 { readonly map: (f: (a: A) => B) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableFunctor3~~ (interface) **Signature** ```ts export interface PipeableFunctor3 { readonly map: (f: (a: A) => B) => (fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableFunctor4~~ (interface) **Signature** ```ts export interface PipeableFunctor4 { readonly map: (f: (a: A) => B) => (fa: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableFunctorWithIndex1~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex1 extends PipeableFunctor1 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind) => Kind } ``` Added in v2.0.0 ## ~~PipeableFunctorWithIndex2C~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex2C extends PipeableFunctor2C { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableFunctorWithIndex2~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex2 extends PipeableFunctor2 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableFunctorWithIndex3~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex3 extends PipeableFunctor3 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableFunctorWithIndex4~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex4 extends PipeableFunctor4 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableFunctorWithIndex~~ (interface) **Signature** ```ts export interface PipeableFunctorWithIndex extends PipeableFunctor { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: HKT) => HKT } ``` Added in v2.0.0 ## ~~PipeableFunctor~~ (interface) **Signature** ```ts export interface PipeableFunctor { readonly map: (f: (a: A) => B) => (fa: HKT) => HKT } ``` Added in v2.0.0 ## ~~PipeableMonadThrow1~~ (interface) **Signature** ```ts export interface PipeableMonadThrow1 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind readonly fromEither: (ma: Either) => Kind readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind) => Kind (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind) => Kind } } ``` Added in v2.0.0 ## ~~PipeableMonadThrow2C~~ (interface) **Signature** ```ts export interface PipeableMonadThrow2C { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind2 readonly fromEither: (ma: Either) => Kind2 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } } ``` Added in v2.0.0 ## ~~PipeableMonadThrow2~~ (interface) **Signature** ```ts export interface PipeableMonadThrow2 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind2 readonly fromEither: (ma: Either) => Kind2 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } } ``` Added in v2.0.0 ## ~~PipeableMonadThrow3~~ (interface) **Signature** ```ts export interface PipeableMonadThrow3 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind3 readonly fromEither: (ma: Either) => Kind3 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind3 ) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } } ``` Added in v2.0.0 ## ~~PipeableMonadThrow4~~ (interface) **Signature** ```ts export interface PipeableMonadThrow4 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind4 readonly fromEither: (ma: Either) => Kind4 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind4 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind4 ) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind4) => Kind4 } } ``` Added in v2.0.0 ## ~~PipeableMonadThrow~~ (interface) **Signature** ```ts export interface PipeableMonadThrow { readonly fromOption: (onNone: LazyArg) => (ma: Option) => HKT readonly fromEither: (ma: Either) => HKT readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => HKT (predicate: Predicate, onFalse: (a: A) => E): (a: A) => HKT } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: HKT) => HKT (predicate: Predicate, onFalse: (a: A) => E): (ma: HKT) => HKT } } ``` Added in v2.0.0 ## ~~PipeableProfunctor2C~~ (interface) **Signature** ```ts export interface PipeableProfunctor2C extends PipeableFunctor2C { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableProfunctor2~~ (interface) **Signature** ```ts export interface PipeableProfunctor2 extends PipeableFunctor2 { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableProfunctor3~~ (interface) **Signature** ```ts export interface PipeableProfunctor3 extends PipeableFunctor3 { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableProfunctor4~~ (interface) **Signature** ```ts export interface PipeableProfunctor4 extends PipeableFunctor4 { readonly promap: ( f: (d: D) => E, g: (a: A) => B ) => (fbc: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableProfunctor~~ (interface) **Signature** ```ts export interface PipeableProfunctor { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: HKT2) => HKT2 } ``` Added in v2.0.0 ## ~~PipeableSemigroupoid2C~~ (interface) **Signature** ```ts export interface PipeableSemigroupoid2C { readonly compose: (la: Kind2) => (ab: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableSemigroupoid2~~ (interface) **Signature** ```ts export interface PipeableSemigroupoid2 { readonly compose: (la: Kind2) => (ab: Kind2) => Kind2 } ``` Added in v2.0.0 ## ~~PipeableSemigroupoid3~~ (interface) **Signature** ```ts export interface PipeableSemigroupoid3 { readonly compose: (la: Kind3) => (ab: Kind3) => Kind3 } ``` Added in v2.0.0 ## ~~PipeableSemigroupoid4~~ (interface) **Signature** ```ts export interface PipeableSemigroupoid4 { readonly compose: (la: Kind4) => (ab: Kind4) => Kind4 } ``` Added in v2.0.0 ## ~~PipeableSemigroupoid~~ (interface) **Signature** ```ts export interface PipeableSemigroupoid { readonly compose: (la: HKT2) => (ab: HKT2) => HKT2 } ``` Added in v2.0.0 ## ~~pipeable~~ **Signature** ```ts export declare function pipeable( I: { readonly URI: F } & I ): (I extends Chain4 ? PipeableChain4 : I extends Apply4 ? PipeableApply4 : I extends Functor4 ? PipeableFunctor4 : {}) & (I extends Contravariant4 ? PipeableContravariant4 : {}) & (I extends FunctorWithIndex4 ? PipeableFunctorWithIndex4 : {}) & (I extends Bifunctor4 ? PipeableBifunctor4 : {}) & (I extends Extend4 ? PipeableExtend4 : {}) & (I extends FoldableWithIndex4 ? PipeableFoldableWithIndex4 : I extends Foldable4 ? PipeableFoldable4 : {}) & (I extends Alt4 ? PipeableAlt4 : {}) & (I extends FilterableWithIndex4 ? PipeableFilterableWithIndex4 : I extends Filterable4 ? PipeableFilterable4 : I extends Compactable4 ? PipeableCompactable4 : {}) & (I extends Profunctor4 ? PipeableProfunctor4 : {}) & (I extends Semigroupoid4 ? PipeableSemigroupoid4 : {}) & (I extends MonadThrow4 ? PipeableMonadThrow4 : {}) export declare function pipeable( I: { readonly URI: F } & I ): (I extends Chain3 ? PipeableChain3 : I extends Apply3 ? PipeableApply3 : I extends Functor3 ? PipeableFunctor3 : {}) & (I extends Contravariant3 ? PipeableContravariant3 : {}) & (I extends FunctorWithIndex3 ? PipeableFunctorWithIndex3 : {}) & (I extends Bifunctor3 ? PipeableBifunctor3 : {}) & (I extends Extend3 ? PipeableExtend3 : {}) & (I extends FoldableWithIndex3 ? PipeableFoldableWithIndex3 : I extends Foldable3 ? PipeableFoldable3 : {}) & (I extends Alt3 ? PipeableAlt3 : {}) & (I extends FilterableWithIndex3 ? PipeableFilterableWithIndex3 : I extends Filterable3 ? PipeableFilterable3 : I extends Compactable3 ? PipeableCompactable3 : {}) & (I extends Profunctor3 ? PipeableProfunctor3 : {}) & (I extends Semigroupoid3 ? PipeableSemigroupoid3 : {}) & (I extends MonadThrow3 ? PipeableMonadThrow3 : {}) export declare function pipeable( I: { readonly URI: F } & I ): (I extends Chain3C ? PipeableChain3C : I extends Apply3C ? PipeableApply3C : I extends Functor3C ? PipeableFunctor3C : {}) & (I extends Contravariant3C ? PipeableContravariant3C : {}) & (I extends FunctorWithIndex3C ? PipeableFunctorWithIndex3C : {}) & (I extends Bifunctor3C ? PipeableBifunctor3C : {}) & (I extends Extend3C ? PipeableExtend3C : {}) & (I extends FoldableWithIndex3C ? PipeableFoldableWithIndex3C : I extends Foldable3C ? PipeableFoldable3C : {}) & (I extends Alt3C ? PipeableAlt3C : {}) & (I extends FilterableWithIndex3C ? PipeableFilterableWithIndex3C : I extends Filterable3C ? PipeableFilterable3C : I extends Compactable3C ? PipeableCompactable3C : {}) & (I extends Profunctor3C ? PipeableProfunctor3C : {}) & (I extends Semigroupoid3C ? PipeableSemigroupoid3C : {}) & (I extends MonadThrow3C ? PipeableMonadThrow3C : {}) export declare function pipeable( I: { readonly URI: F; readonly _E: E } & I ): (I extends Chain2C ? PipeableChain2C : I extends Apply2C ? PipeableApply2C : I extends Functor2C ? PipeableFunctor2C : {}) & (I extends Contravariant2C ? PipeableContravariant2C : {}) & (I extends FunctorWithIndex2C ? PipeableFunctorWithIndex2C : {}) & (I extends Extend2C ? PipeableExtend2C : {}) & (I extends FoldableWithIndex2C ? PipeableFoldableWithIndex2C : I extends Foldable2C ? PipeableFoldable2C : {}) & (I extends Alt2C ? PipeableAlt2C : {}) & (I extends FilterableWithIndex2C ? PipeableFilterableWithIndex2C : I extends Filterable2C ? PipeableFilterable2C : I extends Compactable2C ? PipeableCompactable2C : {}) & (I extends Profunctor2C ? PipeableProfunctor2C : {}) & (I extends Semigroupoid2C ? PipeableSemigroupoid2C : {}) & (I extends MonadThrow2C ? PipeableMonadThrow2C : {}) export declare function pipeable( I: { readonly URI: F } & I ): (I extends Chain2 ? PipeableChain2 : I extends Apply2 ? PipeableApply2 : I extends Functor2 ? PipeableFunctor2 : {}) & (I extends Contravariant2 ? PipeableContravariant2 : {}) & (I extends FunctorWithIndex2 ? PipeableFunctorWithIndex2 : {}) & (I extends Bifunctor2 ? PipeableBifunctor2 : {}) & (I extends Extend2 ? PipeableExtend2 : {}) & (I extends FoldableWithIndex2 ? PipeableFoldableWithIndex2 : I extends Foldable2 ? PipeableFoldable2 : {}) & (I extends Alt2 ? PipeableAlt2 : {}) & (I extends FilterableWithIndex2 ? PipeableFilterableWithIndex2 : I extends Filterable2 ? PipeableFilterable2 : I extends Compactable2 ? PipeableCompactable2 : {}) & (I extends Profunctor2 ? PipeableProfunctor2 : {}) & (I extends Semigroupoid2 ? PipeableSemigroupoid2 : {}) & (I extends MonadThrow2 ? PipeableMonadThrow2 : {}) export declare function pipeable( I: { readonly URI: F } & I ): (I extends Chain1 ? PipeableChain1 : I extends Apply1 ? PipeableApply1 : I extends Functor1 ? PipeableFunctor1 : {}) & (I extends Contravariant1 ? PipeableContravariant1 : {}) & (I extends FunctorWithIndex1 ? PipeableFunctorWithIndex1 : {}) & (I extends Extend1 ? PipeableExtend1 : {}) & (I extends FoldableWithIndex1 ? PipeableFoldableWithIndex1 : I extends Foldable1 ? PipeableFoldable1 : {}) & (I extends Alt1 ? PipeableAlt1 : {}) & (I extends FilterableWithIndex1 ? PipeableFilterableWithIndex1 : I extends Filterable1 ? PipeableFilterable1 : I extends Compactable1 ? PipeableCompactable1 : {}) & (I extends MonadThrow1 ? PipeableMonadThrow1 : {}) export declare function pipeable( I: { readonly URI: F } & I ): (I extends Chain ? PipeableChain : I extends Apply ? PipeableApply : I extends Functor ? PipeableFunctor : {}) & (I extends Contravariant ? PipeableContravariant : {}) & (I extends FunctorWithIndex ? PipeableFunctorWithIndex : {}) & (I extends Bifunctor ? PipeableBifunctor : {}) & (I extends Extend ? PipeableExtend : {}) & (I extends FoldableWithIndex ? PipeableFoldableWithIndex : I extends Foldable ? PipeableFoldable : {}) & (I extends Alt ? PipeableAlt : {}) & (I extends FilterableWithIndex ? PipeableFilterableWithIndex : I extends Filterable ? PipeableFilterable : I extends Compactable ? PipeableCompactable : {}) & (I extends Profunctor ? PipeableProfunctor : {}) & (I extends Semigroupoid ? PipeableSemigroupoid : {}) & (I extends MonadThrow ? PipeableMonadThrow : {}) ``` Added in v2.0.0 ================================================ FILE: docs/modules/string.ts.md ================================================ --- title: string.ts nav_order: 102 parent: Modules --- ## string overview Added in v2.10.0 ---

Table of contents

- [instances](#instances) - [Eq](#eq) - [Monoid](#monoid) - [Ord](#ord) - [Semigroup](#semigroup) - [Show](#show) - [refinements](#refinements) - [isString](#isstring) - [utils](#utils) - [empty](#empty) - [endsWith](#endswith) - [includes](#includes) - [isEmpty](#isempty) - [replace](#replace) - [size](#size) - [slice](#slice) - [split](#split) - [startsWith](#startswith) - [toLowerCase](#tolowercase) - [toUpperCase](#touppercase) - [trim](#trim) - [trimLeft](#trimleft) - [trimRight](#trimright) --- # instances ## Eq **Signature** ```ts export declare const Eq: E.Eq ``` **Example** ```ts import * as S from 'fp-ts/string' assert.deepStrictEqual(S.Eq.equals('a', 'a'), true) assert.deepStrictEqual(S.Eq.equals('a', 'b'), false) ``` Added in v2.10.0 ## Monoid `string` monoid under concatenation. The `empty` value is `''`. **Signature** ```ts export declare const Monoid: M.Monoid ``` **Example** ```ts import * as S from 'fp-ts/string' assert.deepStrictEqual(S.Monoid.concat('a', 'b'), 'ab') assert.deepStrictEqual(S.Monoid.concat('a', S.Monoid.empty), 'a') ``` Added in v2.10.0 ## Ord **Signature** ```ts export declare const Ord: O.Ord ``` **Example** ```ts import * as S from 'fp-ts/string' assert.deepStrictEqual(S.Ord.compare('a', 'a'), 0) assert.deepStrictEqual(S.Ord.compare('a', 'b'), -1) assert.deepStrictEqual(S.Ord.compare('b', 'a'), 1) ``` Added in v2.10.0 ## Semigroup `string` semigroup under concatenation. **Signature** ```ts export declare const Semigroup: S.Semigroup ``` **Example** ```ts import * as S from 'fp-ts/string' assert.deepStrictEqual(S.Semigroup.concat('a', 'b'), 'ab') ``` Added in v2.10.0 ## Show **Signature** ```ts export declare const Show: Sh.Show ``` **Example** ```ts import * as S from 'fp-ts/string' assert.deepStrictEqual(S.Show.show('a'), '"a"') ``` Added in v2.10.0 # refinements ## isString **Signature** ```ts export declare const isString: Refinement ``` **Example** ```ts import * as S from 'fp-ts/string' assert.deepStrictEqual(S.isString('a'), true) assert.deepStrictEqual(S.isString(1), false) ``` Added in v2.11.0 # utils ## empty An empty `string`. **Signature** ```ts export declare const empty: '' ``` Added in v2.10.0 ## endsWith **Signature** ```ts export declare const endsWith: (searchString: string, position?: number | undefined) => (s: string) => boolean ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abc', S.endsWith('c')), true) assert.deepStrictEqual(pipe('ab', S.endsWith('c')), false) ``` Added in v2.11.0 ## includes **Signature** ```ts export declare const includes: (searchString: string, position?: number | undefined) => (s: string) => boolean ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abc', S.includes('b')), true) assert.deepStrictEqual(pipe('abc', S.includes('d')), false) ``` Added in v2.11.0 ## isEmpty Test whether a `string` is empty. **Signature** ```ts export declare const isEmpty: (s: string) => boolean ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('', S.isEmpty), true) assert.deepStrictEqual(pipe('a', S.isEmpty), false) ``` Added in v2.10.0 ## replace **Signature** ```ts export declare const replace: (searchValue: string | RegExp, replaceValue: string) => (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abc', S.replace('b', 'd')), 'adc') ``` Added in v2.11.0 ## size Calculate the number of characters in a `string`. **Signature** ```ts export declare const size: (s: string) => number ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abc', S.size), 3) ``` Added in v2.10.0 ## slice **Signature** ```ts export declare const slice: (start: number, end: number) => (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abcd', S.slice(1, 3)), 'bc') ``` Added in v2.11.0 ## split **Signature** ```ts export declare const split: (separator: string | RegExp) => (s: string) => ReadonlyNonEmptyArray ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abc', S.split('')), ['a', 'b', 'c']) assert.deepStrictEqual(pipe('', S.split('')), ['']) ``` Added in v2.11.0 ## startsWith **Signature** ```ts export declare const startsWith: (searchString: string, position?: number | undefined) => (s: string) => boolean ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('abc', S.startsWith('a')), true) assert.deepStrictEqual(pipe('bc', S.startsWith('a')), false) ``` Added in v2.11.0 ## toLowerCase **Signature** ```ts export declare const toLowerCase: (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('A', S.toLowerCase), 'a') ``` Added in v2.11.0 ## toUpperCase **Signature** ```ts export declare const toUpperCase: (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe('a', S.toUpperCase), 'A') ``` Added in v2.11.0 ## trim **Signature** ```ts export declare const trim: (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(' a ', S.trim), 'a') ``` Added in v2.11.0 ## trimLeft **Signature** ```ts export declare const trimLeft: (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(' a ', S.trimLeft), 'a ') ``` Added in v2.11.0 ## trimRight **Signature** ```ts export declare const trimRight: (s: string) => string ``` **Example** ```ts import * as S from 'fp-ts/string' import { pipe } from 'fp-ts/function' assert.deepStrictEqual(pipe(' a ', S.trimRight), ' a') ``` Added in v2.11.0 ================================================ FILE: docs/modules/struct.ts.md ================================================ --- title: struct.ts nav_order: 104 parent: Modules --- ## struct overview Added in v2.10.0 ---

Table of contents

- [instances](#instances) - [getAssignSemigroup](#getassignsemigroup) - [utils](#utils) - [evolve](#evolve) --- # instances ## getAssignSemigroup Return a semigroup which works like `Object.assign`. **Signature** ```ts export declare const getAssignSemigroup:
() => Semigroup ``` **Example** ```ts import { getAssignSemigroup } from 'fp-ts/struct' interface Person { readonly name: string readonly age: number } const S = getAssignSemigroup() assert.deepStrictEqual(S.concat({ name: 'name', age: 23 }, { name: 'name', age: 24 }), { name: 'name', age: 24 }) ``` Added in v2.10.0 # utils ## evolve Creates a new object by recursively evolving a shallow copy of `a`, according to the `transformation` functions. **Signature** ```ts export declare const evolve: unknown }>( transformations: F ) => (a: A) => { [K in keyof F]: ReturnType } ``` **Example** ```ts import { pipe } from 'fp-ts/function' import { evolve } from 'fp-ts/struct' assert.deepStrictEqual( pipe( { a: 'a', b: 1 }, evolve({ a: (a) => a.length, b: (b) => b * 2, }) ), { a: 1, b: 2 } ) ``` Added in v2.11.0 ================================================ FILE: docs/modules/void.ts.md ================================================ --- title: void.ts nav_order: 118 parent: Modules --- ## void overview Added in v2.11.0 ---

Table of contents

- [instances](#instances) - [Monoid](#monoid) - [Semigroup](#semigroup) --- # instances ## Monoid **Signature** ```ts export declare const Monoid: M.Monoid ``` Added in v2.11.0 ## Semigroup **Signature** ```ts export declare const Semigroup: Se.Semigroup ``` Added in v2.11.0 ================================================ FILE: docs-ts.json ================================================ { "exclude": ["src/internal.ts"] } ================================================ FILE: dtslint/Applicative.ts ================================================ import * as _ from '../src/Applicative' import * as E from '../src/Either' import * as R from '../src/Reader' import * as S from '../src/Semigroup' // // getApplicativeComposition // const applicativeValidation = E.getValidation(S.semigroupString) _.getApplicativeComposition(R.reader, applicativeValidation).map // $ExpectType (fa: Reader>, f: (a: A) => B) => Reader> ================================================ FILE: dtslint/Apply.ts ================================================ import * as _ from '../src/Apply' import * as E from '../src/Either' import { pipe } from '../src/function' import * as Fu from '../src/Functor' import { Kind, URIS } from '../src/HKT' import * as RTE from '../src/ReaderTaskEither' // // apS // export const apS = (F: _.Apply1) => (s: Kind, n: Kind): Kind => { const apS = _.apS(F) const bindTo = Fu.bindTo(F) return pipe(s, bindTo('s'), apS('n', n)) } // // sequenceS // // TODO: broken in typescript@4.2.3 // export const sequenceS = (F: _.Apply1) => ( // s: Kind, // n: Kind // ): Kind => _.sequenceS(F)({ s, n }) declare const sequenceS1: E.Either declare const sequenceS2: E.Either declare const sequenceS3: E.Either declare const sequenceS4: E.Either const sequenceSf1 = _.sequenceS(E.either) // @ts-expect-error sequenceSf1({}) // @ts-expect-error sequenceSf1({ sequenceS1, sequenceS4 }) sequenceSf1({ sequenceS1, sequenceS2, sequenceS3 }) // $ExpectType Either const sequenceSf2 = _.sequenceS(RTE.readerTaskEither) declare const sequenceS5: RTE.ReaderTaskEither<{ a: number }, string, number> declare const sequenceS6: RTE.ReaderTaskEither<{ a: number }, string, string> declare const sequenceS7: RTE.ReaderTaskEither<{ a: number }, string, boolean> declare const sequenceS8: RTE.ReaderTaskEither<{ a: number }, boolean, void> declare const sequenceS9: RTE.ReaderTaskEither<{ a: string }, string, void> // @ts-expect-error sequenceSf2({ sequenceS5, sequenceS8 }) // @ts-expect-error sequenceSf2({ sequenceS5, sequenceS9 }) sequenceSf2({ sequenceS5, sequenceS6, sequenceS7 }) // $ExpectType ReaderTaskEither<{ a: number; }, string, { sequenceS5: number; sequenceS6: string; sequenceS7: boolean; }> // // sequenceT // // TODO: broken in typescript@4.2.3 // export const sequenceT = (F: _.Apply1) => ( // s: Kind, // n: Kind // ): Kind => _.sequenceT(F)(s, n) const sequenceTf1 = _.sequenceT(E.either) // @ts-expect-error sequenceTf1([]) // @ts-expect-error sequenceTf1(sequenceS1, sequenceS4) sequenceTf1(sequenceS1, sequenceS2, sequenceS3) // $ExpectType Either const sequenceTf2 = _.sequenceT(RTE.readerTaskEither) // @ts-expect-error sequenceTf2(sequenceS5, sequenceS8) // @ts-expect-error sequenceTf2(sequenceS5, sequenceS9) sequenceTf2(sequenceS5, sequenceS6, sequenceS7) // $ExpectType ReaderTaskEither<{ a: number; }, string, [number, string, boolean]> ================================================ FILE: dtslint/Array.ts ================================================ import * as _ from '../src/Array' import * as E from '../src/Either' import { identity, pipe } from '../src/function' import * as N from '../src/number' import { Ord } from '../src/Ord' declare const us: Array declare const ns: Array declare const ss: Array declare const tns: Array<[number, string]> // prepend pipe(ss, _.prepend('a')) // $ExpectType NonEmptyArray pipe(ss, _.prependW(1)) // $ExpectType NonEmptyArray // append pipe(ss, _.append('a')) // $ExpectType NonEmptyArray pipe(ss, _.appendW(1)) // $ExpectType NonEmptyArray // // zip // _.zip(ns, ss) // $ExpectType [number, string][] // // zipWith // _.zipWith(ns, ss, (n, s) => [n, s] as const) // $ExpectType (readonly [number, string])[] // // unzip // _.unzip(tns) // $ExpectType [number[], string[]] pipe(tns, _.unzip) // $ExpectType [number[], string[]] // // spanLeft // // $ExpectType Spanned pipe( us, _.spanLeft((u: unknown): u is number => typeof u === 'number') ) // // lookup // _.lookup(0, [1, 2, 3]) // $ExpectType Option _.lookup(0) // $ExpectType
(as: A[]) => Option // // elem // _.elem(N.Eq)(1, [1, 2, 3]) // $ExpectType boolean _.elem(N.Eq)(1) // $ExpectType (as: number[]) => boolean // // difference // _.difference(N.Eq)([1, 2], [3, 4]) // $ExpectType number[] _.difference(N.Eq)([3, 4]) // $ExpectType (ys: number[]) => number[] // // intersection // _.intersection(N.Eq)([1, 2], [3, 4]) // $ExpectType number[] _.intersection(N.Eq)([3, 4]) // $ExpectType (ys: number[]) => number[] // // union // _.union(N.Eq)([1, 2], [3, 4]) // $ExpectType number[] _.union(N.Eq)([3, 4]) // $ExpectType (ys: number[]) => number[] // // zip // _.zip([1, 2], ['a', 'b']) // $ExpectType [number, string][] _.zip(['a', 'b']) // $ExpectType (as: A[]) => [A, string][] // // cons // _.cons(0, [1, 2]) // $ExpectType NonEmptyArray _.cons(0) // $ExpectType (tail: number[]) => NonEmptyArray // // sort // declare const ord1: Ord<{ readonly a: string }> interface X1 { readonly a: string readonly b: number } declare const x1s: Array _.sort(ord1)(x1s) // $ExpectType X1[] pipe(x1s, _.sort(ord1)) // $ExpectType X1[] // // sortBy // declare const ord2: Ord declare const ord3: Ord interface X2 { readonly a: string readonly b: number readonly c: boolean } declare const x2s: Array _.sortBy([ord2, ord3])(x2s) // $ExpectType X2[] pipe(x2s, _.sortBy([ord2, ord3])) // $ExpectType X2[] // // Do // // $ExpectType { readonly a1: number; readonly a2: string; }[] pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // some // // $ExpectType Either> pipe( ns, E.fromPredicate( _.some((n) => n > 0), identity ) ) // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const prns: Array declare const prsns: Array declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean declare const isStringWithIndex: (i: number, u: unknown) => u is string declare const isNumberWithIndex: (i: number, sn: string | number) => sn is number declare const predicateWithIndex: (i: number, sn: string | number) => boolean // // filter // // $ExpectType string[] pipe(prsns, _.filter(isString)) // $ExpectType number[] pipe(prns, _.filter(predicate)) // $ExpectType number[] pipe( prns, _.filter( ( _x // $ExpectType number ) => true ) ) // // filterWithIndex // // $ExpectType string[] pipe(prsns, _.filterWithIndex(isStringWithIndex)) // $ExpectType number[] pipe(prns, _.filterWithIndex(predicateWithIndex)) // $ExpectType number[] pipe( prns, _.filterWithIndex( ( _i, // $ExpectType number _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated pipe(prsns, _.partition(isString)) // $ExpectType Separated pipe(prns, _.partition(predicate)) // $ExpectType Separated<(string | number)[], number[]> pipe(prsns, _.partition(isNumber)) // $ExpectType Separated pipe( prns, _.partition( ( _x // $ExpectType number ) => true ) ) // // partitionWithIndex // // $ExpectType Separated pipe(prsns, _.partitionWithIndex(isStringWithIndex)) // $ExpectType Separated pipe(prns, _.partitionWithIndex(predicateWithIndex)) // $ExpectType Separated<(string | number)[], number[]> pipe(prsns, _.partitionWithIndex(isNumberWithIndex)) // $ExpectType Separated pipe( prns, _.partitionWithIndex( ( _i, // $ExpectType number _x // $ExpectType number ) => true ) ) // // takeLeftWhile // // $ExpectType string[] pipe(prsns, _.takeLeftWhile(isString)) // $ExpectType number[] pipe(prns, _.takeLeftWhile(predicate)) // // dropLeftWhile // // $ExpectType string[] pipe(prsns, _.dropLeftWhile(isString)) // $ExpectType number[] pipe(prns, _.dropLeftWhile(predicate)) // // spanLeft // // $ExpectType Spanned pipe(prsns, _.spanLeft(isString)) // $ExpectType Spanned pipe(prns, _.spanLeft(predicate)) // // findFirst // // $ExpectType Option pipe(prsns, _.findFirst(isString)) // $ExpectType Option pipe(prns, _.findFirst(predicate)) // // findLast // // $ExpectType Option pipe(prsns, _.findLast(isString)) // $ExpectType Option pipe(prns, _.findLast(predicate)) // // isEmpty // // $ExpectType Either pipe( ss, E.fromPredicate(_.isEmpty, (as) => as) ) ================================================ FILE: dtslint/Console.ts ================================================ import * as _ from '../src/Console' import { flow, pipe } from '../src/function' import * as TE from '../src/TaskEither' // $ExpectType TaskEither pipe(TE.right('a'), TE.chainFirst(flow(_.error, TE.fromIO))) // $ExpectType TaskEither pipe(TE.right('a'), TE.chainFirst(flow(_.info, TE.fromIO))) // $ExpectType TaskEither pipe(TE.right('a'), TE.chainFirst(flow(_.log, TE.fromIO))) // $ExpectType TaskEither pipe(TE.right('a'), TE.chainFirst(flow(_.warn, TE.fromIO))) ================================================ FILE: dtslint/Const.ts ================================================ import * as _ from '../src/Const' // // contramap // _.const_.contramap(_.make(true), (s: string) => s.length) // $ExpectType Const ================================================ FILE: dtslint/Either.ts ================================================ import * as _ from '../src/Either' import { flow, identity, pipe } from '../src/function' import * as RA from '../src/ReadonlyArray' // // getOrElseW // // $ExpectType string | null pipe( _.right('a'), _.getOrElseW(() => null) ) // // chainW // // $ExpectType Either pipe( _.right('a'), _.chainW(() => _.right(1)) ) // // fromNullable // interface D { foo: number | undefined } declare const f: (key: K) => D[K] // $ExpectType Either flow(f, _.fromNullable('error'))('foo') // // do notation // // $ExpectType Either pipe( _.right(1), _.bindTo('a1'), _.bind('a2', () => _.right('b')), _.bindW('a3', () => _.right(true)) ) // // pipeable sequence S // // $ExpectType Either pipe( _.right(1), _.bindTo('a1'), _.apS('a2', _.right('b')), _.apSW('a3', _.right(true)) ) // // Do // // $ExpectType Either pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filterOrElseW // // $ExpectType Either<"a1" | "a2", number> pipe( _.left<'a1', number>('a1'), _.filterOrElseW( (result) => result > 0, () => 'a2' as const ) ) // // stringifyJSON // // $ExpectType Either pipe( _.right('a'), _.chainFirst((s) => _.stringifyJSON(s, identity)) ) // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const n: number declare const sn: string | number declare const en: _.Either declare const esn: _.Either declare const isString: (u: unknown) => u is string declare const predicate: (sn: string | number) => boolean // // fromPredicate // // $ExpectType Either pipe( sn, _.fromPredicate(isString, () => false) ) // $ExpectType Either pipe( n, _.fromPredicate(predicate, () => false) ) // $ExpectType Either pipe( n, _.fromPredicate( ( _n // $ExpectType number ) => true, () => false ) ) // // filterOrElse // // $ExpectType Either pipe( esn, _.filterOrElse(isString, () => false) ) // $ExpectType Either pipe( en, _.filterOrElse(predicate, () => false) ) // $ExpectType Either pipe( en, _.filterOrElse( ( _n // $ExpectType number ) => true, () => false ) ) // // exists // declare const es: Array<_.Either> pipe(es, RA.filter(_.exists((n) => n > 0))) ================================================ FILE: dtslint/Eq.ts ================================================ import * as B from '../src/boolean' import * as _ from '../src/Eq' import * as N from '../src/number' import * as S from '../src/string' // // struct // // $ExpectType Eq<{ readonly a: string; readonly b: number; readonly c: boolean; }> _.struct({ a: S.Eq, b: N.Eq, c: B.Eq }) // // tuple // // $ExpectType Eq _.tuple(S.Eq, N.Eq, B.Eq) // // getTupleEq // _.getTupleEq(_.eqString, _.eqNumber, _.eqBoolean) // $ExpectType Eq<[string, number, boolean]> ================================================ FILE: dtslint/Functor.ts ================================================ import * as E from '../src/Either' import * as _ from '../src/Functor' import * as RTE from '../src/ReaderTaskEither' import * as RA from '../src/ReadonlyArray' // $ExpectType (f: (a: A) => B) => (fa: readonly (readonly A[])[]) => readonly (readonly B[])[] export const F11 = _.map(RA.Functor, RA.Functor) // $ExpectType (f: (a: A) => B) => (fa: readonly Either[]) => readonly Either[] export const F12 = _.map(RA.Functor, E.Functor) // $ExpectType (f: (a: A) => B) => (fa: readonly ReaderTaskEither[]) => readonly ReaderTaskEither[] export const F13 = _.map(RA.Functor, RTE.Functor) // $ExpectType (f: (a: A) => B) => (fa: Either) => Either export const F21 = _.map(E.Functor, RA.Functor) // $ExpectType (f: (a: A) => B) => (fa: Either>) => Either> export const F22 = _.map(E.Functor, E.Functor) // $ExpectType (f: (a: A) => B) => (fa: ReaderTaskEither) => ReaderTaskEither export const F31 = _.map(RTE.Functor, RA.Functor) ================================================ FILE: dtslint/IO.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/IO' // // Do // // $ExpectType IO<{ readonly a1: number; readonly a2: string; }> pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) ================================================ FILE: dtslint/IOEither.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as IO from '../src/IO' import * as _ from '../src/IOEither' // // getOrElseW // // $ExpectType IO pipe( _.right('a'), _.getOrElseW(() => IO.of(null)) ) // // orElse // // $ExpectType IOEither pipe( _.left('a'), _.orElse((a) => _.left(a.length)) ) // // orElseW // // $ExpectType IOEither pipe( _.left('a'), _.orElseW((a) => _.right(a.length)) ) // // orElseFirst // // $ExpectType IOEither pipe( _.left('a'), _.orElseFirst((a) => _.right(a.length)) ) // // orElseFirstW // // $ExpectType IOEither pipe( _.left('a'), _.orElseFirstW((a) => _.left(a.length)) ) // // orElseFirstIOK // // $ExpectType IOEither pipe( _.left('a'), _.orElseFirstIOK((a) => IO.of(a.length)) ) // // orLeft // // $ExpectType IOEither pipe( _.left('a'), _.orLeft((a) => IO.of(a.length)) ) // // chainW // // $ExpectType IOEither pipe( _.right('a'), _.chainW(() => _.right(1)) ) // // chainEitherKW // // $ExpectType IOEither pipe( _.right('a'), _.chainEitherKW(() => E.right(1)) ) // // do notation // // $ExpectType IOEither pipe( _.right(1), _.bindTo('a1'), _.bind('a2', () => _.right('b')), _.bindW('a3', () => _.right(true)) ) // // pipeable sequence S // // $ExpectType IOEither pipe( _.right(1), _.bindTo('a1'), _.apS('a2', _.right('b')), _.apSW('a3', _.right(true)) ) // // Do // // $ExpectType IOEither pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filterOrElseW // // $ExpectType IOEither<"a1" | "a2", number> pipe( _.left<'a1', number>('a1'), _.filterOrElseW( (result) => result > 0, () => 'a2' as const ) ) ================================================ FILE: dtslint/Identity.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/Identity' // // Do // // $ExpectType { readonly a1: number; readonly a2: string; } pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) ================================================ FILE: dtslint/Json.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as _ from '../src/Json' // // stringify // // @ts-expect-error _.stringify<_.Json>(undefined) // @ts-expect-error _.stringify<_.Json>(() => { return }) // @ts-expect-error _.stringify<_.Json>(Symbol()) // @ts-expect-error _.stringify<_.Json>({ a: undefined }) // @ts-expect-error _.stringify<_.Json>({ ...{ a: undefined } }) // tslint:disable-next-line: interface-over-type-literal interface AB { readonly a: string readonly b: number } const ab: AB = { a: 'a', b: 1 } const abs: ReadonlyArray = [{ a: 'a', b: 1 }] _.stringify({ a: 'a', b: 1 }) _.stringify(ab) _.stringify({ ...ab }) _.stringify([{ a: 'a', b: 1 }]) _.stringify(abs) _.stringify([...abs]) // $ExpectType Either pipe(E.right('a'), E.chainFirst(_.stringify)) ================================================ FILE: dtslint/Map.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as _ from '../src/Map' import * as N from '../src/number' import * as S from '../src/string' // // member // _.member(S.Eq)('a', new Map()) // $ExpectType boolean _.member(S.Eq)('a') // $ExpectType (m: Map) => boolean // // elem // _.elem(S.Eq)('a', new Map()) // $ExpectType boolean _.elem(S.Eq)('a') // $ExpectType (m: Map) => boolean // // lookup // _.lookup(S.Eq)('a', new Map([['a', 1]])) // $ExpectType Option _.lookup(S.Eq)('a') // $ExpectType (m: Map) => Option // // lookupWithKey // _.lookupWithKey(S.Eq)('a', new Map([['a', 1]])) // $ExpectType Option<[string, number]> _.lookupWithKey(S.Eq)('a') // $ExpectType (m: Map) => Option<[string, A]> // // isSubmap // _.isSubmap(S.Eq, N.Eq)(new Map([['a', 1]]), new Map([['a', 1]])) // $ExpectType boolean _.isSubmap(S.Eq, N.Eq)(new Map([['a', 1]])) // $ExpectType (me: Map) => boolean // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const prns: Map declare const prsns: Map declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean declare const isStringWithIndex: (k: string, u: unknown) => u is string declare const isNumberWithIndex: (k: string, sn: string | number) => sn is number declare const predicateWithIndex: (k: string, sn: string | number) => boolean // // filter // // $ExpectType Map pipe(prsns, _.filter(isString)) // $ExpectType Map pipe(prns, _.filter(predicate)) // $ExpectType Map pipe( prns, _.filter( ( _x // $ExpectType number ) => true ) ) // // filterWithIndex // // $ExpectType Map pipe(prsns, _.filterWithIndex(isStringWithIndex)) // $ExpectType Map pipe(prns, _.filterWithIndex(predicateWithIndex)) // $ExpectType Map pipe( prns, _.filterWithIndex( ( _k, // $ExpectType string _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated, Map> pipe(prsns, _.partition(isString)) // $ExpectType Separated, Map> pipe(prns, _.partition(predicate)) // $ExpectType Separated, Map> pipe(prsns, _.partition(isNumber)) // $ExpectType Separated, Map> pipe( prns, _.partition( ( _x // $ExpectType number ) => true ) ) // // partitionWithIndex // // $ExpectType Separated, Map> pipe(prsns, _.partitionWithIndex(isStringWithIndex)) // $ExpectType Separated, Map> pipe(prns, _.partitionWithIndex(predicateWithIndex)) // $ExpectType Separated, Map> pipe(prsns, _.partitionWithIndex(isNumberWithIndex)) // $ExpectType Separated, Map> pipe( prns, _.partitionWithIndex( ( _k, // $ExpectType string _x // $ExpectType number ) => true ) ) // // isEmpty // // $ExpectType Either, Map> pipe( prns, E.fromPredicate(_.isEmpty, (as) => as) ) ================================================ FILE: dtslint/Monoid.ts ================================================ import * as B from '../src/boolean' import * as _ from '../src/Monoid' import * as N from '../src/number' import * as S from '../src/string' // // struct // // $ExpectType Monoid<{ readonly a: string; readonly b: number; readonly c: boolean; }> _.struct({ a: S.Monoid, b: N.MonoidSum, c: B.MonoidAll }) // // tuple // // $ExpectType Monoid _.tuple(S.Monoid, N.MonoidSum, B.MonoidAll) // // getTupleMonoid // _.getTupleMonoid(_.monoidString, _.monoidSum, _.monoidAll) // $ExpectType Monoid<[string, number, boolean]> ================================================ FILE: dtslint/NonEmptyArray.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/NonEmptyArray' import { Ord } from '../src/Ord' declare const as: Array declare const neas: _.NonEmptyArray declare const nens: _.NonEmptyArray declare const netns: _.NonEmptyArray<[number, string]> // // zip // _.zip(nens, neas) // $ExpectType NonEmptyArray<[number, string]> _.zip(neas) // $ExpectType (as: NonEmptyArray) => NonEmptyArray<[A, string]> // // zipWith // _.zipWith(nens, neas, (n, s) => [n, s] as const) // $ExpectType NonEmptyArray // // unzip // _.unzip(netns) // $ExpectType [NonEmptyArray, NonEmptyArray] pipe(netns, _.unzip) // $ExpectType [NonEmptyArray, NonEmptyArray] // // cons // _.cons(1, []) // $ExpectType NonEmptyArray<1> _.cons(1, [2, 3]) // $ExpectType NonEmptyArray // // sort // declare const ordSubX: Ord<{ readonly a: string }> interface X { readonly a: string readonly b: number } declare const xs: Array declare const nexs: _.NonEmptyArray _.sort(ordSubX)(nexs) // $ExpectType NonEmptyArray pipe(nexs, _.sort(ordSubX)) // $ExpectType NonEmptyArray // // group // _.group(ordSubX)(xs) // $ExpectType NonEmptyArray[] pipe(xs, _.group(ordSubX)) // $ExpectType NonEmptyArray[] _.group(ordSubX)(nexs) // $ExpectType NonEmptyArray> // TODO pipe(nexs, _.group(ordSubX)) // $ExpectType NonEmptyArray> // // groupSort // _.groupSort(ordSubX)(xs) // $ExpectType NonEmptyArray[] pipe(xs, _.groupSort(ordSubX)) // $ExpectType NonEmptyArray[] _.groupSort(ordSubX)(nexs) // $ExpectType NonEmptyArray> // TODO pipe(nexs, _.groupSort(ordSubX)) // $ExpectType NonEmptyArray> // // groupBy // _.groupBy((x: { readonly a: string }) => x.a)(xs) // $ExpectType Record> // $ExpectType Record> pipe( xs, _.groupBy((x) => x.a) ) // // Do // // $ExpectType NonEmptyArray<{ readonly a1: number; readonly a2: string; }> pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filter // declare const isNumber1: (sn: string | number) => sn is number declare const isNumber2: (sn: unknown) => sn is number declare const neasn: _.NonEmptyArray // $ExpectType Option> pipe(neasn, _.filter(isNumber1)) // $ExpectType Option> _.filter(isNumber1)(neasn) // $ExpectType Option> pipe(neasn, _.filter(isNumber2)) // $ExpectType Option> _.filter(isNumber2)(neasn) // // concat // _.concat(as, neas) // $ExpectType NonEmptyArray _.concat(neas, as) // $ExpectType NonEmptyArray _.concat(neas)(as) // $ExpectType NonEmptyArray _.concat(as)(neas) // $ExpectType NonEmptyArray ================================================ FILE: dtslint/Option.ts ================================================ import { flow, pipe } from '../src/function' import * as _ from '../src/Option' // // getOrElseW // // $ExpectType string | null pipe( _.some('a'), _.getOrElseW(() => null) ) // // fromNullable // declare const x: number | null | undefined _.fromNullable(x) // $ExpectType Option interface D { foo: number | undefined } declare const f: (key: K) => D[K] // $ExpectType Option flow(f, _.fromNullable)('foo') // // Do // // $ExpectType Option<{ readonly a1: number; readonly a2: string; }> pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const n: number declare const sn: string | number declare const on: _.Option declare const osn: _.Option declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean // // filter // // $ExpectType Option pipe(osn, _.filter(isString)) // $ExpectType Option pipe(on, _.filter(predicate)) // $ExpectType Option pipe( on, _.filter( ( _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated, Option> pipe(osn, _.partition(isString)) // $ExpectType Separated, Option> pipe(on, _.partition(predicate)) // $ExpectType Separated, Option> pipe(osn, _.partition(isNumber)) // $ExpectType Separated, Option> pipe( on, _.partition( ( _x // $ExpectType number ) => true ) ) // // fromPredicate // // $ExpectType Option pipe(sn, _.fromPredicate(isString)) // $ExpectType Option pipe(n, _.fromPredicate(predicate)) // $ExpectType Option pipe( n, _.fromPredicate( ( _n // $ExpectType number ) => true ) ) ================================================ FILE: dtslint/Ord.ts ================================================ import * as B from '../src/boolean' import * as N from '../src/number' import * as _ from '../src/Ord' import * as S from '../src/string' // // tuple // // $ExpectType Ord _.tuple(S.Ord, N.Ord, B.Ord) // // getTupleOrd // _.getTupleOrd(_.ordString, _.ordNumber, _.ordBoolean) // $ExpectType Ord<[string, number, boolean]> ================================================ FILE: dtslint/Reader.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/Reader' // // chainW // // $ExpectType Reader<{ a: string; } & { b: number; }, number> pipe( _.of<{ a: string }, string>('a'), _.chainW(() => _.of<{ b: number }, number>(1)) ) // // Do // // $ExpectType Reader pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) ================================================ FILE: dtslint/ReaderEither.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as R from '../src/Reader' import * as _ from '../src/ReaderEither' // // getOrElseW // // $ExpectType Reader<{ a: string; } & { b: number; }, string | null> pipe( _.right<{ a: string }, string, string>('a'), _.getOrElseW(() => R.of<{ b: number }, null>(null)) ) // // orElse // // $ExpectType ReaderEither<{ a: string; }, number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orElse((a) => _.left(a.length)) ) // // orElseW // // $ExpectType ReaderEither<{ b: number; } & { a: string; }, never, string | number> pipe( _.left<{ a: string }, string, string>('a'), _.orElseW((a) => _.right<{ b: number }, never, string | number>(a.length)) ) // // orElseFirst // // $ExpectType ReaderEither<{ a: string; }, string, never> pipe( _.left<{ a: string }, string, never>('a'), _.orElseFirst((a) => _.right(a.length)) ) // // orElseFirstW // // $ExpectType ReaderEither<{ a: string; }, string | number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orElseFirstW((a) => _.left(a.length)) ) // // orLeft // // $ExpectType ReaderEither<{ a: string; }, number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orLeft((a) => R.of(a.length)) ) // // orLeftW // // $ExpectType ReaderEither<{ a: string; } & { b: string; }, number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orLeftW((a) => R.of<{ b: string }, number>(a.length)) ) // // chainW // // $ExpectType ReaderEither<{ a: string; } & { b: number; }, string | number, number> pipe( _.right<{ a: string }, string, string>('a'), _.chainW(() => _.right<{ b: number }, number, number>(1)) ) // // chainEitherKW // // $ExpectType ReaderEither pipe( _.right('a'), _.chainEitherKW(() => E.right(1)) ) // // do notation // // $ExpectType ReaderEither<{ readonly a: number; } & { readonly b: string; }, string | number, { readonly a1: number; readonly a2: string; readonly a3: boolean; }> pipe( _.right<{ readonly a: number }, string, number>(1), _.bindTo('a1'), _.bind('a2', () => _.right('b')), _.bindW('a3', () => _.right<{ readonly b: string }, number, boolean>(true)) ) // // pipeable sequence S // // $ExpectType ReaderEither<{ readonly a: number; } & { readonly b: string; }, string | number, { readonly a1: number; readonly a2: string; readonly a3: boolean; }> pipe( _.right<{ readonly a: number }, string, number>(1), _.bindTo('a1'), _.apS('a2', _.right('b')), _.apSW('a3', _.right<{ readonly b: string }, number, boolean>(true)) ) // // Do // // $ExpectType ReaderEither pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filterOrElseW // // $ExpectType ReaderEither<{ c: boolean; }, "a1" | "a2", number> pipe( _.left<{ c: boolean }, 'a1', number>('a1'), _.filterOrElseW( (result) => result > 0, () => 'a2' as const ) ) ================================================ FILE: dtslint/ReaderT.ts ================================================ import * as _ from '../src/ReaderT' import * as RTE from '../src/ReaderTaskEither' import * as SRTE from '../src/StateReaderTaskEither' import * as TE from '../src/TaskEither' import * as TTH from '../src/TaskThese' // $ExpectType (f: (r: R) => Either) => Reader> _.fromNaturalTransformation<'Either', 'TaskEither'>(TE.fromEither) // $ExpectType (f: (r: R) => IO) => Reader> _.fromNaturalTransformation<'IO', 'TaskEither'>(TE.fromIO) // $ExpectType (f: (r: R) => Reader) => Reader> _.fromNaturalTransformation<'Reader', 'ReaderTaskEither'>(RTE.fromReader) // $ExpectType (f: (r: R) => State) => Reader> _.fromNaturalTransformation<'State', 'StateReaderTaskEither'>(SRTE.fromState) // $ExpectType (f: (r: R) => Task) => Reader> _.fromNaturalTransformation<'Task', 'TaskEither'>(TE.fromTask) // $ExpectType (f: (r: R) => These) => Reader> _.fromNaturalTransformation<'These', 'TaskThese'>(TTH.fromThese) ================================================ FILE: dtslint/ReaderTask.ts ================================================ import { pipe } from '../src/function' import * as RIO from '../src/ReaderIO' import * as _ from '../src/ReaderTask' interface R1 { foo: string } interface R2 { bar: string } // // fromReaderIO // // $ExpectType ReaderTask _.fromReaderIO(RIO.of(true)) // // fromReaderIOK // // $ExpectType (a: boolean) => ReaderTask _.fromReaderIOK((a: boolean) => RIO.of(a)) // // chainReaderIOKW // // $ExpectType ReaderTask pipe( _.of(1), _.chainReaderIOKW(() => RIO.of(true)) ) // // chainReaderIOK // // $ExpectType ReaderTask pipe( _.of(1), _.chainReaderIOK(() => RIO.of(1)) ) pipe( // @ts-expect-error _.of(1), _.chainReaderIOK(() => RIO.of(true)) ) // // chainFirstReaderIOKW // // $ExpectType ReaderTask pipe( _.of(1), _.chainFirstReaderIOKW(() => RIO.of(true)) ) // // chainFirstReaderIOK // // $ExpectType ReaderTask pipe( _.of(1), _.chainFirstReaderIOK(() => RIO.of(true)) ) pipe( // @ts-expect-error _.of(1), _.chainFirstReaderIOK(() => RIO.of(true)) ) // // Do // // $ExpectType ReaderTask pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) ================================================ FILE: dtslint/ReaderTaskEither.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as IOE from '../src/IOEither' import * as RIO from '../src/ReaderIO' import * as RT from '../src/ReaderTask' import * as _ from '../src/ReaderTaskEither' import * as TE from '../src/TaskEither' // // rightReaderIO // // $ExpectType ReaderTaskEither<{ a: string; }, never, boolean> _.rightReaderIO(RIO.of<{ a: string }, boolean>(true)) // // leftReaderIO // // $ExpectType ReaderTaskEither<{ a: string; }, boolean, never> _.leftReaderIO(RIO.of<{ a: string }, boolean>(true)) // // getOrElseW // // $ExpectType ReaderTask<{ a: string; } & { b: number; }, string | null> pipe( _.right<{ a: string }, string, string>('a'), _.getOrElseW(() => RT.of<{ b: number }, null>(null)) ) // // orElse // // $ExpectType ReaderTaskEither<{ a: string; }, number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orElse((a) => _.left(a.length)) ) // // orElseW // // $ExpectType ReaderTaskEither<{ b: number; } & { a: string; }, never, string | number> pipe( _.left<{ a: string }, string, string>('a'), _.orElseW((a) => _.right<{ b: number }, never, string | number>(a.length)) ) // // orElseFirst // // $ExpectType ReaderTaskEither<{ a: string; }, string, never> pipe( _.left<{ a: string }, string, never>('a'), _.orElseFirst((a) => _.right(a.length)) ) // // orElseFirstW // // $ExpectType ReaderTaskEither<{ a: string; }, string | number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orElseFirstW((a) => _.left(a.length)) ) // // orLeft // // $ExpectType ReaderTaskEither<{ a: string; }, number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orLeft((a) => RT.of(a.length)) ) // // orLeftW // // $ExpectType ReaderTaskEither<{ a: string; } & { b: string; }, number, never> pipe( _.left<{ a: string }, string, never>('a'), _.orLeftW((a) => RT.of<{ b: string }, number>(a.length)) ) // // chainW // // $ExpectType ReaderTaskEither<{ a: string; } & { b: number; }, string | number, number> pipe( _.right<{ a: string }, string, string>('a'), _.chainW(() => _.right<{ b: number }, number, number>(1)) ) // // chainEitherKW // // $ExpectType ReaderTaskEither pipe( _.right('a'), _.chainEitherKW(() => E.right(1)) ) // // chainTaskEitherKW // // $ExpectType ReaderTaskEither pipe( _.right('a'), _.chainTaskEitherKW(() => TE.right(1)) ) // // chainIOEitherKW // // $ExpectType ReaderTaskEither pipe( _.right('a'), _.chainIOEitherKW(() => IOE.right(1)) ) // // fromReaderIOK // // $ExpectType (a: boolean) => ReaderTaskEither<{ a: string; }, E, boolean> _.fromReaderIOK((a: boolean) => RIO.of<{ a: string }, boolean>(a)) // // chainReaderIOKW // // $ExpectType ReaderTaskEither<{ a: string; } & { b: number; }, string, boolean> pipe( _.right<{ a: string }, string, number>(1), _.chainReaderIOKW(() => RIO.of<{ b: number }, boolean>(true)) ) // // chainReaderIOK // // $ExpectType ReaderTaskEither<{ a: string; }, string, number> pipe( _.right<{ a: string }, string, number>(1), _.chainReaderIOK(() => RIO.of(1)) ) pipe( _.right<{ a: string }, string, number>(1), // @ts-expect-error _.chainReaderIOK(() => RIO.of<{ b: number }, boolean>(true)) ) // // chainFirstReaderIOKW // // $ExpectType ReaderTaskEither<{ a: string; } & { b: number; }, string, number> pipe( _.right<{ a: string }, string, number>(1), _.chainFirstReaderIOKW(() => RIO.of<{ b: number }, boolean>(true)) ) // // chainFirstReaderIOK // // $ExpectType ReaderTaskEither<{ a: string; }, string, number> pipe( _.right<{ a: string }, string, number>(1), _.chainFirstReaderIOK(() => RIO.of(true)) ) pipe( _.right<{ a: string }, string, number>(1), // @ts-expect-error _.chainFirstReaderIOK(() => RIO.of<{ b: number }, boolean>(true)) ) // // rightReaderIO // // $ExpectType ReaderTaskEither<{ a: string; }, never, boolean> _.rightReaderIO(RIO.of<{ a: string }, boolean>(true)) // // leftReaderIO // // $ExpectType ReaderTaskEither<{ a: string; }, boolean, never> _.leftReaderIO(RIO.of<{ a: string }, boolean>(true)) // // fromReaderIOK // // $ExpectType (a: boolean) => ReaderTaskEither<{ a: string; }, E, boolean> _.fromReaderIOK((a: boolean) => RIO.of<{ a: string }, boolean>(a)) // // chainReaderIOKW // // $ExpectType ReaderTaskEither<{ a: string; } & { b: number; }, string, boolean> pipe( _.right<{ a: string }, string, number>(1), _.chainReaderIOKW(() => RIO.of<{ b: number }, boolean>(true)) ) // // chainReaderIOK // // $ExpectType ReaderTaskEither<{ a: string; }, string, number> pipe( _.right<{ a: string }, string, number>(1), _.chainReaderIOK(() => RIO.of(1)) ) pipe( _.right<{ a: string }, string, number>(1), // @ts-expect-error _.chainReaderIOK(() => RIO.of<{ b: number }, boolean>(true)) ) // // chainFirstReaderIOKW // // $ExpectType ReaderTaskEither<{ a: string; } & { b: number; }, string, number> pipe( _.right<{ a: string }, string, number>(1), _.chainFirstReaderIOKW(() => RIO.of<{ b: number }, boolean>(true)) ) // // chainFirstReaderIOK // // $ExpectType ReaderTaskEither<{ a: string; }, string, number> pipe( _.right<{ a: string }, string, number>(1), _.chainFirstReaderIOK(() => RIO.of(true)) ) pipe( _.right<{ a: string }, string, number>(1), // @ts-expect-error _.chainFirstReaderIOK(() => RIO.of<{ b: number }, boolean>(true)) ) // // do notation // // $ExpectType ReaderTaskEither<{ readonly a: number; } & { readonly b: string; }, string | number, { readonly a1: number; readonly a2: string; readonly a3: boolean; }> pipe( _.right<{ readonly a: number }, string, number>(1), _.bindTo('a1'), _.bind('a2', () => _.right('b')), _.bindW('a3', () => _.right<{ readonly b: string }, number, boolean>(true)) ) // // pipeable sequence S // // $ExpectType ReaderTaskEither<{ readonly a: number; } & { readonly b: string; }, string | number, { readonly a1: number; readonly a2: string; readonly a3: boolean; }> pipe( _.right<{ readonly a: number }, string, number>(1), _.bindTo('a1'), _.apS('a2', _.right('b')), _.apSW('a3', _.right<{ readonly b: string }, number, boolean>(true)) ) // // Do // // $ExpectType ReaderTaskEither pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filterOrElseW // // $ExpectType ReaderTaskEither<{ c: boolean; }, "a1" | "a2", number> pipe( _.left<{ c: boolean }, 'a1', number>('a1'), _.filterOrElseW( (result) => result > 0, () => 'a2' as const ) ) ================================================ FILE: dtslint/ReadonlyArray.ts ================================================ import * as E from '../src/Either' import { identity, pipe } from '../src/function' import * as N from '../src/number' import { Ord } from '../src/Ord' import * as _ from '../src/ReadonlyArray' declare const rus: ReadonlyArray declare const rns: ReadonlyArray declare const rss: ReadonlyArray declare const rtns: ReadonlyArray // prepend pipe(rss, _.prepend('a')) // $ExpectType ReadonlyNonEmptyArray pipe(rss, _.prependW(1)) // $ExpectType ReadonlyNonEmptyArray // append pipe(rss, _.append('a')) // $ExpectType ReadonlyNonEmptyArray pipe(rss, _.appendW(1)) // $ExpectType ReadonlyNonEmptyArray // // zip // _.zip(rns, rss) // $ExpectType readonly (readonly [number, string])[] // // zipWith // _.zipWith(rns, rss, (n, s) => [n, s] as const) // $ExpectType readonly (readonly [number, string])[] // // unzip // _.unzip(rtns) // $ExpectType readonly [readonly number[], readonly string[]] pipe(rtns, _.unzip) // $ExpectType readonly [readonly number[], readonly string[]] // // spanLeft // // $ExpectType Spanned pipe( rus, _.spanLeft((u: unknown): u is number => typeof u === 'number') ) // // lookup // _.lookup(0, [1, 2, 3]) // $ExpectType Option _.lookup(0) // $ExpectType (as: readonly A[]) => Option // // elem // _.elem(N.Eq)(1, [1, 2, 3]) // $ExpectType boolean _.elem(N.Eq)(1) // $ExpectType (as: readonly number[]) => boolean // // difference // _.difference(N.Eq)([1, 2], [3, 4]) // $ExpectType readonly number[] _.difference(N.Eq)([3, 4]) // $ExpectType (ys: readonly number[]) => readonly number[] // // intersection // _.intersection(N.Eq)([1, 2], [3, 4]) // $ExpectType readonly number[] _.intersection(N.Eq)([3, 4]) // $ExpectType (ys: readonly number[]) => readonly number[] // // union // _.union(N.Eq)([1, 2], [3, 4]) // $ExpectType readonly number[] _.union(N.Eq)([3, 4]) // $ExpectType (ys: readonly number[]) => readonly number[] // // zip // _.zip([1, 2], ['a', 'b']) // $ExpectType readonly (readonly [number, string])[] _.zip(['a', 'b']) // $ExpectType (as: readonly A[]) => readonly (readonly [A, string])[] // // cons // _.cons(0, [1, 2]) // $ExpectType ReadonlyNonEmptyArray _.cons(0) // $ExpectType (tail: readonly number[]) => ReadonlyNonEmptyArray // // sort // declare const ord1: Ord<{ readonly a: string }> interface X1 { readonly a: string readonly b: number } declare const x1s: ReadonlyArray _.sort(ord1)(x1s) // $ExpectType ReadonlyArray pipe(x1s, _.sort(ord1)) // $ExpectType ReadonlyArray // // sortBy // declare const ord2: Ord declare const ord3: Ord interface X2 { readonly a: string readonly b: number readonly c: boolean } declare const x2s: ReadonlyArray _.sortBy([ord2, ord3])(x2s) // $ExpectType ReadonlyArray pipe(x2s, _.sortBy([ord2, ord3])) // $ExpectType ReadonlyArray // // Do // // $ExpectType readonly { readonly a1: number; readonly a2: string; }[] pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // some // // $ExpectType Either> pipe( rns, E.fromPredicate( _.some((n) => n > 0), identity ) ) // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const prns: ReadonlyArray declare const prsns: ReadonlyArray declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean declare const isStringWithIndex: (i: number, u: unknown) => u is string declare const isNumberWithIndex: (i: number, sn: string | number) => sn is number declare const predicateWithIndex: (i: number, sn: string | number) => boolean // // filter // // $ExpectType readonly string[] pipe(prsns, _.filter(isString)) // $ExpectType readonly number[] pipe(prns, _.filter(predicate)) // $ExpectType readonly number[] pipe( prns, _.filter( ( _x // $ExpectType number ) => true ) ) // #1484 const isPositive = E.exists((n: number) => n > 0) declare const eithers: ReadonlyArray> pipe(eithers, _.filter(E.isRight), _.filter(isPositive)) interface Registered { readonly type: 'Registered' readonly username: string } interface Unregistered { readonly type: 'Unregistered' } type User = Registered | Unregistered declare const users: ReadonlyArray declare const isRegistered: (u: User) => u is Registered declare const p: (u: User) => boolean const registereds = _.filter(isRegistered)(users) _.filter(p)(registereds) // $ExpectType readonly Registered[] interface Test { test: string } declare const arrayOfTest: Array const isFoo = (t: T) => t.test === 'foo' pipe(arrayOfTest, _.filter(isFoo)) // $ExpectType readonly Test[] // // filterWithIndex // // $ExpectType readonly string[] pipe(prsns, _.filterWithIndex(isStringWithIndex)) // $ExpectType readonly number[] pipe(prns, _.filterWithIndex(predicateWithIndex)) // $ExpectType readonly number[] pipe( prns, _.filterWithIndex( ( _i, // $ExpectType number _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated pipe(prsns, _.partition(isString)) // $ExpectType Separated pipe(prns, _.partition(predicate)) // $ExpectType Separated pipe(prsns, _.partition(isNumber)) // $ExpectType Separated pipe( rns, _.partition( ( _x // $ExpectType number ) => true ) ) // // partitionWithIndex // // $ExpectType Separated pipe(prsns, _.partitionWithIndex(isStringWithIndex)) // $ExpectType Separated pipe(prns, _.partitionWithIndex(predicateWithIndex)) // $ExpectType Separated pipe(prsns, _.partitionWithIndex(isNumberWithIndex)) // $ExpectType Separated pipe( prns, _.partitionWithIndex( ( _i, // $ExpectType number _x // $ExpectType number ) => true ) ) // // takeLeftWhile // // $ExpectType readonly string[] pipe(prsns, _.takeLeftWhile(isString)) // $ExpectType readonly number[] pipe(prns, _.takeLeftWhile(predicate)) // // dropLeftWhile // // $ExpectType readonly string[] pipe(prsns, _.dropLeftWhile(isString)) // $ExpectType readonly number[] pipe(prns, _.dropLeftWhile(predicate)) // // spanLeft // // $ExpectType Spanned pipe(prsns, _.spanLeft(isString)) // $ExpectType Spanned pipe(prns, _.spanLeft(predicate)) // // findFirst // // $ExpectType Option pipe(prsns, _.findFirst(isString)) // $ExpectType Option pipe(prns, _.findFirst(predicate)) // // findLast // // $ExpectType Option pipe(prsns, _.findLast(isString)) // $ExpectType Option pipe(prns, _.findLast(predicate)) // // isEmpty // // $ExpectType Either pipe( rss, E.fromPredicate(_.isEmpty, (as) => as) ) ================================================ FILE: dtslint/ReadonlyMap.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as N from '../src/number' import * as _ from '../src/ReadonlyMap' import * as S from '../src/string' // // member // _.member(S.Eq)('a', new Map()) // $ExpectType boolean _.member(S.Eq)('a') // $ExpectType (m: ReadonlyMap) => boolean // // elem // _.elem(S.Eq)('a', new Map()) // $ExpectType boolean _.elem(S.Eq)('a') // $ExpectType (m: ReadonlyMap) => boolean // // lookup // _.lookup(S.Eq)('a', new Map([['a', 1]])) // $ExpectType Option _.lookup(S.Eq)('a') // $ExpectType (m: ReadonlyMap) => Option // // lookupWithKey // _.lookupWithKey(S.Eq)('a', new Map([['a', 1]])) // $ExpectType Option _.lookupWithKey(S.Eq)('a') // $ExpectType (m: ReadonlyMap) => Option // // isSubmap // _.isSubmap(S.Eq, N.Eq)(new Map([['a', 1]]), new Map([['a', 1]])) // $ExpectType boolean _.isSubmap(S.Eq, N.Eq)(new Map([['a', 1]])) // $ExpectType (me: ReadonlyMap) => boolean // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const prns: ReadonlyMap declare const prsns: ReadonlyMap declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean declare const isStringWithIndex: (k: string, u: unknown) => u is string declare const isNumberWithIndex: (k: string, sn: string | number) => sn is number declare const predicateWithIndex: (k: string, sn: string | number) => boolean // // filter // // $ExpectType ReadonlyMap pipe(prsns, _.filter(isString)) // $ExpectType ReadonlyMap pipe(prns, _.filter(predicate)) // $ExpectType ReadonlyMap pipe( prns, _.filter( ( _x // $ExpectType number ) => true ) ) // // filterWithIndex // // $ExpectType ReadonlyMap pipe(prsns, _.filterWithIndex(isStringWithIndex)) // $ExpectType ReadonlyMap pipe(prns, _.filterWithIndex(predicateWithIndex)) // $ExpectType ReadonlyMap pipe( prns, _.filterWithIndex( ( _k, // $ExpectType string _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated, ReadonlyMap> pipe(prsns, _.partition(isString)) // $ExpectType Separated, ReadonlyMap> pipe(prns, _.partition(predicate)) // $ExpectType Separated, ReadonlyMap> pipe(prsns, _.partition(isNumber)) // $ExpectType Separated, ReadonlyMap> pipe( prns, _.partition( ( _x // $ExpectType number ) => true ) ) // // partitionWithIndex // // $ExpectType Separated, ReadonlyMap> pipe(prsns, _.partitionWithIndex(isStringWithIndex)) // $ExpectType Separated, ReadonlyMap> pipe(prns, _.partitionWithIndex(predicateWithIndex)) // $ExpectType Separated, ReadonlyMap> pipe(prsns, _.partitionWithIndex(isNumberWithIndex)) // $ExpectType Separated, ReadonlyMap> pipe( prns, _.partitionWithIndex( ( _k, // $ExpectType string _x // $ExpectType number ) => true ) ) // // isEmpty // // $ExpectType Either, ReadonlyMap> pipe( prns, E.fromPredicate(_.isEmpty, (as) => as) ) ================================================ FILE: dtslint/ReadonlyNonEmptyArray.ts ================================================ import { pipe } from '../src/function' import { Ord } from '../src/Ord' import * as _ from '../src/ReadonlyNonEmptyArray' declare const ras: ReadonlyArray declare const rneas: _.ReadonlyNonEmptyArray declare const rnens: _.ReadonlyNonEmptyArray declare const rnetns: _.ReadonlyNonEmptyArray<[number, string]> // // zip // _.zip(rnens, rneas) // $ExpectType ReadonlyNonEmptyArray _.zip(rneas) // $ExpectType (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray // // zipWith // _.zipWith(rnens, rneas, (n, s) => [n, s] as const) // $ExpectType ReadonlyNonEmptyArray // // unzip // _.unzip(rnetns) // $ExpectType readonly [ReadonlyNonEmptyArray, ReadonlyNonEmptyArray] pipe(rnetns, _.unzip) // $ExpectType readonly [ReadonlyNonEmptyArray, ReadonlyNonEmptyArray] // // cons // _.cons(1, []) // $ExpectType ReadonlyNonEmptyArray<1> _.cons(1, [2, 3]) // $ExpectType ReadonlyNonEmptyArray // // sort // declare const ordSubX: Ord<{ readonly a: string }> interface X { readonly a: string readonly b: number } declare const xs: ReadonlyArray declare const nexs: _.ReadonlyNonEmptyArray _.sort(ordSubX)(nexs) // $ExpectType ReadonlyNonEmptyArray pipe(nexs, _.sort(ordSubX)) // $ExpectType ReadonlyNonEmptyArray // // group // _.group(ordSubX)(nexs) // $ExpectType ReadonlyNonEmptyArray> pipe(xs, _.group(ordSubX)) // $ExpectType ReadonlyArray> _.group(ordSubX)(nexs) // $ExpectType ReadonlyNonEmptyArray> // TODO pipe(nexs, _.group(ordSubX)) // $ExpectType ReadonlyNonEmptyArray> // // groupSort // _.groupSort(ordSubX)(nexs) // $ExpectType ReadonlyNonEmptyArray> pipe(xs, _.groupSort(ordSubX)) // $ExpectType ReadonlyArray> _.groupSort(ordSubX)(nexs) // $ExpectType ReadonlyNonEmptyArray> // TODO pipe(nexs, _.groupSort(ordSubX)) // $ExpectType ReadonlyNonEmptyArray> // // groupBy // _.groupBy((x: { readonly a: string }) => x.a)(xs) // $ExpectType Readonly>> // $ExpectType Readonly>> pipe( xs, _.groupBy((x) => x.a) ) // // Do // // $ExpectType ReadonlyNonEmptyArray<{ readonly a1: number; readonly a2: string; }> pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filter // declare const isNumber1: (sn: string | number) => sn is number declare const isNumber2: (sn: unknown) => sn is number declare const neasn: _.ReadonlyNonEmptyArray // $ExpectType Option> pipe(neasn, _.filter(isNumber1)) // $ExpectType Option> _.filter(isNumber1)(neasn) // $ExpectType Option> pipe(neasn, _.filter(isNumber2)) // $ExpectType Option> _.filter(isNumber2)(neasn) // // concat // _.concat(ras, rneas) // $ExpectType ReadonlyNonEmptyArray _.concat(rneas, ras) // $ExpectType ReadonlyNonEmptyArray _.concat(rneas)(ras) // $ExpectType ReadonlyNonEmptyArray _.concat(ras)(rneas) // $ExpectType ReadonlyNonEmptyArray ================================================ FILE: dtslint/ReadonlyRecord.ts ================================================ import * as E from '../src/Either' import { Foldable } from '../src/Foldable' import { identity, pipe } from '../src/function' import { HKT } from '../src/HKT' import * as N from '../src/number' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as _ from '../src/ReadonlyRecord' import { getFirstSemigroup } from '../src/Semigroup' import * as S from '../src/string' declare const do1: { [key: string]: O.Option } declare const ro1: Readonly>> declare const stringKey: string declare const d1: { [key: string]: number } declare const recordString: Readonly> declare const r1: Readonly> const l1 = { a: 1 } declare const keyString: string // // hasOwnProperty // // eslint-disable-next-line no-prototype-builtins if (_.hasOwnProperty(keyString, d1)) { keyString // $ExpectType string } // eslint-disable-next-line no-prototype-builtins if (_.hasOwnProperty(keyString, recordString)) { keyString // $ExpectType string } // eslint-disable-next-line no-prototype-builtins if (_.hasOwnProperty(keyString, r1)) { keyString // $ExpectType "a1" | "a2" } // // updateAt // pipe(d1, _.updateAt('a1', 3)) // $ExpectType Option>> pipe(recordString, _.updateAt('a', 3)) // $ExpectType Option>> pipe(r1, _.updateAt('a1', 3)) // $ExpectType Option>> // // modifyAt // pipe(d1, _.modifyAt('a1', identity)) // $ExpectType Option>> pipe(recordString, _.modifyAt('a', identity)) // $ExpectType Option>> pipe(r1, _.modifyAt('a1', identity)) // $ExpectType Option>> // // pop // _.pop('a1')(r1) // $ExpectType Option>]> _.pop('a1')(d1) // $ExpectType Option>]> _.pop(stringKey)(r1) // $ExpectType Option>]> // // collect // _.collect((_k: 'a', n: number) => n)({ a: 1 }) // $ExpectType readonly number[] _.collect((_k: 'a', n: number) => n)(l1) // $ExpectType readonly number[] _.collect((_k, n: number) => n)(d1) // $ExpectType readonly number[] _.collect((_k: 'a1' | 'a2', n: number) => n)(r1) // $ExpectType readonly number[] _.collect(S.Ord)((_k: 'a', n: number) => n)({ a: 1 }) // $ExpectType readonly number[] _.collect(S.Ord)((_k: 'a', n: number) => n)(l1) // $ExpectType readonly number[] _.collect(S.Ord)((_k, n: number) => n)(d1) // $ExpectType readonly number[] _.collect(S.Ord)((_k: 'a1' | 'a2', n: number) => n)(r1) // $ExpectType readonly number[] // // insertAt // _.insertAt('b', 0)(d1) // $ExpectType Readonly> _.insertAt(stringKey, 0)(r1) // $ExpectType Readonly> // // deleteAt // _.deleteAt('a')({ a: 1 }) // $ExpectType Readonly> _.deleteAt('b')({ a: 1 }) // $ExpectType Readonly> _.deleteAt('a')(l1) // $ExpectType Readonly> _.deleteAt('b')(l1) // $ExpectType Readonly> _.deleteAt('b')(d1) // $ExpectType Readonly> _.deleteAt('c')(r1) // $ExpectType Readonly> _.deleteAt('a1')(r1) // $ExpectType Readonly> _.deleteAt(stringKey)(r1) // $ExpectType Readonly> // // mapWithIndex // _.mapWithIndex((_k: 'a', n: number) => n > 2)({ a: 1 }) // $ExpectType Readonly> _.mapWithIndex((_k: 'a', n: number) => n > 2)(l1) // $ExpectType Readonly> _.mapWithIndex((_k: string, n: number) => n > 2)(d1) // $ExpectType Readonly> _.mapWithIndex((_k: 'a1' | 'a2', n: number) => n > 2)(r1) // $ExpectType Readonly> // $ExpectType Readonly> pipe( d1, _.mapWithIndex( ( _key, // $ExpectType string value // $ExpectType number ) => value > 0 ) ) // $ExpectType Readonly> pipe( r1, _.mapWithIndex( ( _key, // $ExpectType "a1" | "a2" value // $ExpectType number ) => value > 0 ) ) // // map // _.map((n: number) => n > 2)({ a: 1 }) // $ExpectType Readonly> _.map((n: number) => n > 2)(l1) // $ExpectType Readonly> _.map((n: number) => n > 2)(d1) // $ExpectType Readonly> _.map((n: number) => n > 2)(r1) // $ExpectType Readonly> const constStruct = { a: 1, b: 2 } as const function mapToBoolean(): { [K in keyof typeof constStruct]: boolean } { return pipe( constStruct, _.map(() => true) ) } // $ExpectType { readonly a: boolean; readonly b: boolean; } mapToBoolean() // // reduceWithIndex // _.reduceWithIndex(S.Ord)('', (k: string, _n) => k)(d1) // $ExpectType string _.reduceWithIndex(S.Ord)('', (k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.reduceWithIndex('', (k: string, _n) => k)(d1) // $ExpectType string _.reduceWithIndex('', (k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.foldMapWithIndex(S.Ord)(S.Monoid)((k: string, _n) => k)(d1) // $ExpectType string _.foldMapWithIndex(S.Ord)(S.Monoid)((k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.foldMapWithIndex(S.Monoid)((k: string, _n) => k)(d1) // $ExpectType string _.foldMapWithIndex(S.Monoid)((k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.reduceRightWithIndex(S.Ord)('', (k: string, _n, _b) => k)(d1) // $ExpectType string _.reduceRightWithIndex(S.Ord)('', (k: 'a1' | 'a2', _n, _b) => k)(r1) // $ExpectType string _.reduceRightWithIndex('', (k: string, _n, _b) => k)(d1) // $ExpectType string _.reduceRightWithIndex('', (k: 'a1' | 'a2', _n, _b) => k)(r1) // $ExpectType string _.singleton('a', 1) // $ExpectType Readonly> _.traverseWithIndex(O.option)((_k, n: number) => O.some(n))(d1) // $ExpectType Option>> _.traverseWithIndex(O.option)((_k: 'a1' | 'a2', n: number) => O.some(n))(r1) // $ExpectType Option>> _.traverse(O.option)((n: number) => O.some(n))(d1) // $ExpectType Option>> _.traverse(O.option)((n: number) => O.some(n))(r1) // $ExpectType Option>> _.sequence(O.option)(do1) // $ExpectType Option>> _.sequence(O.option)(ro1) // $ExpectType Option>> _.readonlyRecord.compact(do1) // $ExpectType Readonly> _.partitionMapWithIndex((_k: string, n: number): E.Either => E.right(n))(d1) // $ExpectType Separated>, Readonly>> _.partitionMapWithIndex((_k: 'a1' | 'a2', n: number): E.Either => E.right(n))(r1) // $ExpectType Separated>, Readonly>> _.partitionWithIndex((_k: string, n: number) => n > 2)(d1) // $ExpectType Separated>, Readonly>> _.partitionWithIndex((_k: 'a1' | 'a2', n: number) => n > 2)(r1) // $ExpectType Separated>, Readonly>> _.filterMapWithIndex((_k: string, n: number) => O.some(n))(d1) // $ExpectType Readonly> _.filterMapWithIndex((_k: 'a1' | 'a2', n: number) => O.some(n))(r1) // $ExpectType Readonly> _.filterWithIndex((_k: string, n: number) => n > 2)(d1) // $ExpectType Readonly> _.filterWithIndex((_k: 'a1' | 'a2', n: number) => n > 2)(r1) // $ExpectType Readonly> declare const arr1: Array<[string, number]> declare const arr2: Array<['a' | 'b', number]> _.fromFoldable(getFirstSemigroup(), RA.Foldable)(arr1) // $ExpectType Readonly> _.fromFoldable(getFirstSemigroup(), RA.Foldable)(arr2) // $ExpectType Readonly> type Keys = 'key1' | 'key2' _.getMonoid(N.SemigroupSum) // $ExpectType Monoid>> _.getMonoid(N.SemigroupSum) // $ExpectType Monoid>> _.getEq(N.Eq) // $ExpectType Eq>> _.getEq(N.Eq) // $ExpectType Eq>> _.toUnfoldable(RA.Unfoldable)({ a: 1 }) // $ExpectType readonly (readonly ["a", number])[] _.toUnfoldable(RA.Unfoldable)({ a1: 1, a2: 2 }) // $ExpectType readonly (readonly ["a1" | "a2", number])[] declare const fromFoldableF1: Foldable<'Test'> declare const fromFoldableInput1: HKT<'Test', ['a' | 'b', number]> _.fromFoldable(getFirstSemigroup(), fromFoldableF1)(fromFoldableInput1) // $ExpectType Readonly> // // isSubrecord // _.isSubrecord(N.Eq)(recordString, recordString) // $ExpectType boolean _.isSubrecord(N.Eq)(recordString) // $ExpectType (me: Readonly>) => boolean // // lookup // _.lookup('a', recordString) // $ExpectType Option _.lookup('a') // $ExpectType (r: Readonly>) => Option // // elem // _.elem(N.Eq)(1, recordString) // $ExpectType boolean _.elem(N.Eq)(1) // $ExpectType (fa: Readonly>) => boolean // // reduce // pipe( r1, _.reduce(1, (acc, n) => acc + n) ) pipe( r1, _.reduce(S.Ord)(1, (acc, n) => acc + n) ) ================================================ FILE: dtslint/ReadonlySet.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as N from '../src/number' import * as _ from '../src/ReadonlySet' declare const me: ReadonlySet // // isSubset // _.isSubset(N.Eq)(me, me) // $ExpectType boolean _.isSubset(N.Eq)(me) // $ExpectType (me: ReadonlySet) => boolean // // elem // _.elem(N.Eq)(1, me) // $ExpectType boolean _.elem(N.Eq)(1) // $ExpectType (set: ReadonlySet) => boolean // // union // _.union(N.Eq)(me, me) // $ExpectType ReadonlySet _.union(N.Eq)(me) // $ExpectType (me: ReadonlySet) => ReadonlySet // // intersection // _.intersection(N.Eq)(me, me) // $ExpectType ReadonlySet _.intersection(N.Eq)(me) // $ExpectType (me: ReadonlySet) => ReadonlySet // // difference // _.difference(N.Eq)(me, me) // $ExpectType ReadonlySet _.difference(N.Eq)(me) // $ExpectType (me: ReadonlySet) => ReadonlySet // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const prns: ReadonlySet declare const prsns: ReadonlySet declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean // // filter // // $ExpectType ReadonlySet pipe(prsns, _.filter(isString)) // $ExpectType ReadonlySet pipe(prns, _.filter(predicate)) // $ExpectType ReadonlySet pipe( prns, _.filter( ( _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated, ReadonlySet> pipe(prsns, _.partition(isString)) // $ExpectType Separated, ReadonlySet> pipe(prns, _.partition(predicate)) // $ExpectType Separated, ReadonlySet> pipe(prsns, _.partition(isNumber)) // $ExpectType Separated, ReadonlySet> pipe( prns, _.partition( ( _x // $ExpectType number ) => true ) ) // // isEmpty // // $ExpectType Either, ReadonlySet> pipe( me, E.fromPredicate(_.isEmpty, (as) => as) ) ================================================ FILE: dtslint/Record.ts ================================================ import * as A from '../src/Array' import * as E from '../src/Either' import { Foldable } from '../src/Foldable' import { identity, pipe } from '../src/function' import { HKT } from '../src/HKT' import * as N from '../src/number' import * as O from '../src/Option' import * as _ from '../src/Record' import { getFirstSemigroup } from '../src/Semigroup' import * as S from '../src/string' declare const do1: { [key: string]: O.Option } declare const ro1: Record<'a1' | 'a2', O.Option> declare const stringKey: string declare const d1: { [key: string]: number } declare const recordString: Record declare const r1: Record<'a1' | 'a2', number> const l1 = { a: 1 } declare const keyString: string // // hasOwnProperty // // eslint-disable-next-line no-prototype-builtins if (_.hasOwnProperty(keyString, d1)) { keyString // $ExpectType string } // eslint-disable-next-line no-prototype-builtins if (_.hasOwnProperty(keyString, recordString)) { keyString // $ExpectType string } // eslint-disable-next-line no-prototype-builtins if (_.hasOwnProperty(keyString, r1)) { keyString // $ExpectType "a1" | "a2" } // // updateAt // pipe(d1, _.updateAt('a1', 3)) // $ExpectType Option> pipe(recordString, _.updateAt('a', 3)) // $ExpectType Option> pipe(r1, _.updateAt('a1', 3)) // $ExpectType Option> // // modifyAt // pipe(d1, _.modifyAt('a1', identity)) // $ExpectType Option> pipe(recordString, _.modifyAt('a', identity)) // $ExpectType Option> pipe(r1, _.modifyAt('a1', identity)) // $ExpectType Option> // // pop // _.pop('a1')(r1) // $ExpectType Option<[number, Record<"a2", number>]> _.pop('a1')(d1) // $ExpectType Option<[number, Record]> _.pop(stringKey)(r1) // $ExpectType Option<[number, Record]> // // collect // _.collect((_k: 'a', n: number) => n)({ a: 1 }) // $ExpectType number[] _.collect((_k: 'a', n: number) => n)(l1) // $ExpectType number[] _.collect((_k, n: number) => n)(d1) // $ExpectType number[] _.collect((_k: 'a1' | 'a2', n: number) => n)(r1) // $ExpectType number[] _.collect(S.Ord)((_k: 'a', n: number) => n)({ a: 1 }) // $ExpectType number[] _.collect(S.Ord)((_k: 'a', n: number) => n)(l1) // $ExpectType number[] _.collect(S.Ord)((_k, n: number) => n)(d1) // $ExpectType number[] _.collect(S.Ord)((_k: 'a1' | 'a2', n: number) => n)(r1) // $ExpectType number[] // // toArray // _.toArray({ a: 1 }) // $ExpectType ["a", number][] _.toArray(l1) // $ExpectType ["a", number][] _.toArray(d1) // $ExpectType [string, number][] _.toArray(r1) // $ExpectType ["a1" | "a2", number][] // // insertAt // _.insertAt('b', 0)(d1) // $ExpectType Record _.insertAt(stringKey, 0)(r1) // $ExpectType Record // // deleteAt // _.deleteAt('a')({ a: 1 }) // $ExpectType Record _.deleteAt('b')({ a: 1 }) // $ExpectType Record<"a", number> _.deleteAt('a')(l1) // $ExpectType Record _.deleteAt('b')(l1) // $ExpectType Record<"a", number> _.deleteAt('b')(d1) // $ExpectType Record _.deleteAt('c')(r1) // $ExpectType Record<"a1" | "a2", number> _.deleteAt('a1')(r1) // $ExpectType Record<"a2", number> _.deleteAt(stringKey)(r1) // $ExpectType Record // // mapWithIndex // _.mapWithIndex((_k: 'a', n: number) => n > 2)({ a: 1 }) // $ExpectType Record<"a", boolean> _.mapWithIndex((_k: 'a', n: number) => n > 2)(l1) // $ExpectType Record<"a", boolean> _.mapWithIndex((_k: string, n: number) => n > 2)(d1) // $ExpectType Record _.mapWithIndex((_k: 'a1' | 'a2', n: number) => n > 2)(r1) // $ExpectType Record<"a1" | "a2", boolean> // // map // _.map((n: number) => n > 2)({ a: 1 }) // $ExpectType Record<"a", boolean> _.map((n: number) => n > 2)(l1) // $ExpectType Record<"a", boolean> _.map((n: number) => n > 2)(d1) // $ExpectType Record _.map((n: number) => n > 2)(r1) // $ExpectType Record<"a1" | "a2", boolean> // // reduceWithIndex // _.reduceWithIndex(S.Ord)('', (k: string, _n) => k)(d1) // $ExpectType string _.reduceWithIndex(S.Ord)('', (k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.reduceWithIndex('', (k: string, _n) => k)(d1) // $ExpectType string _.reduceWithIndex('', (k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.foldMapWithIndex(S.Ord)(S.Monoid)((k: string, _n) => k)(d1) // $ExpectType string _.foldMapWithIndex(S.Ord)(S.Monoid)((k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.foldMapWithIndex(S.Monoid)((k: string, _n) => k)(d1) // $ExpectType string _.foldMapWithIndex(S.Monoid)((k: 'a1' | 'a2', _n) => k)(r1) // $ExpectType string _.reduceRightWithIndex(S.Ord)('', (k: string, _n, _b) => k)(d1) // $ExpectType string _.reduceRightWithIndex(S.Ord)('', (k: 'a1' | 'a2', _n, _b) => k)(r1) // $ExpectType string _.reduceRightWithIndex('', (k: string, _n, _b) => k)(d1) // $ExpectType string _.reduceRightWithIndex('', (k: 'a1' | 'a2', _n, _b) => k)(r1) // $ExpectType string _.singleton('a', 1) // $ExpectType Record _.traverseWithIndex(O.option)((_k, n: number) => O.some(n))(d1) // $ExpectType Option> _.traverseWithIndex(O.option)((_k: 'a1' | 'a2', n: number) => O.some(n))(r1) // $ExpectType Option> _.traverse(O.option)((n: number) => O.some(n))(d1) // $ExpectType Option> _.traverse(O.option)((n: number) => O.some(n))(r1) // $ExpectType Option> _.sequence(O.option)(do1) // $ExpectType Option> _.sequence(O.option)(ro1) // $ExpectType Option> _.record.compact(do1) // $ExpectType Record _.partitionMapWithIndex((_k: string, n: number): E.Either => E.right(n))(d1) // $ExpectType Separated, Record> _.partitionMapWithIndex((_k: 'a1' | 'a2', n: number): E.Either => E.right(n))(r1) // $ExpectType Separated, Record> _.partitionWithIndex((_k: string, n: number) => n > 2)(d1) // $ExpectType Separated, Record> _.partitionWithIndex((_k: 'a1' | 'a2', n: number) => n > 2)(r1) // $ExpectType Separated, Record> _.filterMapWithIndex((_k: string, n: number) => O.some(n))(d1) // $ExpectType Record _.filterMapWithIndex((_k: 'a1' | 'a2', n: number) => O.some(n))(r1) // $ExpectType Record _.filterWithIndex((_k: string, n: number) => n > 2)(d1) // $ExpectType Record _.filterWithIndex((_k: 'a1' | 'a2', n: number) => n > 2)(r1) // $ExpectType Record declare const arr1: Array<[string, number]> declare const arr2: Array<['a' | 'b', number]> _.fromFoldable(getFirstSemigroup(), A.array)(arr1) // $ExpectType Record _.fromFoldable(getFirstSemigroup(), A.array)(arr2) // $ExpectType Record type Keys = 'key1' | 'key2' _.getMonoid(N.SemigroupSum) // $ExpectType Monoid> _.getMonoid(N.SemigroupSum) // $ExpectType Monoid> _.getEq(N.Eq) // $ExpectType Eq> _.getEq(N.Eq) // $ExpectType Eq> _.toUnfoldable(A.array)({ a: 1 }) // $ExpectType ["a", number][] _.toUnfoldable(A.array)({ a1: 1, a2: 2 }) // $ExpectType ["a1" | "a2", number][] declare const fromFoldableF1: Foldable<'Test'> declare const fromFoldableInput1: HKT<'Test', ['a' | 'b', number]> _.fromFoldable(getFirstSemigroup(), fromFoldableF1)(fromFoldableInput1) // $ExpectType Record // // isSubrecord // _.isSubrecord(N.Eq)(recordString, recordString) // $ExpectType boolean _.isSubrecord(N.Eq)(recordString) // $ExpectType (me: Record) => boolean // // lookup // _.lookup('a', recordString) // $ExpectType Option _.lookup('a') // $ExpectType (r: Record) => Option // // elem // _.elem(N.Eq)(1, recordString) // $ExpectType boolean _.elem(N.Eq)(1) // $ExpectType (fa: Record) => boolean // // reduce // pipe( r1, _.reduce(1, (acc, n) => acc + n) ) pipe( r1, _.reduce(S.Ord)(1, (acc, n) => acc + n) ) ================================================ FILE: dtslint/Ring.ts ================================================ import * as N from '../src/number' import * as _ from '../src/Ring' // // tuple // // $ExpectType Ring _.tuple(N.Field, N.Field, N.Field) // // getTupleRing // _.getTupleRing(N.Field, N.Field, N.Field) // $ExpectType Ring<[number, number, number]> ================================================ FILE: dtslint/Semigroup.ts ================================================ import * as B from '../src/boolean' import * as N from '../src/number' import * as _ from '../src/Semigroup' import * as S from '../src/string' // // struct // // $ExpectType Semigroup<{ readonly a: string; readonly b: number; readonly c: boolean; }> _.struct({ a: S.Semigroup, b: N.SemigroupSum, c: B.SemigroupAll }) // // tuple // // $ExpectType Semigroup _.tuple(S.Semigroup, N.SemigroupSum, B.SemigroupAll) // // getTupleSemigroup // _.getTupleSemigroup(_.semigroupString, _.semigroupSum, _.semigroupAll) // $ExpectType Semigroup<[string, number, boolean]> // // fold // _.fold(_.semigroupString)('', ['a']) // $ExpectType string _.fold(_.semigroupString)('') // $ExpectType (as: readonly string[]) => string ================================================ FILE: dtslint/Set.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as N from '../src/number' import * as _ from '../src/Set' declare const me: Set // // subset // _.subset(N.Eq)(me, me) // $ExpectType boolean _.subset(N.Eq)(me) // $ExpectType (me: Set) => boolean // // elem // _.elem(N.Eq)(1, me) // $ExpectType boolean _.elem(N.Eq)(1) // $ExpectType (set: Set) => boolean // // union // _.union(N.Eq)(me, me) // $ExpectType Set _.union(N.Eq)(me) // $ExpectType (me: Set) => Set // // intersection // _.intersection(N.Eq)(me, me) // $ExpectType Set _.intersection(N.Eq)(me) // $ExpectType (me: Set) => Set // // difference // _.difference(N.Eq)(me, me) // $ExpectType Set _.difference(N.Eq)(me) // $ExpectType (me: Set) => Set // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const prns: Set declare const prsns: Set declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean // // filter // // $ExpectType Set pipe(prsns, _.filter(isString)) // $ExpectType Set pipe(prns, _.filter(predicate)) // $ExpectType Set pipe( prns, _.filter( ( _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated, Set> pipe(prsns, _.partition(isString)) // $ExpectType Separated, Set> pipe(prns, _.partition(predicate)) // $ExpectType Separated, Set> pipe(prsns, _.partition(isNumber)) // $ExpectType Separated, Set> pipe( prns, _.partition( ( _x // $ExpectType number ) => true ) ) // // isEmpty // // $ExpectType Either, Set> pipe( me, E.fromPredicate(_.isEmpty, (as) => as) ) ================================================ FILE: dtslint/Show.ts ================================================ import * as B from '../src/boolean' import * as N from '../src/number' import * as _ from '../src/Show' import * as S from '../src/string' // // struct // // $ExpectType Show<{ readonly a: string; readonly b: number; readonly c: boolean; }> _.struct({ a: S.Show, b: N.Show, c: B.Show }) // // tuple // // $ExpectType Show _.tuple(S.Show, N.Show, B.Show) ================================================ FILE: dtslint/StateReaderTaskEither.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as IOE from '../src/IOEither' import * as RTE from '../src/ReaderTaskEither' import * as _ from '../src/StateReaderTaskEither' import * as TE from '../src/TaskEither' // // chainW // // $ExpectType StateReaderTaskEither pipe( _.right('a'), _.chainW(() => _.right(1)) ) // // chainEitherKW // // $ExpectType StateReaderTaskEither pipe( _.right('a'), _.chainEitherKW(() => E.right(1)) ) // // chainTaskEitherKW // // $ExpectType StateReaderTaskEither pipe( _.right('a'), _.chainTaskEitherKW(() => TE.right(1)) ) // // chainReaderTaskEitherKW // // $ExpectType StateReaderTaskEither pipe( _.right('a'), _.chainReaderTaskEitherKW(() => RTE.right(1)) ) // // chainIOEitherKW // // $ExpectType StateReaderTaskEither pipe( _.right('a'), _.chainIOEitherKW(() => IOE.right(1)) ) // // do notation // // $ExpectType StateReaderTaskEither pipe( _.right(1), _.bindTo('a1'), _.bind('a2', () => _.right('b')), _.bindW('a3', () => _.right(true)) ) // // pipeable sequence S // // $ExpectType StateReaderTaskEither pipe( _.right(1), _.bindTo('a1'), _.apS('a2', _.right('b')), _.apSW('a3', _.right(true)) ) // // filterOrElseW // // $ExpectType StateReaderTaskEither<{ d: Date; }, { c: boolean; }, "a1" | "a2", number> pipe( _.left<{ d: Date }, { c: boolean }, 'a1', number>('a1'), _.filterOrElseW( (result) => result > 0, () => 'a2' as const ) ) ================================================ FILE: dtslint/Task.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/Task' // // Do // // $ExpectType Task<{ readonly a1: number; readonly a2: string; }> pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) ================================================ FILE: dtslint/TaskEither.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as IO from '../src/IO' import * as IOE from '../src/IOEither' import * as T from '../src/Task' import * as _ from '../src/TaskEither' import * as TO from '../src/TaskOption' // // getOrElseW // // $ExpectType Task pipe( _.right('a'), _.getOrElseW(() => T.of(null)) ) // // orElse // // $ExpectType TaskEither pipe( _.left('a'), _.orElse((a) => _.left(a.length)) ) // // orElseW // // $ExpectType TaskEither pipe( _.left('a'), _.orElseW((a) => _.right(a.length)) ) // // orElseFirst // // $ExpectType TaskEither pipe( _.left('a'), _.orElseFirst((a) => _.right(a.length)) ) // // orElseFirstW // // $ExpectType TaskEither pipe( _.left('a'), _.orElseFirstW((a) => _.left(a.length)) ) // // orElseFirstIOK // // $ExpectType TaskEither pipe( _.left('a'), _.orElseFirstIOK((a) => IO.of(a.length)) ) // // orElseFirstTaskK // // $ExpectType TaskEither pipe( _.left('a'), _.orElseFirstTaskK((a) => T.of(a.length)) ) // // orLeft // // $ExpectType TaskEither pipe( _.left('a'), _.orLeft((a) => T.of(a.length)) ) // // chainW // // $ExpectType TaskEither pipe( _.right('a'), _.chainW(() => _.right(1)) ) // // chainEitherKW // // $ExpectType TaskEither pipe( _.right('a'), _.chainEitherKW(() => E.right(1)) ) // // chainIOEitherKW // // $ExpectType TaskEither pipe( _.right('a'), _.chainIOEitherKW(() => IOE.right(1)) ) // // fromTaskOption // // $ExpectType TaskEither pipe( TO.some(1), _.fromTaskOption(() => 'a') ) // // taskify // declare function apiForTaskify(path: string, callback: (err: Error | null | undefined, result?: string) => void): void _.taskify(apiForTaskify) // $ExpectType (a: string) => TaskEither // // do notation // // $ExpectType TaskEither pipe( _.right(1), _.bindTo('a1'), _.bind('a2', () => _.right('b')), _.bindW('a3', () => _.right(true)) ) // // pipeable sequence S // // $ExpectType TaskEither pipe( _.right(1), _.bindTo('a1'), _.apS('a2', _.right('b')), _.apSW('a3', _.right(true)) ) // // Do // // $ExpectType TaskEither pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) // // filterOrElseW // // $ExpectType TaskEither<"a1" | "a2", number> pipe( _.left<'a1', number>('a1'), _.filterOrElseW( (result) => result > 0, () => 'a2' as const ) ) ================================================ FILE: dtslint/TaskOption.ts ================================================ import { pipe } from '../src/function' import * as TE from '../src/TaskEither' import * as _ from '../src/TaskOption' declare const tesn: TE.TaskEither // // fromTaskEither // pipe(tesn, _.fromTaskEither) // $ExpectType TaskOption // ------------------------------------------------------------------------------------- // Predicate-based APIs // ------------------------------------------------------------------------------------- declare const n: number declare const sn: string | number declare const on: _.TaskOption declare const osn: _.TaskOption declare const isString: (u: unknown) => u is string declare const isNumber: (sn: string | number) => sn is number declare const predicate: (sn: string | number) => boolean // // filter // // $ExpectType TaskOption pipe(osn, _.filter(isString)) // $ExpectType TaskOption pipe(on, _.filter(predicate)) // $ExpectType TaskOption pipe( on, _.filter( ( _x // $ExpectType number ) => true ) ) // // partition // // $ExpectType Separated, TaskOption> pipe(osn, _.partition(isString)) // $ExpectType Separated, TaskOption> pipe(on, _.partition(predicate)) // $ExpectType Separated, TaskOption> pipe(osn, _.partition(isNumber)) // $ExpectType Separated, TaskOption> pipe( on, _.partition( ( _x // $ExpectType number ) => true ) ) // // fromPredicate // // $ExpectType TaskOption pipe(sn, _.fromPredicate(isString)) // $ExpectType TaskOption pipe(n, _.fromPredicate(predicate)) // $ExpectType TaskOption pipe( n, _.fromPredicate( ( _n // $ExpectType number ) => true ) ) // // filterOrElse // ================================================ FILE: dtslint/Traversable.ts ================================================ import * as E from '../src/Either' import * as RA from '../src/ReadonlyArray' import * as TE from '../src/TaskEither' import * as _ from '../src/Traversable' // // traversable // // $ExpectType (f: (a: A) => TaskEither) => (tga: readonly Either[]) => TaskEither[]> _.traverse(RA.Traversable, E.Traversable)(TE.ApplicativePar) // // traversable // // $ExpectType (tgfa: readonly Either>[]) => TaskEither[]> _.sequence(RA.Traversable, E.Traversable)(TE.ApplicativePar) ================================================ FILE: dtslint/Tree.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/Tree' // // Do // // $ExpectType Tree<{ readonly a1: number; readonly a2: string; }> pipe( _.Do, _.bind('a1', () => _.of(1)), _.bind('a2', () => _.of('b')) ) ================================================ FILE: dtslint/constrained.ts ================================================ import { Alt2C, Alt3C } from '../src/Alt' import { Alternative2C, Alternative3C } from '../src/Alternative' import { Applicative2C, Applicative3C } from '../src/Applicative' import { Apply2C, Apply3C } from '../src/Apply' import { Bifunctor2C, Bifunctor3C } from '../src/Bifunctor' import { Chain2C, Chain3C } from '../src/Chain' import { ChainRec2C, ChainRec3C } from '../src/ChainRec' import { Comonad2C, Comonad3C } from '../src/Comonad' import { Compactable2C, Compactable3C } from '../src/Compactable' import { Contravariant2C, Contravariant3C } from '../src/Contravariant' import { Extend2C, Extend3C } from '../src/Extend' import { Filterable2C, Filterable3C } from '../src/Filterable' import { FilterableWithIndex2C } from '../src/FilterableWithIndex' import { Foldable2C, Foldable3C } from '../src/Foldable' import { FoldableWithIndex2C, FoldableWithIndex3C } from '../src/FoldableWithIndex' import { FromEither2C, FromEither3C } from '../src/FromEither' import { FromIO2C, FromIO3C } from '../src/FromIO' import { FromTask2C, FromTask3C } from '../src/FromTask' import { Functor2C, Functor3C } from '../src/Functor' import { FunctorWithIndex2C, FunctorWithIndex3C } from '../src/FunctorWithIndex' import { Invariant2C, Invariant3C } from '../src/Invariant' import { Monad2C, Monad3C } from '../src/Monad' import { Pointed2C, Pointed3C } from '../src/Pointed' import { Profunctor2C, Profunctor3C } from '../src/Profunctor' import { Traversable2C } from '../src/Traversable' import { TraversableWithIndex2C } from '../src/TraversableWithIndex' import { Unfoldable2C, Unfoldable3C } from '../src/Unfoldable' import { Witherable2C } from '../src/Witherable' // $ExpectType string export type _1 = Alt2C<'Either', string>['_E'] // $ExpectType string export type _2 = Alt3C<'ReaderEither', string>['_E'] // $ExpectType string export type _3 = Alternative2C<'Either', string>['_E'] // $ExpectType string export type _4 = Alternative3C<'ReaderEither', string>['_E'] // $ExpectType string export type _5 = Applicative2C<'Either', string>['_E'] // $ExpectType string export type _6 = Applicative3C<'ReaderEither', string>['_E'] // $ExpectType string export type _7 = Apply2C<'Either', string>['_E'] // $ExpectType string export type _8 = Apply3C<'ReaderEither', string>['_E'] // $ExpectType string export type _9 = Bifunctor2C<'Either', string>['_E'] // $ExpectType string export type _10 = Bifunctor3C<'ReaderEither', string>['_E'] // $ExpectType string export type _11 = Comonad2C<'Either', string>['_E'] // $ExpectType string export type _12 = Comonad3C<'ReaderEither', string>['_E'] // $ExpectType string export type _13 = Compactable2C<'Either', string>['_E'] // $ExpectType string export type _14 = Compactable3C<'ReaderEither', string>['_E'] // $ExpectType string export type _15 = Contravariant2C<'Either', string>['_E'] // $ExpectType string export type _16 = Contravariant3C<'ReaderEither', string>['_E'] // $ExpectType string export type _17 = Extend2C<'Either', string>['_E'] // $ExpectType string export type _18 = Extend3C<'ReaderEither', string>['_E'] // $ExpectType string export type _19 = Filterable2C<'Either', string>['_E'] // $ExpectType string export type _20 = Filterable3C<'ReaderEither', string>['_E'] // $ExpectType string export type _21 = FilterableWithIndex2C<'Either', number, string>['_E'] // $ExpectType string export type _22 = Foldable2C<'Either', string>['_E'] // $ExpectType string export type _23 = Foldable3C<'ReaderEither', string>['_E'] // $ExpectType string export type _24 = FoldableWithIndex2C<'Either', number, string>['_E'] // $ExpectType string export type _25 = FoldableWithIndex3C<'ReaderEither', number, string>['_E'] // $ExpectType string export type _26 = FromEither2C<'Either', string>['_E'] // $ExpectType string export type _27 = FromEither3C<'ReaderEither', string>['_E'] // $ExpectType string export type _28 = FromIO2C<'Either', string>['_E'] // $ExpectType string export type _29 = FromIO3C<'ReaderEither', string>['_E'] // $ExpectType string export type _30 = FromTask2C<'Either', string>['_E'] // $ExpectType string export type _31 = FromTask3C<'ReaderEither', string>['_E'] // $ExpectType string export type _32 = Functor2C<'Either', string>['_E'] // $ExpectType string export type _33 = Functor3C<'ReaderEither', string>['_E'] // $ExpectType string export type _34 = FunctorWithIndex2C<'Either', number, string>['_E'] // $ExpectType string export type _35 = FunctorWithIndex3C<'ReaderEither', number, string>['_E'] // $ExpectType string export type _36 = Invariant2C<'Either', string>['_E'] // $ExpectType string export type _37 = Invariant3C<'ReaderEither', string>['_E'] // $ExpectType string export type _38 = Monad2C<'Either', string>['_E'] // $ExpectType string export type _39 = Monad3C<'ReaderEither', string>['_E'] // $ExpectType string export type _40 = Pointed2C<'Either', string>['_E'] // $ExpectType string export type _41 = Pointed3C<'ReaderEither', string>['_E'] // $ExpectType string export type _42 = Profunctor2C<'Either', string>['_E'] // $ExpectType string export type _43 = Profunctor3C<'ReaderEither', string>['_E'] // $ExpectType string export type _44 = Traversable2C<'Either', string>['_E'] // $ExpectType string export type _45 = TraversableWithIndex2C<'Either', number, string>['_E'] // $ExpectType string export type _46 = Unfoldable2C<'Either', string>['_E'] // $ExpectType string export type _47 = Unfoldable3C<'ReaderEither', string>['_E'] // $ExpectType string export type _48 = Witherable2C<'Either', string>['_E'] // $ExpectType string export type _49 = Chain2C<'Either', string>['_E'] // $ExpectType string export type _50 = Chain3C<'ReaderEither', string>['_E'] // $ExpectType string export type _51 = ChainRec2C<'Either', string>['_E'] // $ExpectType string export type _52 = ChainRec3C<'ReaderEither', string>['_E'] ================================================ FILE: dtslint/function.ts ================================================ import * as _ from '../src/function' import * as RA from '../src/ReadonlyArray' // // flip // // should handle generics _.flip(RA.snoc) // $ExpectType (b: A, a: ReadonlyArray) => ReadonlyNonEmptyArray // // tuple // _.tuple() // $ExpectType [] _.tuple(1) // $ExpectType [number] _.tuple(1, 'a') // $ExpectType [number, string] _.tuple(1, 'a', true) // $ExpectType [number, string, boolean] // $ExpectType (init: ReadonlyArray, end: A) => Option _.flow(RA.snoc, RA.head) // // tupled // _.tupled(RA.insertAt)([0, 'a']) // $ExpectType (as: ReadonlyArray) => Option> // // untupled // _.untupled(_.tupled(RA.insertAt)) // $ExpectType (i: number, a: A) => (as: ReadonlyArray) => Option> ================================================ FILE: dtslint/index.d.ts ================================================ ================================================ FILE: dtslint/index.ts ================================================ import * as _ from '../src/HKT' import * as T from '../src/Task' // issue #536 export function testIssue536(x: _.Kind): _.Kind { // @ts-expect-error return x } export const testURI = (ma: T.Task): _.Kind => { // @ts-expect-error return ma } // @ts-expect-error export type HKT1 = _.Kind<'a', string> export type Tuple = readonly [A, E] ================================================ FILE: dtslint/pipeable.ts ================================================ import { Chain3C } from '../src/Chain' import * as Eq from '../src/Eq' import * as O from '../src/Option' import * as P from '../src/pipeable' import * as R from '../src/Reader' import * as RTE from '../src/ReaderTaskEither' import * as RA from '../src/ReadonlyArray' import * as RT from '../src/ReadonlyTuple' import * as SRTE from '../src/StateReaderTaskEither' import * as S from '../src/string' import * as T from '../src/Task' import * as TE from '../src/TaskEither' import * as TH from '../src/These' const TEApplicative = TE.getApplicativeTaskValidation(T.ApplyPar, S.Semigroup) const TEAlt = TE.getAltTaskValidation(S.Semigroup) const RTEApplicative = RTE.getApplicativeReaderTaskValidation(T.ApplyPar, S.Semigroup) const RTEAlt = RTE.getAltReaderTaskValidation(S.Semigroup) // // map // // $ExpectType (f: (a: A) => B) => (fa: Task) => Task P.map(T.Functor) // $ExpectType (f: (a: A) => B) => (fa: TaskEither) => TaskEither P.map(TE.Functor) // $ExpectType (f: (a: A) => B) => (fa: TaskEither) => TaskEither P.map(TEApplicative) // $ExpectType (f: (a: A) => B) => (fa: ReaderTaskEither) => ReaderTaskEither P.map(RTE.Functor) // $ExpectType (f: (a: A) => B) => (fa: ReaderTaskEither) => ReaderTaskEither P.map(RTEApplicative) // $ExpectType (f: (a: A) => B) => (fa: StateReaderTaskEither) => StateReaderTaskEither P.map(SRTE.Functor) // // mapWithIndex // // $ExpectType (f: (i: number, a: A) => B) => (fa: readonly A[]) => readonly B[] P.mapWithIndex(RA.FunctorWithIndex) // // contramap // // $ExpectType (f: (b: B) => A) => (fa: Eq) => Eq P.contramap(Eq.Contravariant) // // ap // // $ExpectType (fa: Task) => (fab: Task<(a: A) => B>) => Task P.ap(T.ApplyPar) // $ExpectType (fa: TaskEither) => (fab: TaskEither B>) => TaskEither P.ap(TE.ApplyPar) // $ExpectType (fa: TaskEither) => (fab: TaskEither B>) => TaskEither P.ap(TEApplicative) // $ExpectType (fa: ReaderTaskEither) => (fab: ReaderTaskEither B>) => ReaderTaskEither P.ap(RTE.ApplyPar) // $ExpectType (fa: ReaderTaskEither) => (fab: ReaderTaskEither B>) => ReaderTaskEither P.ap(RTEApplicative) // $ExpectType (fa: StateReaderTaskEither) => (fab: StateReaderTaskEither B>) => StateReaderTaskEither P.ap(SRTE.Apply) // // chain // // $ExpectType (f: (a: A) => Task) => (fa: Task) => Task P.chain(T.Chain) // $ExpectType (f: (a: A) => TaskEither) => (fa: TaskEither) => TaskEither P.chain(TE.Chain) const THChain = TH.getChain(S.Semigroup) // $ExpectType (f: (a: A) => These) => (fa: These) => These P.chain(THChain) // $ExpectType (f: (a: A) => ReaderTaskEither) => (fa: ReaderTaskEither) => ReaderTaskEither P.chain(RTE.Chain) declare const Chain3C: Chain3C // $ExpectType (f: (a: A) => ReaderTaskEither) => (fa: ReaderTaskEither) => ReaderTaskEither P.chain(Chain3C) // $ExpectType (f: (a: A) => StateReaderTaskEither) => (fa: StateReaderTaskEither) => StateReaderTaskEither P.chain(SRTE.Chain) // // bimap // // $ExpectType (f: (e: E) => G, g: (a: A) => B) => (fea: These) => These P.bimap(TH.Bifunctor) // // mapLeft // // $ExpectType (f: (e: E) => G) => (fea: These) => These P.mapLeft(TH.Bifunctor) // // extend // // $ExpectType (f: (wa: readonly A[]) => B) => (wa: readonly A[]) => readonly B[] P.extend(RA.Extend) // // reduce // // $ExpectType (b: B, f: (b: B, a: A) => B) => (fa: readonly A[]) => B P.reduce(RA.Foldable) // // foldMap // // $ExpectType (M: Monoid) => (f: (a: A) => M) => (fa: readonly A[]) => M P.foldMap(RA.Foldable) // // reduceRight // // $ExpectType (b: B, f: (a: A, b: B) => B) => (fa: readonly A[]) => B P.reduceRight(RA.Foldable) // // reduceWithIndex // // $ExpectType (b: B, f: (i: number, b: B, a: A) => B) => (fa: readonly A[]) => B P.reduceWithIndex(RA.FoldableWithIndex) // // foldMapWithIndex // // $ExpectType (M: Monoid) => (f: (i: number, a: A) => M) => (fa: readonly A[]) => M P.foldMapWithIndex(RA.FoldableWithIndex) // // reduceRightWithIndex // // $ExpectType (b: B, f: (i: number, a: A, b: B) => B) => (fa: readonly A[]) => B P.reduceRightWithIndex(RA.FoldableWithIndex) // // alt // // $ExpectType (that: LazyArg>) => (fa: Option) => Option P.alt(O.Alt) // $ExpectType (that: LazyArg>) => (fa: TaskEither) => TaskEither P.alt(TE.Alt) // $ExpectType (that: LazyArg>) => (fa: TaskEither) => TaskEither P.alt(TEAlt) // $ExpectType (that: LazyArg>) => (fa: ReaderTaskEither) => ReaderTaskEither P.alt(RTE.Alt) // $ExpectType (that: LazyArg>) => (fa: ReaderTaskEither) => ReaderTaskEither P.alt(RTEAlt) // $ExpectType (that: LazyArg>) => (fa: StateReaderTaskEither) => StateReaderTaskEither P.alt(SRTE.Alt) // // filter // // $ExpectType { (refinement: Refinement): (fa: readonly A[]) => readonly B[]; (predicate: Predicate): (fa: readonly A[]) => readonly A[]; } P.filter(RA.Filterable) // // filterMap // // $ExpectType (f: (a: A) => Option) => (fa: readonly A[]) => readonly B[] P.filterMap(RA.Filterable) // // partition // // $ExpectType { (refinement: Refinement): (fa: readonly A[]) => Separated; (predicate: Predicate): (fa: readonly A[]) => Separated; } P.partition(RA.Filterable) // // partitionMap // // $ExpectType (f: (a: A) => Either) => (fa: readonly A[]) => Separated P.partitionMap(RA.Filterable) // // filterWithIndex // // $ExpectType { (refinement: RefinementWithIndex): (fa: readonly A[]) => readonly B[]; (predicate: PredicateWithIndex): (fa: readonly A[]) => readonly A[]; } P.filterWithIndex(RA.FilterableWithIndex) // // filterMapWithIndex // // $ExpectType (f: (i: number, a: A) => Option) => (fa: readonly A[]) => readonly B[] P.filterMapWithIndex(RA.FilterableWithIndex) // // partitionWithIndex // // $ExpectType { (refinement: RefinementWithIndex): (fa: readonly A[]) => Separated; (predicate: PredicateWithIndex): (fa: readonly A[]) => Separated; } P.partitionWithIndex(RA.FilterableWithIndex) // // partitionMapWithIndex // // $ExpectType (f: (i: number, a: A) => Either) => (fa: readonly A[]) => Separated P.partitionMapWithIndex(RA.FilterableWithIndex) // // promap // // $ExpectType (f: (d: D) => E, g: (a: A) => B) => (fbc: Reader) => Reader P.promap(R.Profunctor) // // compose // // $ExpectType (ea: readonly [A, E]) => (ab: readonly [B, A]) => readonly [B, E] P.compose(RT.Semigroupoid) ================================================ FILE: dtslint/tsconfig.json ================================================ { "extends": "../tsconfig.json", "include": ["."], "compilerOptions": { "incremental": false, "composite": false, "noUnusedLocals": false } } ================================================ FILE: examples/fp-ts-to-the-max-I.ts ================================================ import { createInterface } from 'readline' import { log } from '../src/Console' import { flow, pipe } from '../src/function' import * as O from '../src/Option' import { randomInt } from '../src/Random' import * as T from '../src/Task' // // helpers // // read from standard input const getStrLn: T.Task = () => new Promise((resolve) => { const rl = createInterface({ input: process.stdin, output: process.stdout }) rl.question('> ', (answer) => { rl.close() resolve(answer) }) }) // write to standard output const putStrLn = flow(log, T.fromIO) // ask something and get the answer function ask(question: string): T.Task { return pipe( putStrLn(question), T.flatMap(() => getStrLn) ) } // get a random int between 1 and 5 const random = T.fromIO(randomInt(1, 5)) // parse a string to an integer function parse(s: string): O.Option { const i = +s return isNaN(i) || i % 1 !== 0 ? O.none : O.some(i) } // // game // function shouldContinue(name: string): T.Task { return pipe( ask(`Do you want to continue, ${name} (y/n)?`), T.flatMap((answer) => { switch (answer.toLowerCase()) { case 'y': return T.of(true) case 'n': return T.of(false) default: return shouldContinue(name) } }) ) } function gameLoop(name: string): T.Task { return pipe( T.Do, T.apS('secret', random), T.apS('guess', ask(`Dear ${name}, please guess a number from 1 to 5`)), T.flatMap(({ secret, guess }) => pipe( parse(guess), O.fold( () => putStrLn('You did not enter an integer!'), (x) => x === secret ? putStrLn(`You guessed right, ${name}!`) : putStrLn(`You guessed wrong, ${name}! The number was: ${secret}`) ) ) ), T.flatMap(() => shouldContinue(name)), T.flatMap((b) => (b ? gameLoop(name) : T.of(undefined))) ) } const main: T.Task = pipe( ask('What is your name?'), T.tap((name) => putStrLn(`Hello, ${name} welcome to the game!`)), T.flatMap(gameLoop) ) // tslint:disable-next-line: no-floating-promises main() ================================================ FILE: examples/fp-ts-to-the-max-II.ts ================================================ import * as assert from 'assert' import { createInterface } from 'readline' import { apS as apS_ } from '../src/Apply' import { chainFirst as chainFirst_ } from '../src/Chain' import { log } from '../src/Console' import { flow, pipe } from '../src/function' import { Kind, URIS } from '../src/HKT' import { Monad1 } from '../src/Monad' import * as O from '../src/Option' import { randomInt } from '../src/Random' import { append, dropLeft } from '../src/ReadonlyArray' import * as S from '../src/State' import * as T from '../src/Task' // // type classes // interface Program extends Monad1 { readonly finish: (a: A) => Kind } interface Console { readonly putStrLn: (message: string) => Kind readonly getStrLn: Kind } interface Random { readonly nextInt: (upper: number) => Kind } interface Main extends Program, Console, Random {} // // instances // const programTask: Program = { ...T.Monad, finish: T.of } // read from standard input const getStrLn: T.Task = () => new Promise((resolve) => { const rl = createInterface({ input: process.stdin, output: process.stdout }) rl.question('> ', (answer) => { rl.close() resolve(answer) }) }) // write to standard output const putStrLn = flow(log, T.fromIO) const consoleTask: Console = { putStrLn, getStrLn } const randomTask: Random = { nextInt: (upper) => T.fromIO(randomInt(1, upper)) } // // game // // parse a string to an integer function parse(s: string): O.Option { const i = +s return isNaN(i) || i % 1 !== 0 ? O.none : O.some(i) } function main(F: Main): Kind { const flatMap = (f: (a: A) => Kind) => (ma: Kind): Kind => F.chain(ma, f) const Do: Kind = F.of({}) const apS = apS_(F) const tap = chainFirst_(F) // ask something and get the answer const ask = (question: string): Kind => pipe( F.putStrLn(question), flatMap(() => F.getStrLn) ) const shouldContinue = (name: string): Kind => { return pipe( ask(`Do you want to continue, ${name} (y/n)?`), flatMap((answer) => { switch (answer.toLowerCase()) { case 'y': return F.of(true) case 'n': return F.of(false) default: return shouldContinue(name) } }) ) } const gameLoop = (name: string): Kind => { return pipe( Do, apS('secret', F.nextInt(5)), apS('guess', ask(`Dear ${name}, please guess a number from 1 to 5`)), flatMap(({ secret, guess }) => pipe( parse(guess), O.fold( () => F.putStrLn('You did not enter an integer!'), (x) => x === secret ? F.putStrLn(`You guessed right, ${name}!`) : F.putStrLn(`You guessed wrong, ${name}! The number was: ${secret}`) ) ) ), flatMap(() => shouldContinue(name)), flatMap((b) => (b ? gameLoop(name) : F.of(undefined))) ) } return pipe( ask('What is your name?'), tap((name) => F.putStrLn(`Hello, ${name} welcome to the game!`)), flatMap(gameLoop) ) } export const mainTask = main({ ...programTask, ...consoleTask, ...randomTask }) // tslint:disable-next-line: no-floating-promises // mainTask() // // tests // class TestData { constructor( readonly input: ReadonlyArray, readonly output: ReadonlyArray, readonly nums: ReadonlyArray ) {} putStrLn(message: string): [void, TestData] { return [undefined, new TestData(this.input, pipe(this.output, append(message)), this.nums)] } getStrLn(): [string, TestData] { return [this.input[0], new TestData(dropLeft(1)(this.input), this.output, this.nums)] } nextInt(_upper: number): [number, TestData] { return [this.nums[0], new TestData(this.input, this.output, dropLeft(1)(this.nums))] } } const URI = 'Test' type URI = typeof URI declare module '../src/HKT' { interface URItoKind { readonly Test: Test } } interface Test extends S.State {} const of = (a: A): Test => (data) => [a, data] const programTest: Program = { ...S.Monad, URI, finish: of } const consoleTest: Console = { putStrLn: (message) => (data) => data.putStrLn(message), getStrLn: (data) => data.getStrLn() } const randomTest: Random = { nextInt: (upper) => (data) => { return data.nextInt(upper) } } const mainTestTask = main({ ...programTest, ...consoleTest, ...randomTest }) const testExample = new TestData(['Giulio', '1', 'n'], [], [1]) assert.deepStrictEqual(mainTestTask(testExample), [ undefined, new TestData( [], [ 'What is your name?', 'Hello, Giulio welcome to the game!', 'Dear Giulio, please guess a number from 1 to 5', 'You guessed right, Giulio!', 'Do you want to continue, Giulio (y/n)?' ], [] ) ]) ================================================ FILE: examples/tsconfig.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "noEmit": true }, "include": ["./**/*"] } ================================================ FILE: package.json ================================================ { "name": "fp-ts", "version": "2.16.11", "description": "Functional programming in TypeScript", "main": "./lib/index.js", "module": "./es6/index.js", "typings": "lib/index.d.ts", "sideEffects": false, "scripts": { "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\" \"scripts/**/*.ts\"", "lint-fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\" \"scripts/**/*.ts\"", "prettier": "prettier --list-different \"./{src,test,examples,scripts}/**/*.ts\"", "fix-prettier": "prettier --write \"./{src,test,examples,scripts}/**/*.ts\"", "test": "npm run lint && npm run prettier && npm run dtslint && npm run vitest && npm run docs", "clean": "rimraf ./dist", "prebuild": "npm run clean", "build": "tsc -p ./tsconfig.build.json && tsc -p ./tsconfig.build-es6.json && ts-node scripts/build", "postbuild": "prettier --loglevel=silent --write \"./dist/**/*.ts\"", "prepublishOnly": "ts-node scripts/pre-publish", "mocha": "mocha -r ts-node/register test/*.ts", "dtslint": "dtslint dtslint", "docs": "docs-ts", "prerelease": "npm run build", "release": "ts-node scripts/release", "dpdm": "dpdm --warning=false --tree=false --exit-code circular:1 -T src/index.ts", "vitest": "vitest run", "coverage": "vitest run --coverage" }, "repository": { "type": "git", "url": "https://github.com/gcanti/fp-ts.git" }, "author": "Giulio Canti ", "license": "MIT", "bugs": { "url": "https://github.com/gcanti/fp-ts/issues" }, "homepage": "https://github.com/gcanti/fp-ts", "devDependencies": { "@effect/dtslint": "^0.1.0", "@effect/language-service": "^0.0.19", "@types/benchmark": "^1.0.31", "@types/chai": "^3.5.2", "@types/glob": "^7.1.3", "@types/node": "^20.14.10", "@typescript-eslint/eslint-plugin": "^5.59.0", "@typescript-eslint/parser": "^5.59.0", "@vitest/coverage-istanbul": "^1.6.0", "benchmark": "2.1.4", "docs-ts": "^0.8.0", "eslint": "^8.38.0", "eslint-plugin-deprecation": "^1.4.1", "eslint-plugin-import": "^2.27.5", "eslint-plugin-simple-import-sort": "^10.0.0", "fast-check": "^3.1.3", "glob": "^7.1.6", "mocha": "^5.2.0", "prettier": "^2.7.1", "rimraf": "2.6.2", "ts-node": "^8.0.2", "tslint": "5.11.0", "typescript": "^5.5.2", "vitest": "^1.6.0" }, "tags": [ "typescript", "algebraic-data-types", "functional-programming" ], "keywords": [ "typescript", "algebraic-data-types", "functional-programming" ] } ================================================ FILE: perf/Either/sequenceArray.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/Either' import { pipe } from '../../src/function' /* A.sequence(_.Applicative) x 993 ops/sec ±0.39% (88 runs sampled) _.sequenceArray x 164,033 ops/sec ±3.53% (87 runs sampled) Fastest is _.sequenceArray */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000), RNEA.map(_.of)) suite .add('A.sequence(_.Applicative)', function () { pipe(as, RNEA.sequence(_.Applicative)) }) .add('_.sequenceArray', function () { // tslint:disable-next-line: deprecation pipe(as, _.sequenceArray) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/IO/sequenceArray.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/IO' import { pipe } from '../../src/function' /* A.sequence(_.Applicative) x 17,253 ops/sec ±0.28% (88 runs sampled) _.sequenceArray x 21,475,613 ops/sec ±1.19% (88 runs sampled) Fastest is _.sequenceArray */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000), RNEA.map(_.of)) suite .add('A.sequence(_.Applicative)', function () { pipe(as, RNEA.sequence(_.Applicative)) }) .add('_.sequenceArray', function () { // tslint:disable-next-line: deprecation pipe(as, _.sequenceArray) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/Option/sequenceArray.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/Option' import { pipe } from '../../src/function' /* A.sequence(_.Applicative) x 261 ops/sec ±9.68% (60 runs sampled) _.sequenceArray x 58,110 ops/sec ±7.58% (71 runs sampled) Fastest is _.sequenceArray */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000), RNEA.map(_.of)) suite .add('A.sequence(_.Applicative)', function () { return pipe(as, RNEA.sequence(_.Applicative)) }) .add('_.sequenceArray', function () { // tslint:disable-next-line: deprecation return pipe(as, _.sequenceArray) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/ReaderTask/traverseReadonlyArrayWithIndexSeq.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/ReaderTask' import { pipe } from '../../src/function' /* A.traverseWithIndex(_.ApplicativeSeq) x 247 ops/sec ±4.98% (36 runs sampled) _.traverseSeqArrayWithIndex x 1,901 ops/sec ±10.34% (66 runs sampled) Fastest is _.traverseSeqArrayWithIndex */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000)) suite .add('A.traverseWithIndex(_.ApplicativeSeq)', function () { return pipe( as, RNEA.traverseWithIndex(_.ApplicativeSeq)((_i, a) => _.of(a)) )(undefined)() }) .add('_.traverseReadonlyArrayWithIndexSeq', function () { return pipe( as, _.traverseReadonlyArrayWithIndexSeq((_i, a) => _.of(a)) )(undefined)() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/ReaderTaskEither/traverseReadonlyArrayWithIndexSeq.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/ReaderTaskEither' import { pipe } from '../../src/function' /* A.traverseWithIndex(_.ApplicativeSeq) x 200 ops/sec ±6.32% (44 runs sampled) _.traverseSeqArrayWithIndex x 4,132 ops/sec ±8.65% (67 runs sampled) Fastest is _.traverseSeqArrayWithIndex */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000)) suite .add('A.traverseWithIndex(_.ApplicativeSeq)', function () { return pipe( as, RNEA.traverseWithIndex(_.ApplicativeSeq)((_i, a) => _.of(a)) )(undefined)() }) .add('_.traverseReadonlyArrayWithIndexSeq', function () { return pipe( as, _.traverseReadonlyArrayWithIndexSeq((_i, a) => _.of(a)) )(undefined)() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/ReadonlyNonEmptyArray.ts/reverse.ts ================================================ import * as Benchmark from 'benchmark' import * as _ from '../../src/ReadonlyNonEmptyArray' /* snoc x 11,443,076 ops/sec ±1.78% (85 runs sampled) snoc2 x 40,554,861 ops/sec ±1.52% (84 runs sampled) */ const suite = new Benchmark.Suite() export const reverse2 = (as: _.ReadonlyNonEmptyArray): _.ReadonlyNonEmptyArray => as.slice().reverse() as any suite .add('reverse', function () { _.reverse([1, 2, 3, 4]) }) .add('reverse2', function () { reverse2([1, 2, 3, 4]) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/StateReaderTaskEither/sequenceArray.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/StateReaderTaskEither' import { pipe } from '../../src/function' /* A.sequence(_.Applicative) x 5,930 ops/sec ±0.39% (90 runs sampled) _.sequenceArray x 21,057,757 ops/sec ±0.84% (88 runs sampled) Fastest is _.sequenceArray */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000), RNEA.map(_.of)) suite .add('A.sequence(_.Applicative)', function () { pipe(as, RNEA.sequence(_.Applicative)) }) .add('_.sequenceArray', function () { // tslint:disable-next-line: deprecation pipe(as, _.sequenceArray) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/Task/sequenceArray.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/Task' import { pipe } from '../../src/function' /* A.sequence(_.ApplicativePar) x 390 ops/sec ±13.15% (44 runs sampled) _.sequenceArray x 3,460 ops/sec ±7.30% (57 runs sampled) Fastest is _.sequenceArray */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000), RNEA.map(_.of)) suite .add('A.sequence(_.ApplicativePar)', function () { return pipe(as, RNEA.sequence(_.ApplicativePar))() }) .add('_.sequenceArray', function () { // tslint:disable-next-line: deprecation return pipe(as, _.sequenceArray)() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/Task/stack.ts ================================================ import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/Task' import { pipe } from '../../src/function' const as = RNEA.range(0, 100000) // tslint:disable-next-line: no-floating-promises pipe( as, // tslint:disable-next-line: deprecation _.traverseSeqArrayWithIndex((_i, a) => _.of(a)) // tslint:disable-next-line: no-console )().then((as) => console.log(as.length)) ================================================ FILE: perf/Task/traverseReadonlyArrayWithIndexSeq.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/Task' import { pipe } from '../../src/function' /* A.traverseWithIndex(_.ApplicativeSeq) x 310 ops/sec ±10.89% (31 runs sampled) _.traverseSeqArrayWithIndex x 1,324 ops/sec ±6.92% (20 runs sampled) Fastest is _.traverseSeqArrayWithIndex */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000)) suite .add('A.traverseWithIndex(_.ApplicativeSeq)', function () { return pipe( as, RNEA.traverseWithIndex(_.ApplicativeSeq)((_i, a) => _.of(a)) )() }) .add('_.traverseReadonlyArrayWithIndexSeq', function () { return pipe( as, _.traverseReadonlyArrayWithIndexSeq((_i, a) => _.of(a)) )() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/TaskEither/traverseReadonlyArrayWithIndexSeq.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/TaskEither' import { pipe } from '../../src/function' /* A.traverseWithIndex(_.ApplicativeSeq) x 309 ops/sec ±8.49% (67 runs sampled) _.traverseSeqArrayWithIndex x 1,502 ops/sec ±4.20% (20 runs sampled) Fastest is _.traverseSeqArrayWithIndex */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000)) suite .add('A.traverseWithIndex(_.ApplicativeSeq)', function () { return pipe( as, RNEA.traverseWithIndex(_.ApplicativeSeq)((_i, a) => _.of(a)) )() }) .add('_.traverseReadonlyArrayWithIndexSeq', function () { return pipe( as, _.traverseReadonlyArrayWithIndexSeq((_i, a) => _.of(a)) )() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/TaskOption/traverseReadonlyArrayWithIndexSeq.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/TaskOption' import { pipe } from '../../src/function' /* A.traverseWithIndex(_.ApplicativeSeq) x 309 ops/sec ±8.49% (67 runs sampled) _.traverseSeqArrayWithIndex x 1,502 ops/sec ±4.20% (20 runs sampled) Fastest is _.traverseSeqArrayWithIndex */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000)) suite .add('A.traverseWithIndex(_.ApplicativeSeq)', function () { return pipe( as, RNEA.traverseWithIndex(_.ApplicativeSeq)((_i, a) => _.of(a)) )() }) .add('_.traverseReadonlyArrayWithIndexSeq', function () { return pipe( as, _.traverseReadonlyArrayWithIndexSeq((_i, a) => _.of(a)) )() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/TaskOption.ts/traverseReadonlyArrayWithIndexSeq.ts ================================================ import * as Benchmark from 'benchmark' import * as RNEA from '../../src/ReadonlyNonEmptyArray' import * as _ from '../../src/TaskOption' import { pipe } from '../../src/function' /* A.traverseWithIndex(_.ApplicativeSeq) x 309 ops/sec ±8.49% (67 runs sampled) _.traverseSeqArrayWithIndex x 1,502 ops/sec ±4.20% (20 runs sampled) Fastest is _.traverseSeqArrayWithIndex */ const suite = new Benchmark.Suite() const as = pipe(RNEA.range(0, 1000)) suite .add('A.traverseWithIndex(_.ApplicativeSeq)', function () { return pipe( as, RNEA.traverseWithIndex(_.ApplicativeSeq)((_i, a) => _.of(a)) )() }) .add('_.traverseReadonlyArrayWithIndexSeq', function () { return pipe( as, _.traverseReadonlyArrayWithIndexSeq((_i, a) => _.of(a)) )() }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/function/flow.ts ================================================ import * as Benchmark from 'benchmark' import { flow } from '../../src/function' const suite = new Benchmark.Suite() export function flow2(...fns: ReadonlyArray): Function { const len = fns.length return function (this: any, ...x: ReadonlyArray) { let y = fns[0].apply(this, x) for (let i = 1; i < len; i++) { y = fns[i].call(this, y) } return y } } const f = (n: number) => n + 1 const g = (n: number) => n * 2 suite .add('flow2', function (this: unknown) { flow2(f, g, f, g, f, g, f, g, f)(2) }) .add('flow', function (this: unknown) { flow(f, g, f, g, f, g, f, g, f)(2) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: perf/function/pipe.ts ================================================ import * as Benchmark from 'benchmark' import { pipe } from '../../src/function' const suite = new Benchmark.Suite() export function pipe2(a: unknown, ...fns: ReadonlyArray): unknown { let out: unknown = a for (let i = 0; i < fns.length; i++) { out = fns[i](out) } return out } const f = (n: number) => n + 1 const g = (n: number) => n * 2 suite .add('pipe2', function (this: unknown) { pipe2(2, f, g, f, g, f, g, f, g, f) }) .add('pipe', function (this: unknown) { pipe(2, f, g, f, g, f, g, f, g, f) }) .on('cycle', function (event: any) { // tslint:disable-next-line: no-console console.log(String(event.target)) }) .on('complete', function (this: any) { // tslint:disable-next-line: no-console console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({ async: true }) ================================================ FILE: scripts/FileSystem.ts ================================================ import * as fs from 'fs' import G from 'glob' import { flow } from '../src/function' import * as TE from '../src/TaskEither' export interface FileSystem { readonly readFile: (path: string) => TE.TaskEither readonly writeFile: (path: string, content: string) => TE.TaskEither readonly copyFile: (from: string, to: string) => TE.TaskEither readonly glob: (pattern: string) => TE.TaskEither> readonly mkdir: (path: string) => TE.TaskEither readonly moveFile: (from: string, to: string) => TE.TaskEither } const readFile = TE.taskify(fs.readFile) const writeFile = TE.taskify(fs.writeFile) const copyFile = TE.taskify(fs.copyFile) const glob = TE.taskify>(G) const mkdirTE = TE.taskify(fs.mkdir) const moveFile = TE.taskify(fs.rename) export const fileSystem: FileSystem = { readFile: (path) => readFile(path, { encoding: 'utf8' }), writeFile, copyFile, glob, mkdir: flow( mkdirTE, TE.map(() => undefined) ), moveFile } ================================================ FILE: scripts/build.ts ================================================ import * as path from 'path' import * as E from '../src/Either' import { pipe } from '../src/function' import * as J from '../src/Json' import * as RTE from '../src/ReaderTaskEither' import * as TE from '../src/TaskEither' import { FileSystem, fileSystem } from './FileSystem' import { run } from './run' interface Build extends RTE.ReaderTaskEither {} const OUTPUT_FOLDER = 'dist' const PKG = 'package.json' export const copyPackageJson: Build = (C) => pipe( C.readFile(PKG), TE.flatMap((s) => TE.fromEither(pipe(J.parse(s), E.mapLeft(E.toError)))), TE.map((json) => { const clone = Object.assign({}, json as any) delete clone.scripts delete clone.files delete clone.devDependencies return clone }), TE.flatMap((json) => C.writeFile(path.join(OUTPUT_FOLDER, PKG), JSON.stringify(json, null, 2))) ) export const FILES: ReadonlyArray = ['CHANGELOG.md', 'LICENSE', 'README.md'] export const copyFiles: Build> = (C) => pipe( FILES, TE.traverseReadonlyArrayWithIndex((_, from) => C.copyFile(from, path.resolve(OUTPUT_FOLDER, from))) ) export const makeModules: Build = (C) => { const makeSingleModuleC = makeSingleModule(C) return pipe( C.glob(`${OUTPUT_FOLDER}/lib/*.js`), TE.map(getModules), TE.flatMap(TE.traverseReadonlyArrayWithIndex((_, a) => makeSingleModuleC(a))), TE.map(() => undefined) ) } function getModules(paths: ReadonlyArray): ReadonlyArray { return paths.map((filePath) => path.basename(filePath, '.js')).filter((x) => x !== 'index') } function makeSingleModule(C: FileSystem): (module: string) => TE.TaskEither { return (m) => pipe( C.mkdir(path.join(OUTPUT_FOLDER, m)), TE.flatMap(() => makePkgJson(m)), TE.flatMap((data) => C.writeFile(path.join(OUTPUT_FOLDER, m, 'package.json'), data)) ) } function makePkgJson(module: string): TE.TaskEither { return pipe( JSON.stringify( { main: `../lib/${module}.js`, module: `../es6/${module}.js`, typings: module === 'HKT' ? `../HKT.d.ts` : `../lib/${module}.d.ts`, sideEffects: false }, null, 2 ), TE.right ) } const fixHKT = (folder: string): Build => pipe( (C: FileSystem) => C.mkdir(path.join(OUTPUT_FOLDER, folder, 'HKT')), RTE.flatMap( (): Build => (C) => C.writeFile( path.join(OUTPUT_FOLDER, folder, 'HKT', 'package.json'), JSON.stringify({ typings: '../../HKT.d.ts' }, null, 2) ) ), RTE.flatMap( (): Build => (C) => C.moveFile(path.join(OUTPUT_FOLDER, folder, 'HKT.js'), path.join(OUTPUT_FOLDER, folder, 'HKT', 'index.js')) ), RTE.flatMap( (): Build => (C) => C.moveFile(path.join(OUTPUT_FOLDER, folder, 'HKT.d.ts'), path.join(OUTPUT_FOLDER, 'HKT.d.ts')) ) ) const main: Build = pipe( copyPackageJson, RTE.flatMap(() => copyFiles), RTE.flatMap(() => makeModules), RTE.flatMap(() => fixHKT('es6')), RTE.flatMap(() => fixHKT('lib')) ) run( main({ ...fileSystem }) ) ================================================ FILE: scripts/linter.ts ================================================ import * as glob from 'glob' import * as path from 'path' import * as ast from 'ts-morph' import { pipe } from '../src/function' import * as M from '../src/Monoid' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as string from '../src/string' // ------------------------------------------------------------------------------------- // domain // ------------------------------------------------------------------------------------- export interface Overloadings { readonly _tag: 'Overloadings' readonly signatures: ReadonlyArray } export interface TypeParameter { readonly name: string readonly constraint: O.Option } export interface Parameter { readonly name: string readonly type: Type } export interface Signature { readonly _tag: 'Signature' readonly typeParameters: ReadonlyArray readonly parameters: ReadonlyArray readonly returnType: Type } export interface TypeReference { readonly _tag: 'TypeReference' readonly name: string readonly typeArguments: ReadonlyArray } export interface InferType { readonly _tag: 'InferType' readonly typeParameter: Type } export interface Token { readonly _tag: 'Token' } export interface TypeOperator { readonly _tag: 'TypeOperator' readonly type: Type } export interface MappedType { readonly _tag: 'MappedType' readonly typeParameter: Type readonly type: O.Option } export interface UnionType { readonly _tag: 'UnionType' readonly members: ReadonlyArray } export interface TypeParameterDeclaration { readonly _tag: 'TypeParameterDeclaration' readonly name: string readonly constraint: O.Option } export interface ConditionalType { readonly _tag: 'ConditionalType' readonly checkType: Type readonly extendsType: Type readonly trueType: Type readonly falseType: Type } export interface IndexedAccessType { readonly _tag: 'IndexedAccessType' readonly objectType: Type readonly indexType: Type } export interface TupleType { readonly _tag: 'TupleType' readonly elements: ReadonlyArray } export interface RestType { readonly _tag: 'RestType' readonly type: Type } export interface LiteralType { readonly _tag: 'LiteralType' } export interface IntersectionType { readonly _tag: 'IntersectionType' readonly members: ReadonlyArray } export type Type = | Signature | Overloadings | TypeReference | Token | TypeOperator | MappedType | TypeParameterDeclaration | UnionType | ConditionalType | IndexedAccessType | TupleType | RestType | LiteralType | IntersectionType | InferType export interface FunctionDeclaration { readonly name: string readonly overloadings: ReadonlyArray } export interface File { readonly name: string readonly functions: ReadonlyArray } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- export const signature = (input: { readonly typeParameters: ReadonlyArray readonly parameters: ReadonlyArray readonly returnType: Type }): Signature => ({ _tag: 'Signature', typeParameters: input.typeParameters, parameters: input.parameters, returnType: input.returnType }) // ------------------------------------------------------------------------------------- // parsers // ------------------------------------------------------------------------------------- const ensureReadonlyArray = (as: ReadonlyArray | undefined): ReadonlyArray => (as ? as : RA.empty) export function parseType( node: ast.ts.TypeNode | ast.ts.TypeParameterDeclaration | ast.ts.CallSignatureDeclaration ): Type { if (ast.ts.isTypeReferenceNode(node)) { return { _tag: 'TypeReference', name: node.typeName.getText(), typeArguments: pipe(node.typeArguments, ensureReadonlyArray, RA.map(parseType)) } } if (ast.ts.isFunctionTypeNode(node) || ast.ts.isCallSignatureDeclaration(node)) { if (node.type === undefined) { throw new Error(`(parseType) not sure what to do with ${node.getText()}`) } return signature({ typeParameters: pipe(node.typeParameters, ensureReadonlyArray, RA.map(parseTypeParameter)), parameters: pipe(node.parameters, RA.map(parseParameterDeclaration)), returnType: parseType(node.type) }) } if (ast.ts.isToken(node)) { return { _tag: 'Token' } } if (ast.ts.isTypeOperatorNode(node)) { return { _tag: 'TypeOperator', type: parseType(node.type) } } if (ast.ts.isMappedTypeNode(node)) { return { _tag: 'MappedType', typeParameter: parseType(node.typeParameter), type: pipe(node.type, O.fromNullable, O.map(parseType)) } } if (ast.ts.isUnionTypeNode(node)) { return { _tag: 'UnionType', members: pipe(node.types, RA.map(parseType)) } } if (ast.ts.isTypeParameterDeclaration(node)) { return { _tag: 'TypeParameterDeclaration', name: node.name.getText(), constraint: pipe(node.constraint, O.fromNullable, O.map(parseType)) } } if (ast.ts.isConditionalTypeNode(node)) { return { _tag: 'ConditionalType', checkType: parseType(node.checkType), extendsType: parseType(node.extendsType), trueType: parseType(node.trueType), falseType: parseType(node.falseType) } } if (ast.ts.isIndexedAccessTypeNode(node)) { return { _tag: 'IndexedAccessType', objectType: parseType(node.objectType), indexType: parseType(node.indexType) } } if (ast.ts.isTupleTypeNode(node)) { return { _tag: 'TupleType', elements: pipe(node.elements, RA.map(parseType)) } } if (ast.ts.isRestTypeNode(node)) { return { _tag: 'RestType', type: parseType(node.type) } } if (ast.ts.isLiteralTypeNode(node)) { return { _tag: 'LiteralType' } } if (ast.ts.isTypeLiteralNode(node)) { const members = node.members.filter(ast.ts.isCallSignatureDeclaration) const signatures = pipe(members, RA.map(parseType)) as ReadonlyArray return { _tag: 'Overloadings', signatures } } if (ast.ts.isNamedTupleMember(node)) { return parseType(node.type) } if (ast.ts.isTypePredicateNode(node)) { if (node.type === undefined) { throw new Error(`(parseType) not sure what to do with ${node.getText()}`) } return parseType(node.type) } if (ast.ts.isIntersectionTypeNode(node)) { return { _tag: 'IntersectionType', members: pipe(node.types, RA.map(parseType)) } } if (ast.ts.isParenthesizedTypeNode(node)) { return parseType(node.type) } if (ast.ts.isInferTypeNode(node)) { return { _tag: 'InferType', typeParameter: parseType(node.typeParameter) } } throw new Error(`(parseType) not sure what to do with ${node.getText()}`) } export const parseTypeParameter = (tp: ast.ts.TypeParameterDeclaration): TypeParameter => { return { name: tp.name.getText(), constraint: pipe(tp.constraint, O.fromNullable, O.map(parseType)) } } export const parseParameterDeclaration = (pd: ast.ts.ParameterDeclaration): Parameter => { if (pd.type === undefined) { throw new Error(`(parseParameterDeclaration) not sure what to do with ${pd.getText()} in ${pd.parent.getText()}`) } return { name: pd.name.getText(), type: parseType(pd.type) } } export const parseSignature = ( node: ast.ts.FunctionDeclaration | ast.ts.CallSignatureDeclaration | ast.ts.FunctionTypeNode ): Signature => { if (node.type === undefined) { throw new Error(`(parseSignature) not sure what to do with ${node.getText()}`) } return signature({ typeParameters: pipe(node.typeParameters, ensureReadonlyArray, RA.map(parseTypeParameter)), parameters: pipe(node.parameters, RA.map(parseParameterDeclaration)), returnType: parseType(node.type) }) } export const parseFunctionDeclaration = (fd: ast.FunctionDeclaration): FunctionDeclaration => { const name = fd.getName()! return { name, overloadings: pipe( [...fd.getOverloads(), fd], RA.map((fd) => parseSignature(fd.compilerNode)) ) } } export const parseInterface = (i: ast.InterfaceDeclaration): ReadonlyArray => { const name = i.getName() const members = i.compilerNode.members // CallSignatureDeclaration const csds = pipe(members, RA.filter(ast.ts.isCallSignatureDeclaration), RA.map(parseSignature)) const csdsfd = pipe( csds, RA.match, Signature>( () => RA.empty, (signatures) => [{ name, overloadings: signatures }] ) ) // PropertySignature const pss: ReadonlyArray = pipe( members, RA.filter(ast.ts.isPropertySignature), RA.filterMap((ps) => { const type = parseType(ps.type!) switch (type._tag) { case 'Overloadings': return O.some({ name: `${name}/${ps.name.getText()}`, overloadings: type.signatures }) case 'Signature': return O.some({ name: `${name}/${ps.name.getText()}`, overloadings: [type] }) case 'TypeReference': case 'LiteralType': case 'Token': return O.none } throw new Error(`(parseInterface (interface: ${name})) not sure what to do with ${type._tag}`) }) ) return pipe(csdsfd, RA.concat(pss)) } export const parseArrowFunction = (node: ast.ts.ArrowFunction): ReadonlyArray => { return pipe( node.type, O.fromNullable, O.match( () => { // example: export const makeBy = (f: (i: number) => A) => (n: number): ReadonlyArray => (n <= 0 ? empty : RNEA.makeBy(f)(n)) const body = node.body if (ast.ts.isArrowFunction(body)) { return pipe( parseArrowFunction(body), RA.map((returnType) => { return signature({ typeParameters: pipe(node.typeParameters, ensureReadonlyArray, RA.map(parseTypeParameter)), parameters: pipe(node.parameters, RA.map(parseParameterDeclaration)), returnType }) }) ) } throw new Error(`(parseArrowFunction not sure what to do with ${body.getText()}`) }, (returnType) => { // example: export const replicate = (a: A): ((n: number) => ReadonlyArray) => makeBy(() => a) return [ signature({ typeParameters: pipe(node.typeParameters, ensureReadonlyArray, RA.map(parseTypeParameter)), parameters: pipe(node.parameters, RA.map(parseParameterDeclaration)), returnType: parseType(returnType) }) ] } ) ) } export const parseVariableDeclaration = (vd: ast.VariableDeclaration): ReadonlyArray => { const compilerNode = vd.compilerNode const type = compilerNode.type const name = compilerNode.name.getText() const initializer = compilerNode.initializer if (initializer === undefined) { return RA.empty } if (type !== undefined) { if (ast.ts.isTypeReferenceNode(type)) { // example: export const fromOption: NaturalTransformation11 = (ma) => (_.isNone(ma) ? empty : [ma.value]) return RA.empty } if (ast.ts.isIndexedAccessTypeNode(type)) { // example: export const fromEither: FromEither1['fromEither'] = (e) => (_.isLeft(e) ? empty : [e.right]) return RA.empty } if (ast.ts.isFunctionTypeNode(type)) { // example: export const zip: (bs: ReadonlyArray) => (as: ReadonlyArray) => ReadonlyArray = (bs) => zipWith(bs, (a, b) => [a, b]) return [{ name, overloadings: [parseSignature(type)] }] } if (ast.ts.isTypeLiteralNode(type)) { const members = type.members.filter(ast.ts.isCallSignatureDeclaration) const overloadings = pipe(members, RA.map(parseType)) as ReadonlyArray return [{ name, overloadings }] } if (ast.ts.isIntersectionTypeNode(type)) { return RA.empty } if (ast.ts.isTypeOperatorNode(type)) { return RA.empty } if (ast.ts.isTypeQueryNode(type)) { return RA.empty } throw new Error(`(parseVariableDeclaration) not sure what to do with ${vd.getFullText()}`) } if (ast.ts.isArrowFunction(initializer)) { return [{ name, overloadings: parseArrowFunction(initializer) }] } return RA.empty } export const parseFile = (src: ast.SourceFile): File => { const name = path.basename(src.getFilePath()) const functions = pipe( src.getFunctions(), RA.filter((fd) => fd.isExported()), RA.map(parseFunctionDeclaration), RA.concat(pipe(src.getInterfaces(), RA.flatMap(parseInterface))), RA.concat( pipe( src.getVariableDeclarations(), RA.filter((vd) => vd.isExported()), RA.flatMap(parseVariableDeclaration) ) ) ) return { name, functions } } // ------------------------------------------------------------------------------------- // linters // ------------------------------------------------------------------------------------- export interface Lint { readonly path: string readonly typeParameters: ReadonlyArray readonly typeArguments: ReadonlyArray } export const lint = ( path: string, typeParameters: ReadonlyArray, typeArguments: ReadonlyArray ): Lint => ({ path, typeParameters, typeArguments }) const LintMonoid: M.Monoid = M.struct({ path: string.Monoid, typeParameters: RA.getMonoid(), typeArguments: RA.getMonoid() }) export const append = (bs: ReadonlyArray) => (a: Lint): ReadonlyArray => { return pipe( bs, RA.match( () => [a], RA.map((b) => LintMonoid.concat(a, b)) ) ) } export const getTypeParameters = (type: Type): ReadonlyArray => { switch (type._tag) { case 'TypeReference': return RA.empty } throw new Error(`(getTypeParameters) not sure what to do with ${type._tag}`) } export const getTypeArguments = (type: Type): ReadonlyArray => { switch (type._tag) { case 'TypeReference': return pipe( type.typeArguments, RA.match( () => [type.name], (types) => pipe([type.name], RA.concat(pipe(types, RA.flatMap(getTypeArguments)))) ) ) case 'Signature': { const typeParameters = pipe( type.typeParameters, RA.flatMap((tp) => pipe( tp.constraint, O.map((t) => pipe(getTypeArguments(t), RA.prepend(tp.name))), O.getOrElse>(() => [tp.name]) ) ) ) const typeArguments = pipe( type.parameters, RA.flatMap((p) => getTypeArguments(p.type)) ) return pipe(typeParameters, RA.concat(typeArguments), RA.concat(getTypeArguments(type.returnType))) } case 'TypeOperator': case 'RestType': return getTypeArguments(type.type) case 'MappedType': return pipe( type.type, O.map(getTypeArguments), O.getOrElse>(() => RA.empty) ) case 'ConditionalType': return pipe( getTypeArguments(type.checkType), RA.concat(getTypeArguments(type.extendsType)), RA.concat(getTypeArguments(type.trueType)), RA.concat(getTypeArguments(type.falseType)) ) case 'IndexedAccessType': return pipe(getTypeArguments(type.objectType), RA.concat(getTypeArguments(type.indexType))) case 'TupleType': return pipe(type.elements, RA.flatMap(getTypeArguments)) case 'LiteralType': case 'Token': return RA.empty case 'UnionType': case 'IntersectionType': return pipe(type.members, RA.flatMap(getTypeArguments)) case 'Overloadings': return pipe(type.signatures, RA.flatMap(getTypeArguments)) case 'InferType': return getTypeArguments(type.typeParameter) case 'TypeParameterDeclaration': return pipe( type.constraint, O.map(getTypeArguments), O.getOrElse>(() => RA.empty) ) } // throw new Error(`(getTypeArguments) not sure what to do with ${type._tag}`) } export const lintType = (type: Type, path: string = string.empty): ReadonlyArray => { switch (type._tag) { case 'TypeReference': return [pipe(lint(path, getTypeParameters(type), getTypeArguments(type)))] case 'Signature': return lintSignature(path, type) case 'Overloadings': return pipe( type.signatures, RA.flatMap((t, i) => lintType(t, `/${String(i)}`)) ) case 'TypeOperator': return lintType(type.type, path) case 'TupleType': return pipe( type.elements, RA.flatMap((t) => lintType(t, path)) ) case 'IndexedAccessType': return pipe(lintType(type.objectType, path), RA.concat(lintType(type.indexType, path))) case 'LiteralType': case 'Token': return RA.empty case 'UnionType': case 'IntersectionType': return pipe( type.members, RA.flatMap((t) => lintType(t, path)) ) case 'ConditionalType': return pipe( lintType(type.checkType), RA.concat(lintType(type.extendsType)), RA.concat(lintType(type.trueType)), RA.concat(lintType(type.falseType)) ) case 'MappedType': return pipe( type.type, O.map(lintType), O.getOrElse>(() => RA.empty) ) } throw new Error(`(lintType) not sure what to do with ${type._tag}`) } export const lintSignature = (path: string, s: Signature): ReadonlyArray => { return pipe( lint( path, pipe( s.typeParameters, RA.map((tp) => tp.name) ), pipe( s.parameters, RA.flatMap((p) => getTypeArguments(p.type)) ) ), append(lintType(s.returnType)) ) } export const lintFunction = (filename: string, fd: FunctionDeclaration): ReadonlyArray => { return pipe( fd.overloadings, RA.flatMap((s, i) => lintSignature(`${filename}/${fd.name}/${i}`, s)) ) } export const lintFile = (file: File): ReadonlyArray => { const functions = file.functions return pipe( functions, RA.flatMap((f) => lintFunction(file.name, f)) ) } const eq = RA.getEq(string.Eq) const intersection = RA.intersection(string.Eq) const uniq = RA.uniq(string.Eq) export const check = (lints: ReadonlyArray): ReadonlyArray => { return pipe( lints, RA.map((l) => ({ path: l.path, typeParameters: l.typeParameters, typeArguments: pipe(l.typeArguments, intersection(l.typeParameters), uniq) })) ) .filter((l) => !eq.equals(l.typeParameters, l.typeArguments)) .map( (l) => `Type Parameter Order Error in ${l.path}: ${l.typeParameters.join(', ')} !== ${l.typeArguments.join(', ')}` ) } // ------------------------------------------------------------------------------------- // main // ------------------------------------------------------------------------------------- export const compilerOptions: ast.ProjectOptions['compilerOptions'] = { strict: true } export const project = new ast.Project({ compilerOptions }) export const paths = glob.sync('src/**/*.ts') paths.forEach((path) => project.addSourceFileAtPath(path)) const files = pipe(project.getSourceFiles(), RA.map(parseFile)) const checks = pipe( files, RA.flatMap((f) => check(lintFile(f))) ) if (checks.length > 0) { // tslint:disable-next-line: no-console console.log(JSON.stringify(checks, null, 2)) } // project.addSourceFileAtPath('src/Bounded.ts') // export const file = parseFile(project.getSourceFiles()[0]) // console.log(JSON.stringify(check(lintFile(file)), null, 2)) ================================================ FILE: scripts/pre-publish.ts ================================================ import { left } from '../src/TaskEither' import { run } from './run' const main = left(new Error('"npm publish" can not be run from root, run "npm run release" instead')) run(main) ================================================ FILE: scripts/release.ts ================================================ import * as child_process from 'child_process' import { left, right } from '../src/Either' import * as TE from '../src/TaskEither' import { run } from './run' const DIST = 'dist' const exec = (cmd: string, args?: child_process.ExecOptions): TE.TaskEither => () => new Promise((resolve) => { child_process.exec(cmd, args, (err) => { if (err !== null) { return resolve(left(err)) } return resolve(right(undefined)) }) }) export const main = exec('npm publish', { cwd: DIST }) run(main) ================================================ FILE: scripts/run.ts ================================================ import { fold } from '../src/Either' import { TaskEither } from '../src/TaskEither' export function run(eff: TaskEither): void { eff() .then( fold( (e) => { throw e }, (_) => { process.exitCode = 0 } ) ) .catch((e) => { console.error(e) // tslint:disable-line no-console process.exitCode = 1 }) } ================================================ FILE: src/Alt.ts ================================================ /** * The `Alt` type class identifies an associative operation on a type constructor. It is similar to `Semigroup`, except * that it applies to types of kind `* -> *`, like `Array` or `Option`, rather than concrete types like `string` or * `number`. * * `Alt` instances are required to satisfy the following laws: * * 1. Associativity: `A.alt(A.alt(fa, ga), ha) <-> A.alt(fa, A.alt(ga, ha))` * 2. Distributivity: `A.map(A.alt(fa, ga), ab) <-> A.alt(A.map(fa, ab), A.map(ga, ab))` * * @since 2.0.0 */ import { LazyArg } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4 } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Alt extends Functor { readonly alt: (fa: HKT, that: LazyArg>) => HKT } /** * @category model * @since 2.0.0 */ export interface Alt1 extends Functor1 { readonly alt: (fa: Kind, that: LazyArg>) => Kind } /** * @category model * @since 2.0.0 */ export interface Alt2 extends Functor2 { readonly alt: (fa: Kind2, that: LazyArg>) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Alt2C extends Functor2C { readonly alt: (fa: Kind2, that: LazyArg>) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Alt3 extends Functor3 { readonly alt: (fa: Kind3, that: LazyArg>) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Alt3C extends Functor3C { readonly alt: (fa: Kind3, that: LazyArg>) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Alt4 extends Functor4 { readonly alt: (fa: Kind4, that: LazyArg>) => Kind4 } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function altAll( F: Alt4 ): (startWith: Kind4) => (as: ReadonlyArray>) => Kind4 export function altAll( F: Alt3 ): (startWith: Kind3) => (as: ReadonlyArray>) => Kind3 export function altAll( F: Alt3C ): (startWith: Kind3) => (as: ReadonlyArray>) => Kind3 export function altAll( F: Alt2 ): (startWith: Kind2) => (as: ReadonlyArray>) => Kind2 export function altAll( F: Alt2C ): (startWith: Kind2) => (as: ReadonlyArray>) => Kind2 export function altAll( F: Alt1 ): (startWith: Kind) => (as: ReadonlyArray>) => Kind export function altAll(F: Alt): (startWith: HKT) => (as: ReadonlyArray>) => HKT export function altAll(F: Alt): (startWith: HKT) => (as: ReadonlyArray>) => HKT { return (startWith) => (as) => as.reduce((acc, a) => F.alt(acc, () => a), startWith) } ================================================ FILE: src/Alternative.ts ================================================ /** * The `Alternative` type class extends the `Alt` type class with a value that should be the left and right identity for `alt`. * * It is similar to `Monoid`, except that it applies to types of kind `* -> *`, like `Array` or `Option`, rather than * concrete types like `string` or `number`. * * `Alternative` instances should satisfy the following laws: * * 1. Left identity: `A.alt(zero, fa) <-> fa` * 2. Right identity: `A.alt(fa, zero) <-> fa` * 3. Annihilation: `A.map(zero, f) <-> zero` * 4. Distributivity: `A.ap(A.alt(fab, gab), fa) <-> A.alt(A.ap(fab, fa), A.ap(gab, fa))` * 5. Annihilation: `A.ap(zero, fa) <-> zero` * * @since 2.0.0 */ import { Alt, Alt1, Alt2, Alt2C, Alt3, Alt3C, Alt4, altAll as altAll_ } from './Alt' import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C, Applicative4 } from './Applicative' import { getApplySemigroup } from './Apply' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monoid } from './Monoid' import { Semigroup } from './Semigroup' import { Zero, Zero1, Zero2, Zero2C, Zero3, Zero3C, Zero4 } from './Zero' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Alternative extends Applicative, Alt, Zero {} /** * @category model * @since 2.0.0 */ export interface Alternative1 extends Applicative1, Alt1, Zero1 {} /** * @category model * @since 2.0.0 */ export interface Alternative2 extends Applicative2, Alt2, Zero2 {} /** * @category model * @since 2.0.0 */ export interface Alternative2C extends Applicative2C, Alt2C, Zero2C {} /** * @category model * @since 2.0.0 */ export interface Alternative3 extends Applicative3, Alt3, Zero3 {} /** * @category model * @since 2.10.0 */ export interface Alternative3C extends Applicative3C, Alt3C, Zero3C {} /** * @category model * @since 2.10.0 */ export interface Alternative4 extends Applicative4, Alt4, Zero4 {} // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function altAll( F: Alternative4 ): (as: ReadonlyArray>) => Kind4 export function altAll( F: Alternative3 ): (as: ReadonlyArray>) => Kind3 export function altAll( F: Alternative3C ): (as: ReadonlyArray>) => Kind3 export function altAll(F: Alternative2): (as: ReadonlyArray>) => Kind2 export function altAll( F: Alternative2C ): (as: ReadonlyArray>) => Kind2 export function altAll(F: Alternative1): (as: ReadonlyArray>) => Kind export function altAll(F: Alternative): (as: ReadonlyArray>) => HKT export function altAll(F: Alternative): (as: ReadonlyArray>) => HKT { return altAll_(F)(F.zero()) } /** * Lift a semigroup into a monoid alternative 'F', the inner values are concatenated using the provided `Semigroup`. * @since 2.13.0 */ export function getAlternativeMonoid( F: Alternative4 ): (S: Semigroup) => Monoid> export function getAlternativeMonoid( F: Alternative3 ): (S: Semigroup) => Monoid> export function getAlternativeMonoid( F: Alternative3C ): (S: Semigroup) => Monoid> export function getAlternativeMonoid( F: Alternative2 ): (S: Semigroup) => Monoid> export function getAlternativeMonoid( F: Alternative2C ): (S: Semigroup) => Monoid> export function getAlternativeMonoid(F: Alternative1): (S: Semigroup) => Monoid> export function getAlternativeMonoid(F: Alternative): (S: Semigroup) => Monoid> export function getAlternativeMonoid(F: Alternative): (S: Semigroup) => Monoid> { const f = getApplySemigroup(F) return (S: Semigroup) => { const SF = f(S) return { concat: (first: HKT, second: HKT) => F.alt(SF.concat(first, second), () => F.alt(first, () => second)), empty: F.zero() } } } ================================================ FILE: src/Applicative.ts ================================================ /** * The `Applicative` type class extends the `Apply` type class with a `of` function, which can be used to create values * of type `f a` from values of type `a`. * * Where `Apply` provides the ability to lift functions of two or more arguments to functions whose arguments are * wrapped using `f`, and `Functor` provides the ability to lift functions of one argument, `pure` can be seen as the * function which lifts functions of _zero_ arguments. That is, `Applicative` functors support a lifting operation for * any number of function arguments. * * Instances must satisfy the following laws in addition to the `Apply` laws: * * 1. Identity: `A.ap(A.of(a => a), fa) <-> fa` * 2. Homomorphism: `A.ap(A.of(ab), A.of(a)) <-> A.of(ab(a))` * 3. Interchange: `A.ap(fab, A.of(a)) <-> A.ap(A.of(ab => ab(a)), fab)` * * Note. `Functor`'s `map` can be derived: `A.map(x, f) = A.ap(A.of(f), x)` * * @since 2.0.0 */ import { ap, Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C, Apply4, getApplySemigroup } from './Apply' import { pipe } from './function' import { FunctorComposition, FunctorComposition2C1, FunctorComposition11, FunctorComposition12, FunctorComposition12C, FunctorComposition21, FunctorComposition22, FunctorComposition22C, FunctorCompositionHKT1, FunctorCompositionHKT2, FunctorCompositionHKT2C, getFunctorComposition } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monoid } from './Monoid' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C, Pointed4 } from './Pointed' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Applicative extends Apply, Pointed {} /** * @category model * @since 2.0.0 */ export interface Applicative1 extends Apply1, Pointed1 {} /** * @category model * @since 2.0.0 */ export interface Applicative2 extends Apply2, Pointed2 {} /** * @category model * @since 2.0.0 */ export interface Applicative2C extends Apply2C, Pointed2C {} /** * @category model * @since 2.0.0 */ export interface Applicative3 extends Apply3, Pointed3 {} /** * @category model * @since 2.2.0 */ export interface Applicative3C extends Apply3C, Pointed3C {} /** * @category model * @since 2.0.0 */ export interface Applicative4 extends Apply4, Pointed4 {} // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Lift a monoid into 'F', the inner values are concatenated using the provided `Monoid`. * * @since 2.10.0 */ export function getApplicativeMonoid( F: Applicative4 ): (M: Monoid) => Monoid> export function getApplicativeMonoid( F: Applicative3 ): (M: Monoid) => Monoid> export function getApplicativeMonoid( F: Applicative3C ): (M: Monoid) => Monoid> export function getApplicativeMonoid( F: Applicative2 ): (M: Monoid) => Monoid> export function getApplicativeMonoid( F: Applicative2C ): (M: Monoid) => Monoid> export function getApplicativeMonoid(F: Applicative1): (M: Monoid) => Monoid> export function getApplicativeMonoid(F: Applicative): (M: Monoid) => Monoid> export function getApplicativeMonoid(F: Applicative): (M: Monoid) => Monoid> { const f = getApplySemigroup(F) return (M: Monoid) => ({ concat: f(M).concat, empty: F.of(M.empty) }) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition extends FunctorComposition { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeCompositionHKT1 extends FunctorCompositionHKT1 { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeCompositionHKT2 extends FunctorCompositionHKT2 { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeCompositionHKT2C extends FunctorCompositionHKT2C { readonly of: (a: A) => HKT> readonly ap: (fgab: HKT B>>, fga: HKT>) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition11 extends FunctorComposition11 { readonly of: (a: A) => Kind> readonly ap: (fgab: Kind B>>, fga: Kind>) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition12 extends FunctorComposition12 { readonly of: (a: A) => Kind> readonly ap: ( fgab: Kind B>>, fga: Kind> ) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition12C extends FunctorComposition12C { readonly of: (a: A) => Kind> readonly ap: (fgab: Kind B>>, fga: Kind>) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition21 extends FunctorComposition21 { readonly of: (a: A) => Kind2> readonly ap: ( fgab: Kind2 B>>, fga: Kind2> ) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition2C1 extends FunctorComposition2C1 { readonly of: (a: A) => Kind2> readonly ap: (fgab: Kind2 B>>, fga: Kind2>) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition22 extends FunctorComposition22 { readonly of: (a: A) => Kind2> readonly ap: ( fgab: Kind2 B>>, fga: Kind2> ) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ApplicativeComposition22C extends FunctorComposition22C { readonly of: (a: A) => Kind2> readonly ap: ( fgab: Kind2 B>>, fga: Kind2> ) => Kind2> } /** * Use [`ap`](./Apply.ts.html#ap) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getApplicativeComposition( F: Applicative2, G: Applicative2C ): ApplicativeComposition22C /** @deprecated */ export function getApplicativeComposition( F: Applicative2, G: Applicative2 ): ApplicativeComposition22 /** @deprecated */ export function getApplicativeComposition( F: Applicative2, G: Applicative2C ): ApplicativeComposition22C /** @deprecated */ export function getApplicativeComposition( F: Applicative2, G: Applicative1 ): ApplicativeComposition21 /** @deprecated */ export function getApplicativeComposition( F: Applicative1, G: Applicative2 ): ApplicativeComposition12 /** @deprecated */ export function getApplicativeComposition( F: Applicative1, G: Applicative2C ): ApplicativeComposition12C /** @deprecated */ export function getApplicativeComposition( F: Applicative1, G: Applicative1 ): ApplicativeComposition11 /** @deprecated */ export function getApplicativeComposition( F: Applicative, G: Applicative2 ): ApplicativeCompositionHKT2 /** @deprecated */ export function getApplicativeComposition( F: Applicative, G: Applicative2C ): ApplicativeCompositionHKT2C /** @deprecated */ export function getApplicativeComposition( F: Applicative, G: Applicative1 ): ApplicativeCompositionHKT1 /** @deprecated */ export function getApplicativeComposition(F: Applicative, G: Applicative): ApplicativeComposition /** @deprecated */ export function getApplicativeComposition(F: Applicative, G: Applicative): ApplicativeComposition { const map = getFunctorComposition(F, G).map const _ap = ap(F, G) return { map, of: (a) => F.of(G.of(a)), ap: (fgab, fga) => pipe(fgab, _ap(fga)) } } ================================================ FILE: src/Apply.ts ================================================ /** * The `Apply` class provides the `ap` which is used to apply a function to an argument under a type constructor. * * `Apply` can be used to lift functions of two or more arguments to work on values wrapped with the type constructor * `f`. * * Instances must satisfy the following law in addition to the `Functor` laws: * * 1. Associative composition: `F.ap(F.ap(F.map(fbc, bc => ab => a => bc(ab(a))), fab), fa) <-> F.ap(fbc, F.ap(fab, fa))` * * Formally, `Apply` represents a strong lax semi-monoidal endofunctor. * * @example * import * as O from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * const f = (a: string) => (b: number) => (c: boolean) => a + String(b) + String(c) * const fa: O.Option = O.some('s') * const fb: O.Option = O.some(1) * const fc: O.Option = O.some(true) * * assert.deepStrictEqual( * pipe( * // lift a function * O.some(f), * // apply the first argument * O.ap(fa), * // apply the second argument * O.ap(fb), * // apply the third argument * O.ap(fc) * ), * O.some('s1true') * ) * * @since 2.0.0 */ import { tuple } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4 } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import * as _ from './internal' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Apply extends Functor { readonly ap: (fab: HKT B>, fa: HKT) => HKT } /** * @category model * @since 2.0.0 */ export interface Apply1 extends Functor1 { readonly ap: (fab: Kind B>, fa: Kind) => Kind } /** * @category model * @since 2.0.0 */ export interface Apply2 extends Functor2 { readonly ap: (fab: Kind2 B>, fa: Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Apply2C extends Functor2C { readonly ap: (fab: Kind2 B>, fa: Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Apply3 extends Functor3 { readonly ap: (fab: Kind3 B>, fa: Kind3) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Apply3C extends Functor3C { readonly ap: (fab: Kind3 B>, fa: Kind3) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Apply4 extends Functor4 { readonly ap: (fab: Kind4 B>, fa: Kind4) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `ap` composition. * * @since 2.10.0 */ export function ap( F: Apply4, G: Apply4 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply4, G: Apply3 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply4, G: Apply3C ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply4, G: Apply2 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply4, G: Apply2C ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply4, G: Apply1 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply3C, G: Apply4 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C, G: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C, G: Apply3C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C, G: Apply2 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C, G: Apply2C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C, G: Apply1 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3, G: Apply4 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3, G: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3, G: Apply3C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3, G: Apply2 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3, G: Apply2C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3, G: Apply1 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply2C, G: Apply4 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C, G: Apply3 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C, G: Apply3C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C, G: Apply2 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C, G: Apply2C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C, G: Apply1 ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2, G: Apply4 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2, G: Apply3 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2, G: Apply3C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2, G: Apply2 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2, G: Apply2C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2, G: Apply1 ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply1, G: Apply4 ): ( fa: Kind> ) => (fab: Kind B>>) => Kind> export function ap( F: Apply1, G: Apply3 ): ( fa: Kind> ) => (fab: Kind B>>) => Kind> export function ap( F: Apply1, G: Apply3C ): ( fa: Kind> ) => (fab: Kind B>>) => Kind> export function ap( F: Apply1, G: Apply2 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export function ap( F: Apply1, G: Apply2C ): (fa: Kind>) => (fab: Kind B>>) => Kind> export function ap( F: Apply1, G: Apply1 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export function ap( F: Apply, G: Apply4 ): ( fa: HKT> ) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply3 ): ( fa: HKT> ) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply3C ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply2 ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply2C ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply1 ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply, G: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> { return (fa: HKT>) => (fab: HKT B>>): HKT> => F.ap( F.map(fab, (gab) => (ga: HKT) => G.ap(gab, ga)), fa ) } /** * @since 2.10.0 */ export function apFirst( A: Apply4 ): (second: Kind4) => (first: Kind4) => Kind4 export function apFirst( A: Apply3 ): (second: Kind3) => (first: Kind3) => Kind3 export function apFirst( A: Apply3C ): (second: Kind3) => (first: Kind3) => Kind3 export function apFirst( A: Apply2 ): (second: Kind2) => (first: Kind2) => Kind2 export function apFirst( A: Apply2C ): (second: Kind2) => (first: Kind2) => Kind2 export function apFirst(A: Apply1): (second: Kind) => (first: Kind) => Kind export function apFirst(A: Apply): (second: HKT) => (first: HKT) => HKT export function apFirst(A: Apply): (second: HKT) => (first: HKT) => HKT { return (second) => (first) => A.ap( A.map(first, (a) => () => a), second ) } /** * @since 2.10.0 */ export function apSecond( A: Apply4 ): (second: Kind4) => (first: Kind4) => Kind4 export function apSecond( A: Apply3 ): (second: Kind3) => (first: Kind3) => Kind3 export function apSecond( A: Apply3C ): (second: Kind3) => (first: Kind3) => Kind3 export function apSecond( A: Apply2 ): (second: Kind2) => (first: Kind2) => Kind2 export function apSecond( A: Apply2C ): (second: Kind2) => (first: Kind2) => Kind2 export function apSecond(A: Apply1): (second: Kind) => (first: Kind) => Kind export function apSecond(A: Apply): (second: HKT) => (first: HKT) => HKT export function apSecond(A: Apply): (second: HKT) => (first: HKT) => HKT { return (second: HKT) => (first) => A.ap( A.map(first, () => (b: B) => b), second ) } /** * @since 2.10.0 */ export function apS( F: Apply4 ): ( name: Exclude, fb: Kind4 ) => (fa: Kind4) => Kind4 export function apS( F: Apply3 ): ( name: Exclude, fb: Kind3 ) => (fa: Kind3) => Kind3 export function apS( F: Apply3C ): ( name: Exclude, fb: Kind3 ) => (fa: Kind3) => Kind3 export function apS( F: Apply2 ): ( name: Exclude, fb: Kind2 ) => (fa: Kind2) => Kind2 export function apS( F: Apply2C ): ( name: Exclude, fb: Kind2 ) => (fa: Kind2) => Kind2 export function apS( F: Apply1 ): ( name: Exclude, fb: Kind ) => (fa: Kind) => Kind export function apS( F: Apply ): ( name: Exclude, fb: HKT ) => (fa: HKT) => HKT export function apS( F: Apply ): ( name: Exclude, fb: HKT ) => (fa: HKT) => HKT { return (name: string, fb: HKT) => (fa) => F.ap( F.map(fa, (a) => (b: B) => Object.assign({}, a, { [name]: b }) as any), fb ) } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Lift a semigroup into 'F', the inner values are concatenated using the provided `Semigroup`. * * @since 2.10.0 */ export function getApplySemigroup( F: Apply4 ): (S: Semigroup) => Semigroup> export function getApplySemigroup( F: Apply3 ): (S: Semigroup) => Semigroup> export function getApplySemigroup( F: Apply3C ): (S: Semigroup) => Semigroup> export function getApplySemigroup(F: Apply2): (S: Semigroup) => Semigroup> export function getApplySemigroup( F: Apply2C ): (S: Semigroup) => Semigroup> export function getApplySemigroup(F: Apply1): (S: Semigroup) => Semigroup> export function getApplySemigroup(F: Apply): (S: Semigroup) => Semigroup> export function getApplySemigroup(F: Apply): (S: Semigroup) => Semigroup> { return (S: Semigroup) => ({ concat: (first: HKT, second: HKT) => F.ap( F.map(first, (x: A) => (y: A) => S.concat(x, y)), second ) }) } function curried(f: Function, n: number, acc: ReadonlyArray) { return function (x: unknown) { const combined = Array(acc.length + 1) for (let i = 0; i < acc.length; i++) { combined[i] = acc[i] } combined[acc.length] = x return n === 0 ? f.apply(null, combined) : curried(f, n - 1, combined) } } const tupleConstructors: Record any> = { 1: (a) => [a], 2: (a) => (b: any) => [a, b], 3: (a) => (b: any) => (c: any) => [a, b, c], 4: (a) => (b: any) => (c: any) => (d: any) => [a, b, c, d], 5: (a) => (b: any) => (c: any) => (d: any) => (e: any) => [a, b, c, d, e] } function getTupleConstructor(len: number): (a: unknown) => any { if (!_.has.call(tupleConstructors, len)) { tupleConstructors[len] = curried(tuple, len - 1, []) } return tupleConstructors[len] } /** * Tuple sequencing, i.e., take a tuple of monadic actions and does them from left-to-right, returning the resulting tuple. * * @example * import { sequenceT } from 'fp-ts/Apply' * import * as O from 'fp-ts/Option' * * const sequenceTOption = sequenceT(O.Apply) * assert.deepStrictEqual(sequenceTOption(O.some(1)), O.some([1])) * assert.deepStrictEqual(sequenceTOption(O.some(1), O.some('2')), O.some([1, '2'])) * assert.deepStrictEqual(sequenceTOption(O.some(1), O.some('2'), O.none), O.none) * * @since 2.0.0 */ export function sequenceT( F: Apply4 ): >>( ...t: T & { readonly 0: Kind4 } ) => Kind4] ? A : never }> export function sequenceT( F: Apply3 ): >>( ...t: T & { readonly 0: Kind3 } ) => Kind3] ? A : never }> export function sequenceT( F: Apply3C ): >>( ...t: T & { readonly 0: Kind3 } ) => Kind3] ? A : never }> export function sequenceT( F: Apply2 ): >>( ...t: T & { readonly 0: Kind2 } ) => Kind2] ? A : never }> export function sequenceT( F: Apply2C ): >>( ...t: T & { readonly 0: Kind2 } ) => Kind2] ? A : never }> export function sequenceT( F: Apply1 ): >>( ...t: T & { readonly 0: Kind } ) => Kind] ? A : never }> export function sequenceT( F: Apply ): >>( ...t: T & { readonly 0: HKT } ) => HKT] ? A : never }> export function sequenceT(F: Apply): any { return (...args: Array>) => { const len = args.length const f = getTupleConstructor(len) let fas = F.map(args[0], f) for (let i = 1; i < len; i++) { fas = F.ap(fas, args[i]) } return fas } } type EnforceNonEmptyRecord = keyof R extends never ? never : R function getRecordConstructor(keys: ReadonlyArray) { const len = keys.length switch (len) { case 1: return (a: any) => ({ [keys[0]]: a }) case 2: return (a: any) => (b: any) => ({ [keys[0]]: a, [keys[1]]: b }) case 3: return (a: any) => (b: any) => (c: any) => ({ [keys[0]]: a, [keys[1]]: b, [keys[2]]: c }) case 4: return (a: any) => (b: any) => (c: any) => (d: any) => ({ [keys[0]]: a, [keys[1]]: b, [keys[2]]: c, [keys[3]]: d }) case 5: return (a: any) => (b: any) => (c: any) => (d: any) => (e: any) => ({ [keys[0]]: a, [keys[1]]: b, [keys[2]]: c, [keys[3]]: d, [keys[4]]: e }) default: return curried( (...args: ReadonlyArray) => { const r: Record = {} for (let i = 0; i < len; i++) { r[keys[i]] = args[i] } return r }, len - 1, [] ) } } /** * Like `Apply.sequenceT` but works with structs instead of tuples. * * @example * import * as E from 'fp-ts/Either' * import { sequenceS } from 'fp-ts/Apply' * * const ado = sequenceS(E.Apply) * * assert.deepStrictEqual( * ado({ * a: E.right(1), * b: E.right(true) * }), * E.right({ a: 1, b: true }) * ) * assert.deepStrictEqual( * ado({ * a: E.right(1), * b: E.left('error') * }), * E.left('error') * ) * * @since 2.0.0 */ export function sequenceS( F: Apply4 ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind4] ? A : never }> export function sequenceS( F: Apply3 ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind3] ? A : never }> export function sequenceS( F: Apply3C ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind3] ? A : never }> export function sequenceS( F: Apply2 ): >>( r: EnforceNonEmptyRecord & Record> ) => Kind2] ? A : never }> export function sequenceS( F: Apply2C ): >>( r: EnforceNonEmptyRecord ) => Kind2] ? A : never }> export function sequenceS( F: Apply1 ): >>( r: EnforceNonEmptyRecord ) => Kind] ? A : never }> export function sequenceS( F: Apply ): >>( r: EnforceNonEmptyRecord ) => HKT] ? A : never }> export function sequenceS(F: Apply): (r: Record>) => HKT> { return (r) => { const keys = Object.keys(r) const len = keys.length const f = getRecordConstructor(keys) let fr = F.map(r[keys[0]], f) for (let i = 1; i < len; i++) { fr = F.ap(fr, r[keys[i]]) } return fr } } ================================================ FILE: src/Array.ts ================================================ /** * The Array module provides tools for working with Typescript's Array type in a functional way. * * In functional jargon, this module provides a monadic interface over Typescript's Array. * * @since 2.0.0 */ import { Alt1 } from './Alt' import { Alternative1 } from './Alternative' import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain' import { ChainRec1 } from './ChainRec' import { Compactable1 } from './Compactable' import { Either } from './Either' import { Eq } from './Eq' import { Extend1 } from './Extend' import { Filterable1 } from './Filterable' import { FilterableWithIndex1, PredicateWithIndex, RefinementWithIndex } from './FilterableWithIndex' import { Foldable1 } from './Foldable' import { FoldableWithIndex1 } from './FoldableWithIndex' import { FromEither1, fromEitherK as fromEitherK_ } from './FromEither' import { dual, identity, LazyArg, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { FunctorWithIndex1 } from './FunctorWithIndex' import { HKT } from './HKT' import * as _ from './internal' import { Magma } from './Magma' import { Monad1 } from './Monad' import { Monoid } from './Monoid' import * as NEA from './NonEmptyArray' import { Option } from './Option' import { Ord } from './Ord' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import * as RA from './ReadonlyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' import { PipeableTraverseWithIndex1, TraversableWithIndex1 } from './TraversableWithIndex' import { Unfoldable1 } from './Unfoldable' import { filterE as filterE_, PipeableWilt1, PipeableWither1, wiltDefault, Witherable1, witherDefault } from './Witherable' import { guard as guard_, Zero1 } from './Zero' import NonEmptyArray = NEA.NonEmptyArray // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * Test whether an array is empty * * @example * import { isEmpty } from 'fp-ts/Array' * * assert.strictEqual(isEmpty([]), true) * assert.strictEqual(isEmpty(['a']), false) * * @category refinements * @since 2.0.0 */ export const isEmpty = (as: Array): as is [] => as.length === 0 /** * Test whether an array is non empty narrowing down the type to `NonEmptyArray` * * @example * import { isNonEmpty } from 'fp-ts/Array' * * assert.strictEqual(isNonEmpty([]), false) * assert.strictEqual(isNonEmpty(['a']), true) * * @category refinements * @since 2.0.0 */ export const isNonEmpty: (as: Array) => as is NonEmptyArray = NEA.isNonEmpty // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Prepend an element to the front of a `Array`, creating a new `NonEmptyArray`. * * @example * import { prepend } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([2, 3, 4], prepend(1)), [1, 2, 3, 4]) * * @since 2.10.0 */ export const prepend: (head: A) => (tail: Array) => NEA.NonEmptyArray = NEA.prepend /** * Less strict version of [`prepend`](#prepend). * * @example * import { prependW } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([2, 3, 4], prependW("a")), ["a", 2, 3, 4]); * * @since 2.11.0 */ export const prependW: (head: B) => (tail: Array) => NEA.NonEmptyArray = NEA.prependW /** * Append an element to the end of a `Array`, creating a new `NonEmptyArray`. * * @example * import { append } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], append(4)), [1, 2, 3, 4]) * * @since 2.10.0 */ export const append: (end: A) => (init: Array) => NEA.NonEmptyArray = NEA.append /** * Less strict version of [`append`](#append). * * @example * import { appendW } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], appendW("d")), [1, 2, 3, "d"]); * * @since 2.11.0 */ export const appendW: (end: B) => (init: Array) => NEA.NonEmptyArray = NEA.appendW /** * Return a `Array` of length `n` with element `i` initialized with `f(i)`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { makeBy } from 'fp-ts/Array' * * const double = (i: number): number => i * 2 * assert.deepStrictEqual(makeBy(5, double), [0, 2, 4, 6, 8]) * assert.deepStrictEqual(makeBy(-3, double), []) * assert.deepStrictEqual(makeBy(4.32164, double), [0, 2, 4, 6]) * * @category constructors * @since 2.0.0 */ export const makeBy = (n: number, f: (i: number) => A): Array => (n <= 0 ? [] : NEA.makeBy(f)(n)) /** * Create a `Array` containing a value repeated the specified number of times. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { replicate } from 'fp-ts/Array' * * assert.deepStrictEqual(replicate(3, 'a'), ['a', 'a', 'a']) * assert.deepStrictEqual(replicate(-3, 'a'), []) * assert.deepStrictEqual(replicate(2.985647, 'a'), ['a', 'a']) * * @category constructors * @since 2.0.0 */ export const replicate = (n: number, a: A): Array => makeBy(n, () => a) /** * Create an array with one element, if the element satisfies the predicate, otherwise * it returns an empty array. * * @example * import { fromPredicate } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * import { isString } from "fp-ts/string"; * * assert.deepStrictEqual(pipe("a", fromPredicate(isString)), ["a"]); * assert.deepStrictEqual(pipe(7, fromPredicate(isString)), []); * * assert.deepStrictEqual(pipe(7, fromPredicate((x)=> x > 0)), [7]); * assert.deepStrictEqual(pipe(-3, fromPredicate((x)=> x > 0)), []); * * @category lifting * @since 2.11.0 */ export function fromPredicate(refinement: Refinement): (a: A) => Array export function fromPredicate(predicate: Predicate): (b: B) => Array export function fromPredicate(predicate: Predicate): (a: A) => Array export function fromPredicate(predicate: Predicate): (a: A) => Array { return (a) => (predicate(a) ? [a] : []) } // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * Create an array from an `Option`. The resulting array will contain the content of the * `Option` if it is `Some` and it will be empty if the `Option` is `None`. * * @example * import { fromOption } from 'fp-ts/Array' * import { option } from "fp-ts"; * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(option.some("a"), fromOption),["a"]) * assert.deepStrictEqual(pipe(option.none, fromOption),[]) * * @category conversions * @since 2.11.0 */ export const fromOption: (fa: Option) => Array = (ma) => (_.isNone(ma) ? [] : [ma.value]) /** * Create an array from an `Either`. The resulting array will contain the content of the * `Either` if it is `Right` and it will be empty if the `Either` is `Left`. * * @example * import { fromEither } from 'fp-ts/Array' * import { either } from "fp-ts"; * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(either.right("r"), fromEither), ["r"]); * assert.deepStrictEqual(pipe(either.left("l"), fromEither), []); * * @category conversions * @since 2.11.0 */ export const fromEither: (fa: Either) => Array = (e) => (_.isLeft(e) ? [] : [e.right]) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @example * import { matchW } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * const matcherW = matchW( * () => "No elements", * (as) => as.length * ); * assert.deepStrictEqual(pipe([1, 2, 3, 4], matcherW), 4); * assert.deepStrictEqual(pipe([], matcherW), "No elements"); * * @category pattern matching * @since 2.11.0 */ export const matchW = (onEmpty: LazyArg, onNonEmpty: (as: NonEmptyArray) => C) => (as: Array): B | C => isNonEmpty(as) ? onNonEmpty(as) : onEmpty() /** * Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise * it passes the array to `onNonEmpty` and returns the result. * * @example * import { match } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * const matcher = match( * () => "No elements", * (as) => `Found ${as.length} element(s)` * ); * assert.deepStrictEqual(pipe([1, 2, 3, 4], matcher), "Found 4 element(s)"); * assert.deepStrictEqual(pipe([], matcher), "No elements"); * * @category pattern matching * @since 2.11.0 */ export const match: (onEmpty: LazyArg, onNonEmpty: (as: NonEmptyArray) => B) => (as: Array) => B = matchW /** * Less strict version of [`matchLeft`](#matchleft). It will work when `onEmpty` and * `onNonEmpty` have different return types. * * @example * import { matchLeftW } from 'fp-ts/Array' * * const f = matchLeftW( * () => 0, * (head: string, tail: string[]) => `Found "${head}" followed by ${tail.length} elements` * ); * assert.strictEqual(f(["a", "b", "c"]), 'Found "a" followed by 2 elements'); * assert.strictEqual(f([]), 0); * * @category pattern matching * @since 2.11.0 */ export const matchLeftW = (onEmpty: LazyArg, onNonEmpty: (head: A, tail: Array) => C) => (as: Array): B | C => isNonEmpty(as) ? onNonEmpty(NEA.head(as), NEA.tail(as)) : onEmpty() /** * Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise * it passes the array to `onNonEmpty` broken into its first element and remaining elements. * * @example * import { matchLeft } from 'fp-ts/Array' * * const len: (as: Array) => number = matchLeft(() => 0, (_, tail) => 1 + len(tail)) * assert.strictEqual(len([1, 2, 3]), 3) * * @category pattern matching * @since 2.10.0 */ export const matchLeft: (onEmpty: LazyArg, onNonEmpty: (head: A, tail: Array) => B) => (as: Array) => B = matchLeftW /** * Alias of [`matchLeft`](#matchleft). * * @category pattern matching * @since 2.0.0 */ export const foldLeft: (onEmpty: LazyArg, onNonEmpty: (head: A, tail: Array) => B) => (as: Array) => B = matchLeft /** * Less strict version of [`matchRight`](#matchright). It will work when `onEmpty` and * `onNonEmpty` have different return types. * * @example * import { matchRightW } from 'fp-ts/Array' * * const f = matchRightW( * () => 0, * (head: string[], tail: string) => `Found ${head.length} elements folllowed by "${tail}"` * ); * assert.strictEqual(f(["a", "b", "c"]), 'Found 2 elements folllowed by "c"'); * assert.strictEqual(f([]), 0); * * @category pattern matching * @since 2.11.0 */ export const matchRightW = (onEmpty: LazyArg, onNonEmpty: (init: Array, last: A) => C) => (as: Array): B | C => isNonEmpty(as) ? onNonEmpty(NEA.init(as), NEA.last(as)) : onEmpty() /** * Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise * it passes the array to `onNonEmpty` broken into its initial elements and the last element. * * @example * import { matchRight } from 'fp-ts/Array' * * const len: (as: Array) => number = matchRight( * () => 0, * (head, _) => 1 + len(head) * ); * assert.strictEqual(len([1, 2, 3]), 3); * * @category pattern matching * @since 2.10.0 */ export const matchRight: ( onEmpty: LazyArg, onNonEmpty: (init: Array, last: A) => B ) => (as: Array) => B = matchRightW /** * Alias of [`matchRight`](#matchright). * * @category pattern matching * @since 2.0.0 */ export const foldRight: (onEmpty: LazyArg, onNonEmpty: (init: Array, last: A) => B) => (as: Array) => B = matchRight // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Same as [`chain`](#chain), but passing also the index to the iterating function. * * @example * import { chainWithIndex, replicate } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * const f = (index: number, x: string) => replicate(2, `${x}${index}`); * assert.deepStrictEqual(pipe(["a", "b", "c"], chainWithIndex(f)), ["a0", "a0", "b1", "b1", "c2", "c2"]); * * @category sequencing * @since 2.7.0 */ export const chainWithIndex = (f: (i: number, a: A) => Array) => (as: Array): Array => { const out: Array = [] for (let i = 0; i < as.length; i++) { const bs = f(i, as[i]) for (let j = 0; j < bs.length; j++) { out.push(bs[j]) } } return out } /** * Same as `reduce` but it carries over the intermediate steps * * @example * import { scanLeft } from 'fp-ts/Array' * * assert.deepStrictEqual(scanLeft(10, (b, a: number) => b - a)([1, 2, 3]), [10, 9, 7, 4]) * * @since 2.0.0 */ export const scanLeft = (b: B, f: (b: B, a: A) => B) => (as: Array): NonEmptyArray => { const len = as.length const out = new Array(len + 1) as NonEmptyArray out[0] = b for (let i = 0; i < len; i++) { out[i + 1] = f(out[i], as[i]) } return out } /** * Fold an array from the right, keeping all intermediate results instead of only the final result * * @example * import { scanRight } from 'fp-ts/Array' * * assert.deepStrictEqual(scanRight(10, (a: number, b) => b - a)([1, 2, 3]), [4, 5, 7, 10]) * * @since 2.0.0 */ export const scanRight = (b: B, f: (a: A, b: B) => B) => (as: Array): NonEmptyArray => { const len = as.length const out = new Array(len + 1) as NonEmptyArray out[len] = b for (let i = len - 1; i >= 0; i--) { out[i] = f(as[i], out[i + 1]) } return out } /** * Calculate the number of elements in a `Array`. * * @example * import { size } from 'fp-ts/Array' * * assert.strictEqual(size(["a","b","c"]),3) * * @since 2.10.0 */ export const size = (as: Array): number => as.length /** * Test whether an array contains a particular index * * @example * import { isOutOfBound } from 'fp-ts/Array' * * assert.strictEqual(isOutOfBound(1,["a","b","c"]),false) * assert.strictEqual(isOutOfBound(-1,["a","b","c"]),true) * assert.strictEqual(isOutOfBound(3,["a","b","c"]),true) * * @since 2.0.0 */ export const isOutOfBound: (i: number, as: Array) => boolean = NEA.isOutOfBound // TODO: remove non-curried overloading in v3 /** * This function provides a safe way to read a value at a particular index from an array. * It returns a `none` if the index is out of bounds, and a `some` of the element if the * index is valid. * * @example * import { lookup } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], lookup(1)), some(2)) * assert.deepStrictEqual(pipe([1, 2, 3], lookup(3)), none) * * @since 2.0.0 */ export const lookup: { (i: number): (as: Array) => Option (i: number, as: Array): Option } = RA.lookup /** * Get the first element in an array, or `None` if the array is empty * * @example * import { head } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(head([1, 2, 3]), some(1)) * assert.deepStrictEqual(head([]), none) * * @since 2.0.0 */ export const head: (as: Array) => Option = RA.head /** * Get the last element in an array, or `None` if the array is empty * * @example * import { last } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(last([1, 2, 3]), some(3)) * assert.deepStrictEqual(last([]), none) * * @since 2.0.0 */ export const last: (as: Array) => Option = RA.last /** * Get all but the first element of an array, creating a new array, or `None` if the array is empty * * @example * import { tail } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(tail([1, 2, 3]), some([2, 3])) * assert.deepStrictEqual(tail([]), none) * * @since 2.0.0 */ export const tail = (as: Array): Option> => (isNonEmpty(as) ? _.some(NEA.tail(as)) : _.none) /** * Get all but the last element of an array, creating a new array, or `None` if the array is empty * * @example * import { init } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(init([1, 2, 3]), some([1, 2])) * assert.deepStrictEqual(init([]), none) * * @since 2.0.0 */ export const init = (as: Array): Option> => (isNonEmpty(as) ? _.some(NEA.init(as)) : _.none) /** * Keep only a max number of elements from the start of an `Array`, creating a new `Array`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { takeLeft } from 'fp-ts/Array' * * assert.deepStrictEqual(takeLeft(2)([1, 2, 3, 4, 5]), [1, 2]); * assert.deepStrictEqual(takeLeft(7)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]); * assert.deepStrictEqual(takeLeft(0)([1, 2, 3, 4, 5]), []); * assert.deepStrictEqual(takeLeft(-1)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]); * * @since 2.0.0 */ export const takeLeft = (n: number) => (as: Array): Array => isOutOfBound(n, as) ? copy(as) : as.slice(0, n) /** * Keep only a max number of elements from the end of an `Array`, creating a new `Array`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { takeRight } from 'fp-ts/Array' * * assert.deepStrictEqual(takeRight(2)([1, 2, 3, 4, 5]), [4, 5]); * assert.deepStrictEqual(takeRight(7)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]); * assert.deepStrictEqual(takeRight(0)([1, 2, 3, 4, 5]), []); * assert.deepStrictEqual(takeRight(-1)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]); * * @since 2.0.0 */ export const takeRight = (n: number) => (as: Array): Array => isOutOfBound(n, as) ? copy(as) : n === 0 ? [] : as.slice(-n) /** * Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new array * * @example * import { takeLeftWhile } from 'fp-ts/Array' * * assert.deepStrictEqual(takeLeftWhile((n: number) => n % 2 === 0)([2, 4, 3, 6]), [2, 4]) * * @since 2.0.0 */ export function takeLeftWhile(refinement: Refinement): (as: Array) => Array export function takeLeftWhile(predicate: Predicate): (bs: Array) => Array export function takeLeftWhile(predicate: Predicate): (as: Array) => Array export function takeLeftWhile(predicate: Predicate): (as: Array) => Array { return (as: Array) => { const out: Array = [] for (const a of as) { if (!predicate(a)) { break } out.push(a) } return out } } const spanLeftIndex = (as: Array, predicate: Predicate): number => { const l = as.length let i = 0 for (; i < l; i++) { if (!predicate(as[i])) { break } } return i } /** * Type returned by [`spanLeft`](#spanLeft) composed of an `init` array and a `rest` array. * * @since 2.10.0 */ export interface Spanned { init: Array rest: Array } /** * Split an array into two parts: * 1. the longest initial subarray for which all elements satisfy the specified predicate * 2. the remaining elements * * @example * import { spanLeft } from 'fp-ts/Array' * * const isOdd = (n: number) => n % 2 === 1; * assert.deepStrictEqual(spanLeft(isOdd)([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] }); * assert.deepStrictEqual(spanLeft(isOdd)([0, 2, 4, 5]), { init: [], rest: [0, 2, 4, 5] }); * assert.deepStrictEqual(spanLeft(isOdd)([1, 3, 5]), { init: [1, 3, 5], rest: [] }); * * @since 2.0.0 */ export function spanLeft(refinement: Refinement): (as: Array) => Spanned export function spanLeft(predicate: Predicate): (bs: Array) => Spanned export function spanLeft(predicate: Predicate): (as: Array) => Spanned export function spanLeft(predicate: Predicate): (as: Array) => Spanned { return (as) => { const [init, rest] = splitAt(spanLeftIndex(as, predicate))(as) return { init, rest } } } /** * Creates a new `Array` which is a copy of the input dropping a max number of elements from the start. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { dropLeft } from 'fp-ts/Array' * * assert.deepStrictEqual(dropLeft(2)([1, 2, 3]), [3]); * assert.deepStrictEqual(dropLeft(5)([1, 2, 3]), []); * assert.deepStrictEqual(dropLeft(0)([1, 2, 3]), [1, 2, 3]); * assert.deepStrictEqual(dropLeft(-2)([1, 2, 3]), [1, 2, 3]); * * @since 2.0.0 */ export const dropLeft = (n: number) => (as: Array): Array => n <= 0 || isEmpty(as) ? copy(as) : n >= as.length ? [] : as.slice(n, as.length) /** * Creates a new `Array` which is a copy of the input dropping a max number of elements from the end. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { dropRight } from 'fp-ts/Array' * * assert.deepStrictEqual(dropRight(2)([1, 2, 3]), [1]); * assert.deepStrictEqual(dropRight(5)([1, 2, 3]), []); * assert.deepStrictEqual(dropRight(0)([1, 2, 3]), [1, 2, 3]); * assert.deepStrictEqual(dropRight(-2)([1, 2, 3]), [1, 2, 3]); * * @since 2.0.0 */ export const dropRight = (n: number) => (as: Array): Array => n <= 0 || isEmpty(as) ? copy(as) : n >= as.length ? [] : as.slice(0, as.length - n) /** * Creates a new `Array` which is a copy of the input dropping the longest initial subarray for * which all element satisfy the specified predicate. * * @example * import { dropLeftWhile } from 'fp-ts/Array' * * assert.deepStrictEqual(dropLeftWhile((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), [2, 4, 5]) * * @since 2.0.0 */ export function dropLeftWhile(refinement: Refinement): (as: Array) => Array export function dropLeftWhile(predicate: Predicate): (bs: Array) => Array export function dropLeftWhile(predicate: Predicate): (as: Array) => Array export function dropLeftWhile(predicate: Predicate): (as: Array) => Array { return (as) => as.slice(spanLeftIndex(as, predicate)) } /** * `findIndex` returns an `Option` containing the first index for which a predicate holds. * It returns `None` if no element satisfies the predicate. * Similar to [`findFirst`](#findFirst) but returning the index instead of the element. * * @example * import { findIndex } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(findIndex((n: number) => n === 2)([1, 2, 3]), some(1)) * assert.deepStrictEqual(findIndex((n: number) => n === 2)([]), none) * * @since 2.0.0 */ export const findIndex: (predicate: Predicate) => (as: Array) => Option = RA.findIndex /** * Find the first element which satisfies a predicate (or a refinement) function. * It returns an `Option` containing the element or `None` if not found. * * @example * import { findFirst } from 'fp-ts/Array' * import { some } from 'fp-ts/Option' * * type X = { * readonly a: number * readonly b: number * } * * assert.deepStrictEqual(findFirst((x: X) => x.a === 1)([{ a: 1, b: 1 }, { a: 1, b: 2 }]), some({ a: 1, b: 1 })) * * @since 2.0.0 */ export function findFirst(refinement: Refinement): (as: Array) => Option export function findFirst(predicate: Predicate): (bs: Array) => Option export function findFirst(predicate: Predicate): (as: Array) => Option export function findFirst(predicate: Predicate): (as: Array) => Option { return RA.findFirst(predicate) } /** * Given a selector function which takes an element and returns an option, * this function applies the selector to each element of the array and * returns the first `Some` result. Otherwise it returns `None`. * * @example * import { findFirstMap } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * interface Person { * readonly name: string; * readonly age: number; * } * * const persons: Array = [ * { name: "John", age: 16 }, * { name: "Mary", age: 45 }, * { name: "Joey", age: 28 }, * ]; * * const nameOfPersonAbove18 = (p: Person) => (p.age <= 18 ? none : some(p.name)); * const nameOfPersonAbove70 = (p: Person) => (p.age <= 70 ? none : some(p.name)); * assert.deepStrictEqual(findFirstMap(nameOfPersonAbove18)(persons), some("Mary")); * assert.deepStrictEqual(findFirstMap(nameOfPersonAbove70)(persons), none); * * @since 2.0.0 */ export const findFirstMap: (f: (a: A) => Option) => (as: Array) => Option = RA.findFirstMap /** * Find the last element which satisfies a predicate function. * It returns an `Option` containing the element or `None` if not found. * * @example * import { findLast } from 'fp-ts/Array' * import { some } from 'fp-ts/Option' * * type X = { * readonly a: number * readonly b: number * } * * assert.deepStrictEqual(findLast((x: X) => x.a === 1)([{ a: 1, b: 1 }, { a: 1, b: 2 }]), some({ a: 1, b: 2 })) * * @since 2.0.0 */ export function findLast(refinement: Refinement): (as: Array) => Option export function findLast(predicate: Predicate): (bs: Array) => Option export function findLast(predicate: Predicate): (as: Array) => Option export function findLast(predicate: Predicate): (as: Array) => Option { return RA.findLast(predicate) } /** * Given a selector function which takes an element and returns an option, * this function applies the selector to each element of the array starting from the * end and returns the last `Some` result. Otherwise it returns `None`. * * @example * import { findLastMap } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * interface Person { * readonly name: string; * readonly age: number; * } * * const persons: Array = [ * { name: "John", age: 16 }, * { name: "Mary", age: 45 }, * { name: "Joey", age: 28 }, * ]; * * const nameOfPersonAbove18 = (p: Person) => (p.age <= 18 ? none : some(p.name)); * const nameOfPersonAbove70 = (p: Person) => (p.age <= 70 ? none : some(p.name)); * assert.deepStrictEqual(findLastMap(nameOfPersonAbove18)(persons), some("Joey")); * assert.deepStrictEqual(findLastMap(nameOfPersonAbove70)(persons), none); * * @since 2.0.0 */ export const findLastMap: (f: (a: A) => Option) => (as: Array) => Option = RA.findLastMap /** * Returns the index of the last element of the list which matches the predicate. * It returns an `Option` containing the index or `None` if not found. * * @example * import { findLastIndex } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * interface X { * readonly a: number * readonly b: number * } * const xs: Array = [{ a: 1, b: 0 }, { a: 1, b: 1 }] * assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 1)(xs), some(1)) * assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 4)(xs), none) * * @since 2.0.0 */ export const findLastIndex: (predicate: Predicate) => (as: Array) => Option = RA.findLastIndex /** * This function takes an array and makes a new array containing the same elements. * * @since 2.0.0 */ export const copy = (as: Array): Array => as.slice() /** * Insert an element at the specified index, creating a new array, * or returning `None` if the index is out of bounds. * * @example * import { insertAt } from 'fp-ts/Array' * import { some } from 'fp-ts/Option' * * assert.deepStrictEqual(insertAt(2, 5)([1, 2, 3, 4]), some([1, 2, 5, 3, 4])) * * @since 2.0.0 */ export const insertAt = (i: number, a: A) => (as: Array): Option> => i < 0 || i > as.length ? _.none : _.some(unsafeInsertAt(i, a, as)) /** * Change the element at the specified index, creating a new array, * or returning `None` if the index is out of bounds. * * @example * import { updateAt } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(updateAt(1, 1)([1, 2, 3]), some([1, 1, 3])) * assert.deepStrictEqual(updateAt(1, 1)([]), none) * * @since 2.0.0 */ export const updateAt = (i: number, a: A): ((as: Array) => Option>) => modifyAt(i, () => a) /** * Delete the element at the specified index, creating a new array, or returning `None` if the index is out of bounds. * * @example * import { deleteAt } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(deleteAt(0)([1, 2, 3]), some([2, 3])) * assert.deepStrictEqual(deleteAt(1)([]), none) * * @since 2.0.0 */ export const deleteAt = (i: number) => (as: Array): Option> => isOutOfBound(i, as) ? _.none : _.some(unsafeDeleteAt(i, as)) /** * Apply a function to the element at the specified index, creating a new array, or returning `None` if the index is out * of bounds. * * @example * import { modifyAt } from 'fp-ts/Array' * import { some, none } from 'fp-ts/Option' * * const double = (x: number): number => x * 2 * assert.deepStrictEqual(modifyAt(1, double)([1, 2, 3]), some([1, 4, 3])) * assert.deepStrictEqual(modifyAt(1, double)([]), none) * * @since 2.0.0 */ export const modifyAt = (i: number, f: (a: A) => A) => (as: Array): Option> => isOutOfBound(i, as) ? _.none : _.some(unsafeUpdateAt(i, f(as[i]), as)) /** * Reverse an array, creating a new array * * @example * import { reverse } from 'fp-ts/Array' * * assert.deepStrictEqual(reverse([1, 2, 3]), [3, 2, 1]) * * @since 2.0.0 */ export const reverse = (as: Array): Array => (isEmpty(as) ? [] : as.slice().reverse()) /** * Takes an `Array` of `Either` and produces a new `Array` containing * the values of all the `Right` elements in the same order. * * @example * import { rights } from 'fp-ts/Array' * import { right, left } from 'fp-ts/Either' * * assert.deepStrictEqual(rights([right(1), left('foo'), right(2)]), [1, 2]) * * @since 2.0.0 */ export const rights = (as: Array>): Array => { const r: Array = [] for (let i = 0; i < as.length; i++) { const a = as[i] if (a._tag === 'Right') { r.push(a.right) } } return r } /** * Takes an `Array` of `Either` and produces a new `Array` containing * the values of all the `Left` elements in the same order. * * @example * import { lefts } from 'fp-ts/Array' * import { left, right } from 'fp-ts/Either' * * assert.deepStrictEqual(lefts([right(1), left('foo'), right(2)]), ['foo']) * * @since 2.0.0 */ export const lefts = (as: Array>): Array => { const r: Array = [] for (let i = 0; i < as.length; i++) { const a = as[i] if (a._tag === 'Left') { r.push(a.left) } } return r } /** * Sort the elements of an array in increasing order, creating a new array * * @example * import { sort } from 'fp-ts/Array' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(sort(N.Ord)([3, 2, 1]), [1, 2, 3]) * * @since 2.0.0 */ export const sort = (O: Ord) => (as: Array): Array => as.length <= 1 ? copy(as) : as.slice().sort(O.compare) /** * Apply a function to pairs of elements at the same index in two arrays, collecting the results in a new array. If one * input array is short, excess elements of the longer array are discarded. * * @example * import { zipWith } from 'fp-ts/Array' * * assert.deepStrictEqual(zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3']) * * @since 2.0.0 */ export const zipWith = (fa: Array, fb: Array, f: (a: A, b: B) => C): Array => { const fc: Array = [] const len = Math.min(fa.length, fb.length) for (let i = 0; i < len; i++) { fc[i] = f(fa[i], fb[i]) } return fc } // TODO: remove non-curried overloading in v3 /** * Takes two arrays and returns an array of corresponding pairs. If one input array is short, excess elements of the * longer array are discarded * * @example * import { zip } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], zip(['a', 'b', 'c', 'd'])), [[1, 'a'], [2, 'b'], [3, 'c']]) * * @since 2.0.0 */ export function zip(bs: Array): (as: Array) => Array<[A, B]> export function zip(as: Array, bs: Array): Array<[A, B]> export function zip(as: Array, bs?: Array): Array<[A, B]> | ((bs: Array) => Array<[B, A]>) { if (bs === undefined) { return (bs) => zip(bs, as) } return zipWith(as, bs, (a, b) => [a, b]) } /** * The function is reverse of `zip`. Takes an array of pairs and return two corresponding arrays * * @example * import { unzip } from 'fp-ts/Array' * * assert.deepStrictEqual(unzip([[1, 'a'], [2, 'b'], [3, 'c']]), [[1, 2, 3], ['a', 'b', 'c']]) * * @since 2.0.0 */ export const unzip = (as: Array<[A, B]>): [Array, Array] => { const fa: Array = [] const fb: Array = [] for (let i = 0; i < as.length; i++) { fa[i] = as[i][0] fb[i] = as[i][1] } return [fa, fb] } /** * Creates a new `Array`, prepending an element to every member of the input `Array`. * * @example * import { prependAll } from 'fp-ts/Array' * * assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) * * @since 2.10.0 */ export const prependAll = (middle: A): ((as: Array) => Array) => { const f = NEA.prependAll(middle) return (as) => (isNonEmpty(as) ? f(as) : []) } /** * Creates a new `Array` placing an element in between members of the input `Array`. * * @example * import { intersperse } from 'fp-ts/Array' * * assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) * * @since 2.9.0 */ export const intersperse = (middle: A): ((as: Array) => Array) => { const f = NEA.intersperse(middle) return (as) => (isNonEmpty(as) ? f(as) : copy(as)) } /** * Creates a new `Array` rotating the input `Array` by `n` steps. * * @example * import { rotate } from 'fp-ts/Array' * * assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) * * @since 2.0.0 */ export const rotate = (n: number): ((as: Array) => Array) => { const f = NEA.rotate(n) return (as) => (isNonEmpty(as) ? f(as) : copy(as)) } // TODO: remove non-curried overloading in v3 /** * Test if a value is a member of an `Array`. Takes a `Eq` as a single * argument which returns the function to use to search for a value of type `A` in * an `Array`. * * @example * import { elem } from 'fp-ts/Array' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(2)), true) * assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(0)), false) * * @since 2.0.0 */ export const elem: (E: Eq) => { (a: A): (as: Array) => boolean (a: A, as: Array): boolean } = RA.elem /** * Creates a new `Array` removing duplicate elements, keeping the first occurrence of an element, * based on a `Eq`. * * @example * import { uniq } from 'fp-ts/Array' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) * * @since 2.0.0 */ export const uniq = (E: Eq): ((as: Array) => Array) => { const f = NEA.uniq(E) return (as) => (isNonEmpty(as) ? f(as) : copy(as)) } /** * Sort the elements of an array in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, * etc... * * @example * import { sortBy } from 'fp-ts/Array' * import { contramap } from 'fp-ts/Ord' * import * as S from 'fp-ts/string' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * interface Person { * readonly name: string * readonly age: number * } * const byName = pipe(S.Ord, contramap((p: Person) => p.name)) * const byAge = pipe(N.Ord, contramap((p: Person) => p.age)) * * const sortByNameByAge = sortBy([byName, byAge]) * * const persons = [{ name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 }] * assert.deepStrictEqual(sortByNameByAge(persons), [ * { name: 'a', age: 1 }, * { name: 'b', age: 2 }, * { name: 'b', age: 3 }, * { name: 'c', age: 2 } * ]) * * @since 2.0.0 */ export const sortBy = (ords: Array>): ((as: Array) => Array) => { const f = NEA.sortBy(ords) return (as) => (isNonEmpty(as) ? f(as) : copy(as)) } /** * A useful recursion pattern for processing an array to produce a new array, often used for "chopping" up the input * array. Typically chop is called with some function that will consume an initial prefix of the array and produce a * value and the rest of the array. * * @example * import { Eq } from 'fp-ts/Eq' * import * as A from 'fp-ts/Array' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * const group = (S: Eq): ((as: Array) => Array>) => { * return A.chop(as => { * const { init, rest } = pipe(as, A.spanLeft((a: A) => S.equals(a, as[0]))) * return [init, rest] * }) * } * assert.deepStrictEqual(group(N.Eq)([1, 1, 2, 3, 3, 4]), [[1, 1], [2], [3, 3], [4]]) * * @since 2.0.0 */ export const chop = (f: (as: NonEmptyArray) => [B, Array]): ((as: Array) => Array) => { const g = NEA.chop(f) return (as) => (isNonEmpty(as) ? g(as) : []) } /** * Splits an `Array` into two pieces, the first piece has max `n` elements. * * @example * import { splitAt } from 'fp-ts/Array' * * assert.deepStrictEqual(splitAt(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4, 5]]) * * @since 2.0.0 */ export const splitAt = (n: number) => (as: Array): [Array, Array] => n >= 1 && isNonEmpty(as) ? NEA.splitAt(n)(as) : isEmpty(as) ? [copy(as), []] : [[], copy(as)] /** * Splits an array into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the array. Note that `chunksOf(n)([])` is `[]`, not `[[]]`. This is intentional, and is consistent with a recursive * definition of `chunksOf`; it satisfies the property that * * ```ts * chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys))) * ``` * * whenever `n` evenly divides the length of `xs`. * * @example * import { chunksOf } from 'fp-ts/Array' * * assert.deepStrictEqual(chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) * * @since 2.0.0 */ export const chunksOf = (n: number): ((as: Array) => Array>) => { const f = NEA.chunksOf(n) return (as) => (isNonEmpty(as) ? f(as) : []) } /** * @category lifting * @since 2.11.0 */ export const fromOptionK = , B>(f: (...a: A) => Option) => (...a: A): Array => fromOption(f(...a)) /** * `Array` comprehension. * * ``` * [ f(x, y, ...) | x ← xs, y ← ys, ..., g(x, y, ...) ] * ``` * * @example * import { comprehension } from 'fp-ts/Array' * import { tuple } from 'fp-ts/function' * * assert.deepStrictEqual(comprehension([[1, 2, 3], ['a', 'b']], tuple, (a, b) => (a + b.length) % 2 === 0), [ * [1, 'a'], * [1, 'b'], * [3, 'a'], * [3, 'b'] * ]) * * @since 2.0.0 */ export function comprehension( input: [Array, Array, Array, Array], f: (a: A, b: B, c: C, d: D) => R, g?: (a: A, b: B, c: C, d: D) => boolean ): Array export function comprehension( input: [Array, Array, Array], f: (a: A, b: B, c: C) => R, g?: (a: A, b: B, c: C) => boolean ): Array export function comprehension( input: [Array, Array], f: (a: A, b: B) => R, g?: (a: A, b: B) => boolean ): Array export function comprehension(input: [Array], f: (a: A) => R, g?: (a: A) => boolean): Array export function comprehension( input: Array>, f: (...xs: Array) => R, g: (...xs: Array) => boolean = () => true ): Array { const go = (scope: Array, input: Array>): Array => isNonEmpty(input) ? flatMap(NEA.head(input), (a) => go(pipe(scope, append(a)), NEA.tail(input))) : g(...scope) ? [f(...scope)] : [] return go([], input) } /** * @since 2.11.0 */ export const concatW = (second: Array) => (first: Array): Array => isEmpty(first) ? copy(second) : isEmpty(second) ? copy(first) : (first as Array).concat(second) /** * @since 2.11.0 */ export const concat: (second: Array) => (first: Array) => Array = concatW // TODO: remove non-curried overloading in v3 /** * Creates an array of unique values, in order, from all given arrays using a `Eq` for equality comparisons * * @example * import { union } from 'fp-ts/Array' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2], union(N.Eq)([2, 3])), [1, 2, 3]) * * @since 2.0.0 */ export function union(E: Eq): { (xs: Array): (ys: Array) => Array (xs: Array, ys: Array): Array } export function union(E: Eq): (xs: Array, ys?: Array) => Array | ((ys: Array) => Array) { const unionE = NEA.union(E) return (first, second?) => { if (second === undefined) { const unionE = union(E) return (second) => unionE(second, first) } return isNonEmpty(first) && isNonEmpty(second) ? unionE(second)(first) : isNonEmpty(first) ? copy(first) : copy(second) } } // TODO: remove non-curried overloading in v3 /** * Creates an array of unique values that are included in all given arrays using a `Eq` for equality * comparisons. The order and references of result values are determined by the first array. * * @example * import { intersection } from 'fp-ts/Array' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2], intersection(N.Eq)([2, 3])), [2]) * * @since 2.0.0 */ export function intersection(E: Eq): { (xs: Array): (ys: Array) => Array (xs: Array, ys: Array): Array } export function intersection(E: Eq): (xs: Array, ys?: Array) => Array | ((ys: Array) => Array) { const elemE = elem(E) return (xs, ys?) => { if (ys === undefined) { const intersectionE = intersection(E) return (ys) => intersectionE(ys, xs) } return xs.filter((a) => elemE(a, ys)) } } // TODO: remove non-curried overloading in v3 /** * Creates an array of array values not included in the other given array using a `Eq` for equality * comparisons. The order and references of result values are determined by the first array. * * @example * import { difference } from 'fp-ts/Array' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2], difference(N.Eq)([2, 3])), [1]) * * @since 2.0.0 */ export function difference(E: Eq): { (xs: Array): (ys: Array) => Array (xs: Array, ys: Array): Array } export function difference(E: Eq): (xs: Array, ys?: Array) => Array | ((ys: Array) => Array) { const elemE = elem(E) return (xs, ys?) => { if (ys === undefined) { const differenceE = difference(E) return (ys) => differenceE(ys, xs) } return xs.filter((a) => !elemE(a, ys)) } } const _map: Monad1['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _mapWithIndex: FunctorWithIndex1['mapWithIndex'] = (fa, f) => pipe(fa, mapWithIndex(f)) const _ap: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _filter: Filterable1['filter'] = (fa: Array, predicate: Predicate) => pipe(fa, filter(predicate)) /* istanbul ignore next */ const _filterMap: Filterable1['filterMap'] = (fa, f) => pipe(fa, filterMap(f)) /* istanbul ignore next */ const _partition: Filterable1['partition'] = (fa: Array, predicate: Predicate) => pipe(fa, partition(predicate)) /* istanbul ignore next */ const _partitionMap: Filterable1['partitionMap'] = (fa, f) => pipe(fa, partitionMap(f)) /* istanbul ignore next */ const _partitionWithIndex: FilterableWithIndex1['partitionWithIndex'] = ( fa: Array, predicateWithIndex: (i: number, a: A) => boolean ) => pipe(fa, partitionWithIndex(predicateWithIndex)) /* istanbul ignore next */ const _partitionMapWithIndex: FilterableWithIndex1['partitionMapWithIndex'] = ( fa: Array, f: (i: number, a: A) => Either ) => pipe(fa, partitionMapWithIndex(f)) /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) const _reduce: Foldable1['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable1['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable1['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _reduceWithIndex: FoldableWithIndex1['reduceWithIndex'] = (fa, b, f) => pipe(fa, reduceWithIndex(b, f)) /* istanbul ignore next */ const _foldMapWithIndex: FoldableWithIndex1['foldMapWithIndex'] = (M) => { const foldMapWithIndexM = foldMapWithIndex(M) return (fa, f) => pipe(fa, foldMapWithIndexM(f)) } /* istanbul ignore next */ const _reduceRightWithIndex: FoldableWithIndex1['reduceRightWithIndex'] = (fa, b, f) => pipe(fa, reduceRightWithIndex(b, f)) /* istanbul ignore next */ const _filterMapWithIndex: FilterableWithIndex1['filterMapWithIndex'] = ( fa: Array, f: (i: number, a: A) => Option ) => pipe(fa, filterMapWithIndex(f)) /* istanbul ignore next */ const _filterWithIndex: FilterableWithIndex1['filterWithIndex'] = ( fa: Array, predicateWithIndex: (i: number, a: A) => boolean ) => pipe(fa, filterWithIndex(predicateWithIndex)) /* istanbul ignore next */ const _extend: Extend1['extend'] = (fa, f) => pipe(fa, extend(f)) /* istanbul ignore next */ const _traverse: Traversable1['traverse'] = ( F: ApplicativeHKT ): ((ta: Array, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /* istanbul ignore next */ const _traverseWithIndex: TraversableWithIndex1['traverseWithIndex'] = ( F: ApplicativeHKT ): ((ta: Array, f: (i: number, a: A) => HKT) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta, f) => pipe(ta, traverseWithIndexF(f)) } const _chainRecDepthFirst: ChainRec1['chainRec'] = RA._chainRecDepthFirst as any const _chainRecBreadthFirst: ChainRec1['chainRec'] = RA._chainRecBreadthFirst as any /** * Given an element of the base type, `of` builds an `Array` containing just that * element of the base type (this is useful for building a `Monad`). * * @example * import { of } from 'fp-ts/Array' * * assert.deepStrictEqual(of("a"), ["a"]); * * @category constructors * @since 2.0.0 */ export const of: (a: A) => Array = NEA.of /** * Makes an empty `Array`, useful for building a [`Monoid`](#Monoid) * * @since 2.7.0 */ export const zero: () => Array = () => [] /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: Array) => Array`. * In practice it applies the base function to each element of the array and collects the * results in a new array. * * @example * import { map } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * const f = (n: number) => n * 2; * assert.deepStrictEqual(pipe([1, 2, 3], map(f)), [2, 4, 6]); * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Array) => Array = (f) => (fa) => fa.map((a) => f(a)) /** * @example * import { ap, map, of } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * // a curried function with 3 input parameteres * const f = (s1: string) => (n: number) => (s2: string) => s1 + n + s2; * * // let's use `ap` to iterate `f` over an array for each input parameter * assert.deepStrictEqual(pipe(["a", "b"], map(f), ap([1, 2]), ap(["😀", "😫", "😎"])), [ * "a1😀", "a1😫", "a1😎", * "a2😀", "a2😫", "a2😎", * "b1😀", "b1😫", "b1😎", * "b2😀", "b2😫", "b2😎", * ]); * * // given Array implements the Applicative interface with the `of` method, * // we can write exactly the same thing in a more symmetric way * // using `of` on `f` and `ap` on each array in input * assert.deepStrictEqual( * pipe(of(f), ap(["a", "b"]), ap([1, 2]), ap(["😀", "😫", "😎"])), * pipe(["a", "b"], map(f), ap([1, 2]), ap(["😀", "😫", "😎"])) * ); * * @since 2.0.0 */ export const ap: (fa: Array) => (fab: Array<(a: A) => B>) => Array = (fa) => flatMap((f) => pipe(fa, map(f))) /** * Composes computations in sequence, using the return value of one computation to * determine the next computation. * * In other words it takes a function `f` that produces an array from a single element of * the base type `A` and returns a new function which applies `f` to each element of the * input array (like [`map`](#map)) and, instead of returning an array of arrays, concatenates the * results into a single array (like [`flatten`](#flatten)). * * @example * import { flatMap, map, replicate } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * const f = (n: number) => replicate(n, `${n}`); * assert.deepStrictEqual(pipe([1, 2, 3], map(f)), [["1"], ["2", "2"], ["3", "3", "3"]]); * assert.deepStrictEqual(pipe([1, 2, 3], flatMap(f)), ["1", "2", "2", "3", "3", "3"]); * * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A, i: number) => Array): (ma: Array) => Array (ma: Array, f: (a: A, i: number) => Array): Array } = /*#__PURE__*/ dual( 2, (ma: Array, f: (a: A, i: number) => Array): Array => pipe( ma, chainWithIndex((i, a) => f(a, i)) ) ) /** * Takes an array of arrays of `A` and flattens them into an array of `A` * by concatenating the elements of each array in order. * * @example * import { flatten } from 'fp-ts/Array' * * assert.deepStrictEqual(flatten([["a"], ["b", "c"], ["d", "e", "f"]]), ["a", "b", "c", "d", "e", "f"]); * * @category sequencing * @since 2.5.0 */ export const flatten: (mma: Array>) => Array = /*#__PURE__*/ flatMap(identity) /** * Same as [`map`](#map), but the iterating function takes both the index and the value * of the element. * * @example * import { mapWithIndex } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * const f = (i: number, s: string) => `${s} - ${i}`; * assert.deepStrictEqual(pipe(["a", "b", "c"], mapWithIndex(f)), ["a - 0", "b - 1", "c - 2"]); * * @category mapping * @since 2.0.0 */ export const mapWithIndex: (f: (i: number, a: A) => B) => (fa: Array) => Array = (f) => (fa) => fa.map((a, i) => f(i, a)) /** * Maps an array with an iterating function that takes the index and the value of * each element and returns an `Option`. It keeps only the `Some` values discarding * the `None`s. * * Same as [`filterMap`](#filterMap), but with an iterating function which takes also * the index as input. * * @example * import { filterMapWithIndex } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * import { option } from "fp-ts"; * * const f = (i: number, s: string) => (i % 2 === 1 ? option.some(s.toUpperCase()) : option.none); * assert.deepStrictEqual(pipe(["a", "no", "neither", "b"], filterMapWithIndex(f)), ["NO", "B"]); * * @category filtering * @since 2.0.0 */ export const filterMapWithIndex = (f: (i: number, a: A) => Option) => (fa: Array): Array => { const out: Array = [] for (let i = 0; i < fa.length; i++) { const optionB = f(i, fa[i]) if (_.isSome(optionB)) { out.push(optionB.value) } } return out } /** * Maps an array with an iterating function that returns an `Option` * and it keeps only the `Some` values discarding the `None`s. * * @example * import { filterMap } from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * import { option } from "fp-ts"; * * const f = (s: string) => s.length === 1 ? option.some(s.toUpperCase()) : option.none; * assert.deepStrictEqual(pipe(["a", "no", "neither", "b"], filterMap(f)), ["A", "B"]); * * @category filtering * @since 2.0.0 */ export const filterMap: (f: (a: A) => Option) => (fa: Array) => Array = (f) => filterMapWithIndex((_, a) => f(a)) /** * Compact an array of `Option`s discarding the `None` values and * keeping the `Some` values. It returns a new array containing the values of * the `Some` options. * * @example * import { compact } from 'fp-ts/Array' * import { option } from "fp-ts"; * * assert.deepStrictEqual(compact([option.some("a"), option.none, option.some("b")]), ["a", "b"]); * * @category filtering * @since 2.0.0 */ export const compact: (fa: Array>) => Array = /*#__PURE__*/ filterMap(identity) /** * Separate an array of `Either`s into `Left`s and `Right`s, creating two new arrays: * one containing all the left values and one containing all the right values. * * @example * import { separate } from 'fp-ts/Array' * import { either } from "fp-ts"; * * assert.deepStrictEqual(separate([either.right("r1"), either.left("l1"), either.right("r2")]), { * left: ["l1"], * right: ["r1", "r2"], * }); * * @category filtering * @since 2.0.0 */ export const separate = (fa: Array>): Separated, Array> => { const left: Array = [] const right: Array = [] for (const e of fa) { if (e._tag === 'Left') { left.push(e.left) } else { right.push(e.right) } } return separated(left, right) } /** * Given an iterating function that is a `Predicate` or a `Refinement`, * `filter` creates a new `Array` containing the elements of the original * `Array` for which the iterating function is `true`. * * @example * import { filter } from 'fp-ts/Array' * import { isString } from "fp-ts/string"; * * assert.deepStrictEqual(filter(isString)(["a", 1, {}, "b", 5]), ["a", "b"]); * assert.deepStrictEqual(filter((x:number) => x > 0)([-3, 1, -2, 5]), [1, 5]); * * @category filtering * @since 2.0.0 */ export const filter: { (refinement: Refinement): (as: Array) => Array (predicate: Predicate): (bs: Array) => Array (predicate: Predicate): (as: Array) => Array } = (predicate: Predicate) => (as: Array) => as.filter(predicate) /** * Given an iterating function that is a `Predicate` or a `Refinement`, * `partition` creates two new `Array`s: `right` containing the elements of the original * `Array` for which the iterating function is `true`, `left` containing the elements * for which it is false. * * @example * import { partition } from 'fp-ts/Array' * import { isString } from "fp-ts/string"; * * assert.deepStrictEqual(partition(isString)(["a", 1, {}, "b", 5]), { left: [1, {}, 5], right: ["a", "b"] }); * assert.deepStrictEqual(partition((x: number) => x > 0)([-3, 1, -2, 5]), { left: [-3, -2], right: [1, 5] }); * * @category filtering * @since 2.0.0 */ export const partition: { (refinement: Refinement): (as: Array) => Separated, Array> (predicate: Predicate): (bs: Array) => Separated, Array> (predicate: Predicate): (as: Array) => Separated, Array> } = (predicate: Predicate): ((as: Array) => Separated, Array>) => partitionWithIndex((_, a) => predicate(a)) /** * Same as [`partition`](#partition), but passing also the index to the iterating function. * * @example * import { partitionWithIndex } from 'fp-ts/Array' * * assert.deepStrictEqual(partitionWithIndex((index, x: number) => index < 3 && x > 0)([-2, 5, 6, 7]), { * left: [-2, 7], * right: [5, 6], * }); * * @category filtering * @since 2.0.0 */ export const partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( as: Array ) => Separated, Array> (predicateWithIndex: PredicateWithIndex): (bs: Array) => Separated, Array> (predicateWithIndex: PredicateWithIndex): (as: Array) => Separated, Array> } = (predicateWithIndex: PredicateWithIndex) => (as: Array): Separated, Array> => { const left: Array = [] const right: Array = [] for (let i = 0; i < as.length; i++) { const b = as[i] if (predicateWithIndex(i, b)) { right.push(b) } else { left.push(b) } } return separated(left, right) } /** * Given an iterating function that returns an `Either`, * `partitionMap` applies the iterating function to each element and it creates two `Array`s: * `right` containing the values of `Right` results, `left` containing the values of `Left` results. * * @example * import { partitionMap } from 'fp-ts/Array' * import { Either, left, right } from "fp-ts/Either"; * * const upperIfString = (x: B): Either => * typeof x === "string" ? right(x.toUpperCase()) : left(x); * assert.deepStrictEqual(partitionMap(upperIfString)([-2, "hello", 6, 7, "world"]), { * left: [-2, 6, 7], * right: [ 'HELLO', 'WORLD' ], * }); * * @category filtering * @since 2.0.0 */ export const partitionMap: (f: (a: A) => Either) => (fa: Array) => Separated, Array> = ( f ) => partitionMapWithIndex((_, a) => f(a)) /** * Same as [`partitionMap`](#partitionMap), but passing also the index to the iterating function. * * @example * import { partitionMapWithIndex } from 'fp-ts/Array' * import { Either, left, right } from "fp-ts/Either"; * * const upperIfStringBefore3 = (index: number, x: B): Either => * index < 3 && typeof x === "string" ? right(x.toUpperCase()) : left(x); * assert.deepStrictEqual(partitionMapWithIndex(upperIfStringBefore3)([-2, "hello", 6, 7, "world"]), { * left: [-2, 6, 7, "world"], * right: ["HELLO"], * }); * * @category filtering * @since 2.0.0 */ export const partitionMapWithIndex = (f: (i: number, a: A) => Either) => (fa: Array): Separated, Array> => { const left: Array = [] const right: Array = [] for (let i = 0; i < fa.length; i++) { const e = f(i, fa[i]) if (e._tag === 'Left') { left.push(e.left) } else { right.push(e.right) } } return separated(left, right) } /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @example * import * as A from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * A.altW(() => ['a', 'b']) * ), * [1, 2, 3, 'a', 'b'] * ) * * @category error handling * @since 2.9.0 */ export const altW = (that: LazyArg>) => (fa: Array): Array => (fa as Array).concat(that()) /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * In case of `Array` concatenates the inputs into a single array. * * @example * import * as A from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * A.alt(() => [4, 5]) * ), * [1, 2, 3, 4, 5] * ) * * @category error handling * @since 2.0.0 */ export const alt: (that: LazyArg>) => (fa: Array) => Array = altW /** * Same as [`filter`](#filter), but passing also the index to the iterating function. * * @example * import { filterWithIndex } from 'fp-ts/Array'; * * const f = (index: number, x: number) => x > 0 && index <= 2; * assert.deepStrictEqual(filterWithIndex(f)([-3, 1, -2, 5]), [1]); * * @category filtering * @since 2.0.0 */ export const filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (as: Array) => Array (predicateWithIndex: PredicateWithIndex): (bs: Array) => Array (predicateWithIndex: PredicateWithIndex): (as: Array) => Array } = (predicateWithIndex: PredicateWithIndex) => (as: Array): Array => as.filter((b, i) => predicateWithIndex(i, b)) /** * Given an iterating function that takes `Array` as input, `extend` returns * an array containing the results of the iterating function applied to the whole input * `Array`, then to the input `Array` without the first element, then to the input * `Array` without the first two elements, etc. * * @example * import { extend } from 'fp-ts/Array' * * const f = (a: string[]) => a.join(","); * assert.deepStrictEqual(extend(f)(["a", "b", "c"]), ["a,b,c", "b,c", "c"]); * * @since 2.0.0 */ export const extend: (f: (as: Array) => B) => (as: Array) => Array = (f) => (wa) => wa.map((_, i) => f(wa.slice(i))) /** * `duplicate` returns an array containing the whole input `Array`, * then to the input `Array` dropping the first element, then to the input * `Array` dropping the first two elements, etc. * * @example * import { duplicate } from 'fp-ts/Array' * * assert.deepStrictEqual(duplicate(["a", "b", "c"]), [["a", "b", "c"], ["b", "c"], ["c"]]); * * @since 2.0.0 */ export const duplicate: (wa: Array) => Array> = /*#__PURE__*/ extend(identity) /** * Map and fold an `Array`. * Map the `Array` passing each value to the iterating function. * Then fold the results using the provided `Monoid`. * * @example * import { foldMap } from 'fp-ts/Array' * * const monoid = { concat: (a: string, b: string) => a + b, empty: "" }; * const f = (s: string) => s.toUpperCase() * assert.deepStrictEqual(foldMap(monoid)(f)(["a", "b", "c"]), "ABC"); * * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Array) => M = RA.foldMap /** * Same as [`foldMap`](#foldMap) but passing also the index to the iterating function. * * @example * import { foldMapWithIndex } from 'fp-ts/Array' * * const monoid = { concat: (a: string, b: string) => a + b, empty: "" }; * const f = (index:number, s: string) => `${s.toUpperCase()}(${index})` * assert.deepStrictEqual(foldMapWithIndex(monoid)(f)(["a", "b", "c"]), "A(0)B(1)C(2)"); * * @category folding * @since 2.0.0 */ export const foldMapWithIndex: (M: Monoid) => (f: (i: number, a: A) => M) => (fa: Array) => M = RA.foldMapWithIndex /** * Reduces an `Array`. * * `reduce` executes the supplied iterating function on each element of the array, * in order, passing in the element and the return value from the calculation on the preceding element. * * The first time that the iterating function is called there is no "return value of the * previous calculation", the initial value is used in its place. * * @example * import { reduce } from 'fp-ts/Array' * * assert.deepStrictEqual(reduce(5, (acc: number, cur: number) => acc * cur)([2, 3]), 5 * 2 * 3); * * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Array) => B = RA.reduce /** * Same as [`reduce`](#reduce) but passing also the index to the iterating function. * * @example * import { reduceWithIndex } from 'fp-ts/Array' * * const f = (index: number, acc: string, cur: unknown) => * acc + (typeof cur === "string" ? cur.toUpperCase() + index : ""); * assert.deepStrictEqual(reduceWithIndex("", f)([2, "a", "b", null]), "A1B2"); * * @category folding * @since 2.0.0 */ export const reduceWithIndex: (b: B, f: (i: number, b: B, a: A) => B) => (fa: Array) => B = RA.reduceWithIndex /** * Same as [`reduce`](#reduce) but applied from the end to the start. * * *Note*: the iterating function in this case takes the accumulator as the last argument. * * @example * import { reduceRight } from 'fp-ts/Array' * * assert.deepStrictEqual(reduceRight("", (cur: string, acc: string) => acc + cur)(["a", "b", "c"]), "cba"); * * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Array) => B = RA.reduceRight /** * Same as [`reduceRight`](#reduceRight) but passing also the index to the iterating function. * * @example * import { reduceRightWithIndex } from 'fp-ts/Array' * * const f = (index: number, cur: unknown, acc: string) => * acc + (typeof cur === "string" ? cur.toUpperCase() + index : ""); * assert.deepStrictEqual(reduceRightWithIndex("", f)([2, "a", "b", null]), "B2A1"); * * @category folding * @since 2.0.0 */ export const reduceRightWithIndex: (b: B, f: (i: number, a: A, b: B) => B) => (fa: Array) => B = RA.reduceRightWithIndex /** * Given an iterating function that returns a `HKT` (higher kinded type), `traverse` * applies the iterating function to each element of the `Array` and then [`sequence`](#sequence)-s * the results using the provided `Applicative`. * * E.g. suppose you have an `Array` and you want to format each element with a function * that returns a result or an error as `f = (a: A) => Either`, using `traverse` * you can apply `f` to all elements and directly obtain as a result an `Either>` * i.e. an `Array` if all the results are `B`, or an `Error` if some of the results * are `Error`s. * * @example * import { traverse } from 'fp-ts/Array' * import { Applicative, left, right } from "fp-ts/Either"; * * const f = (x: unknown) => * typeof x === "string" ? right(x.toUpperCase()) : left(new Error("not a string")); * assert.deepStrictEqual(traverse(Applicative)(f)(["a", "b"]), right(["A", "B"])); * assert.deepStrictEqual(traverse(Applicative)(f)(["a", 5]), left(new Error("not a string"))); * * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT) => (ta: Array) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (f) => traverseWithIndexF((_, a) => f(a)) } /** * `sequence` takes an `Array` where elements are `HKT` (higher kinded type) and, * using an applicative of that `HKT`, returns an `HKT` of `Array`. * E.g. it can turn an `Array>` into an `Either>`. * * `sequence` requires an `Applicative` of the `HKT` you are targeting, e.g. to turn an * `Array>` into an `Either>`, it needs an * `Applicative` for `Either`, to to turn an `Array>` into an `Option>`, * it needs an `Applicative` for `Option`. * * @example * import { sequence } from 'fp-ts/Array' * import { Applicative, left, right } from "fp-ts/Either"; * * assert.deepStrictEqual(sequence(Applicative)([right("a"), right("b")]), right(["a", "b"])); * assert.deepStrictEqual( * sequence(Applicative)([right("a"), left(new Error("not a string"))]), * left(new Error("not a string")) * ); * * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = (F: ApplicativeHKT) => (ta: Array>): HKT> => { return _reduce(ta, F.of(zero()), (fas, fa) => F.ap( F.map(fas, (as) => (a: A) => pipe(as, append(a))), fa ) ) } /** * Same as [`traverse`](#traverse) but passing also the index to the iterating function. * * @example * import { traverseWithIndex } from 'fp-ts/Array' * import { Applicative, left, right } from "fp-ts/Either"; * * const f = (index:number, x:unknown) => * typeof x === "string" ? right(x.toUpperCase() + index) : left(new Error("not a string")); * assert.deepStrictEqual(traverseWithIndex(Applicative)(f)(["a", "b"]), right(["A0", "B1"])); * assert.deepStrictEqual(traverseWithIndex(Applicative)(f)(["a", 5]), left(new Error("not a string"))); * * @category sequencing * @since 2.6.3 */ export const traverseWithIndex: PipeableTraverseWithIndex1 = (F: ApplicativeHKT) => (f: (i: number, a: A) => HKT): ((ta: Array) => HKT>) => reduceWithIndex(F.of(zero()), (i, fbs, a) => F.ap( F.map(fbs, (bs) => (b: B) => pipe(bs, append(b))), f(i, a) ) ) /** * @category filtering * @since 2.6.5 */ export const wither: PipeableWither1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT>) => (fa: Array) => HKT>) => { const _witherF = _wither(F) return (f) => (fa) => _witherF(fa, f) } /** * @category filtering * @since 2.6.5 */ export const wilt: PipeableWilt1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT>) => (fa: Array) => HKT, Array>>) => { const _wiltF = _wilt(F) return (f) => (fa) => _wiltF(fa, f) } /** * `unfold` takes a function `f` which returns an `Option` of a tuple containing an outcome * value and an input for the following iteration. * `unfold` applies `f` to the initial value `b` and then recursively to the second * element of the tuple contained in the returned `option` of the previous * calculation until `f` returns `Option.none`. * * @example * import { unfold } from 'fp-ts/Array' * import { option } from 'fp-ts' * * const f = (n: number) => { * if (n <= 0) return option.none; * const returnValue = n * 2; * const inputForNextRound = n - 1; * return option.some([returnValue, inputForNextRound] as const); * }; * assert.deepStrictEqual(unfold(5, f), [10, 8, 6, 4, 2]); * * @since 2.6.6 */ export const unfold = (b: B, f: (b: B) => Option): Array => { const out: Array = [] let bb: B = b // eslint-disable-next-line no-constant-condition while (true) { const mt = f(bb) if (_.isSome(mt)) { const [a, b] = mt.value out.push(a) bb = b } else { break } } return out } /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Array' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Array } } /** * `getShow` makes a `Show` for an `Array` from a `Show` for * an `A`. * * @example * import { getShow } from 'fp-ts/Array' * * const numShow = { show: (n: number) => (n >= 0 ? `${n}` : `(${-n})`) }; * assert.deepStrictEqual(getShow(numShow).show([-2, -1, 0, 1]), "[(2), (1), 0, 1]"); * * @category instances * @since 2.0.0 */ export const getShow: (S: Show) => Show> = RA.getShow /** * Get a `Semigroup` based on the concatenation of `Array`s. * See also [`getMonoid`](#getMonoid). * * @example * import { getSemigroup } from 'fp-ts/Array' * * const S = getSemigroup(); * assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [1, 2, 2, 3]); * * @category instances * @since 2.10.0 */ export const getSemigroup = (): Semigroup> => ({ concat: (first, second) => first.concat(second) }) /** * Returns a `Monoid` for `Array` based on the concatenation of `Array`s. * * @example * import { getMonoid } from 'fp-ts/Array' * * const M = getMonoid() * assert.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4]) * * @category instances * @since 2.0.0 */ export const getMonoid = (): Monoid> => ({ concat: getSemigroup().concat, empty: [] }) /** * Derives an `Eq` over the `Array` of a given element type from the `Eq` of that type. The derived `Eq` defines two * arrays as equal if all elements of both arrays are compared equal pairwise with the given `E`. In case of arrays of * different lengths, the result is non equality. * * @example * import * as S from 'fp-ts/string' * import { getEq } from 'fp-ts/Array' * * const E = getEq(S.Eq) * assert.strictEqual(E.equals(['a', 'b'], ['a', 'b']), true) * assert.strictEqual(E.equals(['a'], []), false) * * @category instances * @since 2.0.0 */ export const getEq: (E: Eq) => Eq> = RA.getEq /** * Derives an `Ord` over the `Array` of a given element type from the `Ord` of that type. The ordering between two such * arrays is equal to: the first non equal comparison of each arrays elements taken pairwise in increasing order, in * case of equality over all the pairwise elements; the longest array is considered the greatest, if both arrays have * the same length, the result is equality. * * @example * import { getOrd } from 'fp-ts/Array' * import * as S from 'fp-ts/string' * * const O = getOrd(S.Ord) * assert.strictEqual(O.compare(['b'], ['a']), 1) * assert.strictEqual(O.compare(['a'], ['a']), 0) * assert.strictEqual(O.compare(['a'], ['b']), -1) * * @category instances * @since 2.0.0 */ export const getOrd: (O: Ord) => Ord> = RA.getOrd /** * Get a `Semigroup` based on the union of the elements of `Array`s. * Elements which equal according to the provided `Eq` are included * only once in the result. * See also [`getUnionMonoid`](#getUnionMonoid). * * @example * import { getUnionSemigroup } from 'fp-ts/Array'; * import { Eq } from 'fp-ts/number'; * * const S = getUnionSemigroup(Eq); * assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [1, 2, 3]); * * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq): Semigroup> => { const unionE = union(E) return { concat: (first, second) => unionE(second)(first) } } /** * Get a `Monoid` based on the union of the elements of `Array`s. * Elements which equal according to the provided `Eq` are included * only once in the result. * * @example * import { getUnionMonoid } from 'fp-ts/Array' * import { Eq } from 'fp-ts/number'; * * const M = getUnionMonoid(Eq); * assert.deepStrictEqual(M.concat([1, 2], [2, 3]), [1, 2, 3]); * assert.deepStrictEqual(M.empty,[]); * * @category instances * @since 2.11.0 */ export const getUnionMonoid = (E: Eq): Monoid> => ({ concat: getUnionSemigroup(E).concat, empty: [] }) /** * Get a `Semigroup` based on the intersection of the elements of `Array`s. * Only elements present in the two arrays which are equal according to the * provided `Eq` are included in the result. * * @example * import { getIntersectionSemigroup } from 'fp-ts/Array' * import { Eq } from 'fp-ts/number'; * * const S = getIntersectionSemigroup(Eq); * assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [2]); * * @category instances * @since 2.11.0 */ export const getIntersectionSemigroup = (E: Eq): Semigroup> => { const intersectionE = intersection(E) return { concat: (first, second) => intersectionE(second)(first) } } /** * Get a `Magma` for `Array` where the `concat` function is the differnce between * the first and the second array, i.e. the result contains all the elements of the * first array for which their is no equal element in the second array according * to the `Eq` provided. * * * @example * import { getDifferenceMagma } from 'fp-ts/Array' * import { Eq } from 'fp-ts/number'; * * const S = getDifferenceMagma(Eq); * assert.deepStrictEqual(S.concat([1, 2], [2, 3]), [1]); * * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (E: Eq): Magma> => { const differenceE = difference(E) return { concat: (first, second) => differenceE(second)(first) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Given an input an `Array` of functions, `flap` returns an `Array` containing * the results of applying each function to the given input. * * @example * import { flap } from 'fp-ts/Array' * * const funs = [ * (n: number) => `Double: ${n * 2}`, * (n: number) => `Triple: ${n * 3}`, * (n: number) => `Square: ${n * n}`, * ]; * assert.deepStrictEqual(flap(4)(funs), ['Double: 8', 'Triple: 12', 'Square: 16']); * * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.7.0 */ export const FunctorWithIndex: FunctorWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.5.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.5.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as A from 'fp-ts/Array' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * A.chainFirst(() => ['a', 'b']) * ), * [1, 1, 2, 2, 3, 3] * ) * assert.deepStrictEqual( * pipe( * [1, 2, 3], * A.chainFirst(() => []) * ), * [] * ) * * @category sequencing * @since 2.0.0 */ export const chainFirst: (f: (a: A) => Array) => (first: Array) => Array = /*#__PURE__*/ chainFirst_(Chain) /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Unfoldable: Unfoldable1 = { URI, unfold } /** * @category instances * @since 2.7.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.11.0 */ export const Zero: Zero1 = { URI, zero } /** * @category do notation * @since 2.11.0 */ export const guard = /*#__PURE__*/ guard_(Zero, Pointed) /** * @category instances * @since 2.7.0 */ export const Alternative: Alternative1 = { URI, map: _map, ap: _ap, of, alt: _alt, zero } /** * @category instances * @since 2.7.0 */ export const Extend: Extend1 = { URI, map: _map, extend: _extend } /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category instances * @since 2.7.0 */ export const FilterableWithIndex: FilterableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const FoldableWithIndex: FoldableWithIndex1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.7.0 */ export const TraversableWithIndex: TraversableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverse: _traverse, sequence, traverseWithIndex: _traverseWithIndex } const _wither: Witherable1['wither'] = /*#__PURE__*/ witherDefault(Traversable, Compactable) const _wilt: Witherable1['wilt'] = /*#__PURE__*/ wiltDefault(Traversable, Compactable) /** * @category instances * @since 2.7.0 */ export const Witherable: Witherable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, wither: _wither, wilt: _wilt } /** * @category sequencing * @since 2.11.0 */ export const chainRecDepthFirst: (f: (a: A) => Array>) => (a: A) => Array = RA.chainRecDepthFirst as any /** * @category instances * @since 2.11.0 */ export const ChainRecDepthFirst: ChainRec1 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRecDepthFirst } /** * @category sequencing * @since 2.11.0 */ export const chainRecBreadthFirst: (f: (a: A) => Array>) => (a: A) => Array = RA.chainRecBreadthFirst as any /** * @category instances * @since 2.11.0 */ export const ChainRecBreadthFirst: ChainRec1 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRecBreadthFirst } /** * Filter values inside a context. * * @since 2.11.0 */ export const filterE = /*#__PURE__*/ filterE_(Witherable) /** * @category instances * @since 2.11.0 */ export const FromEither: FromEither1 = { URI, fromEither } /** * @category lifting * @since 2.11.0 */ export const fromEitherK: , B>( f: (...a: A) => Either ) => (...a: A) => Array = /*#__PURE__*/ fromEitherK_(FromEither) // ------------------------------------------------------------------------------------- // unsafe // ------------------------------------------------------------------------------------- /** * @category unsafe * @since 2.0.0 */ export const unsafeInsertAt: (i: number, a: A, as: Array) => NonEmptyArray = NEA.unsafeInsertAt /** * @category unsafe * @since 2.0.0 */ export const unsafeUpdateAt = (i: number, a: A, as: Array): Array => isNonEmpty(as) ? NEA.unsafeUpdateAt(i, a, as) : [] /** * @category unsafe * @since 2.0.0 */ export const unsafeDeleteAt = (i: number, as: Array): Array => { const xs = as.slice() xs.splice(i, 1) return xs } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * `every` tells if the provided predicate holds true for every element in the `Array`. * * @example * import { every } from 'fp-ts/Array' * * assert.equal(every((x: number) => x >= 0)([1, 2, 3]), true); * assert.equal(every((x: number) => x >= 0)([-1, 2, 3]), false); * * @since 2.9.0 */ export const every: { (refinement: Refinement): Refinement, Array> (predicate: Predicate): Predicate> } = RA.every as any /** * `some` tells if the provided predicate holds true at least for one element in the `Array`. * * @example * import { some } from 'fp-ts/Array' * * assert.equal(some((x: number) => x >= 0)([1, 2, 3]), true); * assert.equal(some((x: number) => x >= 10)([1, 2, 3]), false); * * @since 2.9.0 */ export const some = (predicate: Predicate) => (as: Array): as is NonEmptyArray => as.some(predicate) /** * Alias of [`some`](#some) * * @since 2.11.0 */ export const exists: (predicate: Predicate) => (as: Array) => as is NEA.NonEmptyArray = some /** * Places an element in between members of an `Array`, then folds the results using the provided `Monoid`. * * @example * import * as S from 'fp-ts/string' * import { intercalate } from 'fp-ts/Array' * * assert.deepStrictEqual(intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c') * * @since 2.12.0 */ export const intercalate: (M: Monoid) => (middle: A) => (as: Array) => A = RA.intercalate // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: Array<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ bind_(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Array) => (ma: Array) => Array = flatMap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `NonEmptyArray` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const range = NEA.range /** * Use a new `[]` instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const empty: Array = [] /** * Use `prepend` instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const cons = NEA.cons /** * Use `append` instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const snoc = NEA.snoc /** * Use `prependAll` instead * * @category zone of death * @since 2.9.0 * @deprecated */ export const prependToAll = prependAll /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `A.Functor` instead of `A.array` * (where `A` is from `import A from 'fp-ts/Array'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const array: FunctorWithIndex1 & Monad1 & Unfoldable1 & Alternative1 & Extend1 & FilterableWithIndex1 & FoldableWithIndex1 & TraversableWithIndex1 & Witherable1 = { URI, compact, separate, map: _map, ap: _ap, of, chain: flatMap, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, mapWithIndex: _mapWithIndex, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex, alt: _alt, zero, unfold, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverseWithIndex: _traverseWithIndex, extend: _extend, wither: _wither, wilt: _wilt } ================================================ FILE: src/Bifunctor.ts ================================================ /** * @since 2.0.0 */ import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Bifunctor { readonly URI: F readonly bimap: (fea: HKT2, f: (e: E) => G, g: (a: A) => B) => HKT2 readonly mapLeft: (fea: HKT2, f: (e: E) => G) => HKT2 } /** * @category model * @since 2.0.0 */ export interface Bifunctor2 { readonly URI: F readonly bimap: (fea: Kind2, f: (e: E) => G, g: (a: A) => B) => Kind2 readonly mapLeft: (fea: Kind2, f: (e: E) => G) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Bifunctor2C { readonly URI: F readonly _E: E readonly bimap: (fea: Kind2, f: (e: E) => G, g: (a: A) => B) => Kind2 readonly mapLeft: (fea: Kind2, f: (e: E) => M) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Bifunctor3 { readonly URI: F readonly bimap: (fea: Kind3, f: (e: E) => G, g: (a: A) => B) => Kind3 readonly mapLeft: (fea: Kind3, f: (e: E) => G) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Bifunctor3C { readonly URI: F readonly _E: E readonly bimap: (fea: Kind3, f: (e: E) => G, g: (a: A) => B) => Kind3 readonly mapLeft: (fea: Kind3, f: (e: E) => G) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Bifunctor4 { readonly URI: F readonly bimap: (fea: Kind4, f: (e: E) => G, g: (a: A) => B) => Kind4 readonly mapLeft: (fea: Kind4, f: (e: E) => G) => Kind4 } ================================================ FILE: src/BooleanAlgebra.ts ================================================ /** * Boolean algebras are Heyting algebras with the additional constraint that the law of the excluded middle is true * (equivalently, double-negation is true). * * Instances should satisfy the following laws in addition to the `HeytingAlgebra` laws: * * - Excluded middle: `a ∨ ¬a <-> 1` * * Boolean algebras generalize classical logic: one is equivalent to "true" and zero is equivalent to "false". * * @since 2.0.0 */ import { getBooleanAlgebra } from './function' import { HeytingAlgebra } from './HeytingAlgebra' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface BooleanAlgebra extends HeytingAlgebra {} // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Every boolean algebras has a dual algebra, which involves reversing one/zero as well as join/meet. * * @since 2.10.0 */ export const reverse = (B: BooleanAlgebra): BooleanAlgebra => ({ meet: (x, y) => B.join(x, y), join: (x, y) => B.meet(x, y), zero: B.one, one: B.zero, implies: (x, y) => B.join(B.not(x), y), not: B.not }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.0.0 */ export const booleanAlgebraVoid: BooleanAlgebra = { meet: () => undefined, join: () => undefined, zero: undefined, one: undefined, implies: () => undefined, not: () => undefined } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`reverse`](#reverse) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getDualBooleanAlgebra = reverse /** * Use [`BooleanAlgebra`](./boolean.ts.html#booleanalgebra) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const booleanAlgebraBoolean: BooleanAlgebra = { meet: (x, y) => x && y, join: (x, y) => x || y, zero: false, one: true, implies: (x, y) => !x || y, not: (x) => !x } /** * Use [`getBooleanAlgebra`](./function.ts.html#getbooleanalgebra) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFunctionBooleanAlgebra: (B: BooleanAlgebra) => () => BooleanAlgebra<(a: A) => B> = getBooleanAlgebra ================================================ FILE: src/Bounded.ts ================================================ /** * The `Bounded` type class represents totally ordered types that have an upper and lower boundary. * * Instances should satisfy the following law in addition to the `Ord` laws: * * - Bounded: `bottom <= a <= top` * * @since 2.0.0 */ import * as O from './Ord' import Ord = O.Ord // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Bounded extends Ord { readonly top: A readonly bottom: A } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Clamp a value between bottom and top values. * * @category utils * @since 2.12.0 */ export const clamp = (B: Bounded): ((a: A) => A) => O.clamp(B)(B.bottom, B.top) /** * Reverses the Ord of a bound and swaps top and bottom values. * * @category utils * @since 2.12.0 */ export const reverse = (B: Bounded): Bounded => { const R = O.reverse(B) return { equals: R.equals, compare: R.compare, top: B.bottom, bottom: B.top } } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`Bounded`](./number.ts.html#bounded) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const boundedNumber: Bounded = { equals: O.ordNumber.equals, compare: O.ordNumber.compare, top: Infinity, bottom: -Infinity } ================================================ FILE: src/BoundedDistributiveLattice.ts ================================================ /** * A `BoundedDistributiveLattice` is a lattice that is both bounded and distributive * * @since 2.0.0 */ import { BoundedLattice } from './BoundedLattice' import { DistributiveLattice, getMinMaxDistributiveLattice } from './DistributiveLattice' import { Ord } from './Ord' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface BoundedDistributiveLattice extends BoundedLattice, DistributiveLattice {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export function getMinMaxBoundedDistributiveLattice(O: Ord): (min: A, max: A) => BoundedDistributiveLattice { const L = getMinMaxDistributiveLattice(O) return (min, max) => ({ join: L.join, meet: L.meet, zero: min, one: max }) } ================================================ FILE: src/BoundedJoinSemilattice.ts ================================================ /** * A `BoundedJoinSemilattice` must satisfy the following laws in addition to `JoinSemilattice` laws: * * - `a ∨ 0 <-> a` * * @since 2.0.0 */ import { JoinSemilattice } from './JoinSemilattice' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface BoundedJoinSemilattice extends JoinSemilattice { readonly zero: A } ================================================ FILE: src/BoundedLattice.ts ================================================ /** * A `BoundedLattice` must satisfy the following in addition to `BoundedMeetSemilattice` and `BoundedJoinSemilattice` laws: * * - Absorption law for meet: `a ∧ (a ∨ b) <-> a` * - Absorption law for join: `a ∨ (a ∧ b) <-> a` * * @since 2.0.0 */ import { BoundedJoinSemilattice } from './BoundedJoinSemilattice' import { BoundedMeetSemilattice } from './BoundedMeetSemilattice' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface BoundedLattice extends BoundedJoinSemilattice, BoundedMeetSemilattice {} ================================================ FILE: src/BoundedMeetSemilattice.ts ================================================ /** * A `BoundedMeetSemilattice` must satisfy the following laws in addition to `MeetSemilattice` laws: * * - `a ∧ 1 <-> a` * * @since 2.0.0 */ import { MeetSemilattice } from './MeetSemilattice' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface BoundedMeetSemilattice extends MeetSemilattice { readonly one: A } ================================================ FILE: src/Category.ts ================================================ /** * @since 2.0.0 */ import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' import { Semigroupoid, Semigroupoid2, Semigroupoid3, Semigroupoid4 } from './Semigroupoid' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Category extends Semigroupoid { readonly id: () => HKT2 } /** * @category model * @since 2.0.0 */ export interface Category2 extends Semigroupoid2 { readonly id: () => Kind2 } /** * @category model * @since 2.0.0 */ export interface Category3 extends Semigroupoid3 { readonly id: () => Kind3 } /** * @category model * @since 2.0.0 */ export interface Category4 extends Semigroupoid4 { readonly id: () => Kind4 } ================================================ FILE: src/Chain.ts ================================================ /** * The `Chain` type class extends the `Apply` type class with a `chain` operation which composes computations in * sequence, using the return value of one computation to determine the next computation. * * Instances must satisfy the following law in addition to the `Apply` laws: * * 1. Associativity: `F.chain(F.chain(fa, afb), bfc) <-> F.chain(fa, a => F.chain(afb(a), bfc))` * * Note. `Apply`'s `ap` can be derived: `(fab, fa) => F.chain(fab, f => F.map(fa, f))` * * @since 2.0.0 */ import { Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C, Apply4 } from './Apply' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Chain extends Apply { readonly chain: (fa: HKT, f: (a: A) => HKT) => HKT } /** * @category model * @since 2.0.0 */ export interface Chain1 extends Apply1 { readonly chain: (fa: Kind, f: (a: A) => Kind) => Kind } /** * @category model * @since 2.0.0 */ export interface Chain2 extends Apply2 { readonly chain: (fa: Kind2, f: (a: A) => Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Chain2C extends Apply2C { readonly chain: (fa: Kind2, f: (a: A) => Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Chain3 extends Apply3 { readonly chain: (fa: Kind3, f: (a: A) => Kind3) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Chain3C extends Apply3C { readonly chain: (fa: Kind3, f: (a: A) => Kind3) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Chain4 extends Apply4 { readonly chain: (fa: Kind4, f: (a: A) => Kind4) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function chainFirst( M: Chain4 ): (f: (a: A) => Kind4) => (first: Kind4) => Kind4 export function chainFirst( M: Chain3 ): (f: (a: A) => Kind3) => (first: Kind3) => Kind3 export function chainFirst( M: Chain3C ): (f: (a: A) => Kind3) => (first: Kind3) => Kind3 export function chainFirst( M: Chain2 ): (f: (a: A) => Kind2) => (first: Kind2) => Kind2 export function chainFirst( M: Chain2C ): (f: (a: A) => Kind2) => (first: Kind2) => Kind2 export function chainFirst( M: Chain1 ): (f: (a: A) => Kind) => (first: Kind) => Kind export function chainFirst(M: Chain): (f: (a: A) => HKT) => (first: HKT) => HKT export function chainFirst(M: Chain): (f: (a: A) => HKT) => (first: HKT) => HKT { const tapM = tap(M) return (f) => (first) => tapM(first, f) } /** @internal */ export function tap( M: Chain4 ): ( first: Kind4, f: (a: A) => Kind4 ) => Kind4 /** @internal */ export function tap( M: Chain3 ): (first: Kind3, f: (a: A) => Kind3) => Kind3 /** @internal */ export function tap( M: Chain2 ): (first: Kind2, f: (a: A) => Kind2) => Kind2 /** @internal */ export function tap(M: Chain1): (first: Kind, f: (a: A) => Kind) => Kind /** @internal */ export function tap(M: Chain): (first: HKT, f: (a: A) => HKT) => HKT /** @internal */ export function tap(M: Chain): (first: HKT, f: (a: A) => HKT) => HKT { return (first, f) => M.chain(first, (a) => M.map(f(a), () => a)) } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function bind( M: Chain4 ): ( name: Exclude, f: (a: A) => Kind4 ) => (ma: Kind4) => Kind4 export function bind( M: Chain3 ): ( name: Exclude, f: (a: A) => Kind3 ) => (ma: Kind3) => Kind3 export function bind( M: Chain3C ): ( name: Exclude, f: (a: A) => Kind3 ) => (ma: Kind3) => Kind3 export function bind( M: Chain2 ): ( name: Exclude, f: (a: A) => Kind2 ) => (ma: Kind2) => Kind2 export function bind( M: Chain2C ): ( name: Exclude, f: (a: A) => Kind2 ) => (ma: Kind2) => Kind2 export function bind( M: Chain1 ): ( name: Exclude, f: (a: A) => Kind ) => (ma: Kind) => Kind export function bind( M: Chain ): ( name: Exclude, f: (a: A) => HKT ) => (ma: HKT) => HKT export function bind( M: Chain ): ( name: Exclude, f: (a: A) => HKT ) => (ma: HKT) => HKT { return (name, f) => (ma) => M.chain(ma, (a) => M.map(f(a), (b) => Object.assign({}, a, { [name]: b }) as any)) } ================================================ FILE: src/ChainRec.ts ================================================ /** * @since 2.0.0 */ import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4 } from './Chain' import { Either } from './Either' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface ChainRec extends Chain { readonly chainRec: (a: A, f: (a: A) => HKT>) => HKT } /** * @category model * @since 2.0.0 */ export interface ChainRec1 extends Chain1 { readonly chainRec: (a: A, f: (a: A) => Kind>) => Kind } /** * @category model * @since 2.0.0 */ export interface ChainRec2 extends Chain2 { readonly chainRec: (a: A, f: (a: A) => Kind2>) => Kind2 } /** * @category model * @since 2.0.0 */ export interface ChainRec2C extends Chain2C { readonly chainRec: (a: A, f: (a: A) => Kind2>) => Kind2 } /** * @category model * @since 2.0.0 */ export interface ChainRec3 extends Chain3 { readonly chainRec: (a: A, f: (a: A) => Kind3>) => Kind3 } /** * @category model * @since 2.10.0 */ export interface ChainRec3C extends Chain3C { readonly chainRec: (a: A, f: (a: A) => Kind3>) => Kind3 } /** * @category model * @since 2.10.0 */ export interface ChainRec4 extends Chain4 { readonly chainRec: (a: A, f: (a: A) => Kind4>) => Kind4 } /** * @since 2.0.0 */ export const tailRec = (startWith: A, f: (a: A) => Either): B => { let ab = f(startWith) while (ab._tag === 'Left') { ab = f(ab.left) } return ab.right } ================================================ FILE: src/Choice.ts ================================================ /** * The `Choice` class extends `Profunctor` with combinators for working with * sum types. * * `left` and `right` lift values in a `Profunctor` to act on the `Left` and * `Right` components of a sum, respectively. * * Looking at `Choice` through the intuition of inputs and outputs * yields the following type signature: * * ```purescript * left :: forall input output a. p input output -> p (Either input a) (Either output a) * right :: forall input output a. p input output -> p (Either a input) (Either a output) * ``` * * If we specialize the profunctor `p` to the `function` arrow, we get the following type * signatures: * * ```purescript * left :: forall input output a. (input -> output) -> (Either input a) -> (Either output a) * right :: forall input output a. (input -> output) -> (Either a input) -> (Either a output) * ``` * * When the `profunctor` is `Function` application, `left` allows you to map a function over the * left side of an `Either`, and `right` maps it over the right side (same as `map` would do). * * Adapted from https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Choice.purs * * @since 2.0.0 */ import { Category, Category2, Category3, Category4 } from './Category' import { Either } from './Either' import { identity } from './function' import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' import { Profunctor, Profunctor2, Profunctor3, Profunctor4 } from './Profunctor' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Choice extends Profunctor { readonly left: (pab: HKT2) => HKT2, Either> readonly right: (pbc: HKT2) => HKT2, Either> } /** * @category model * @since 2.0.0 */ export interface Choice2 extends Profunctor2 { readonly left: (pab: Kind2) => Kind2, Either> readonly right: (pbc: Kind2) => Kind2, Either> } /** * @category model * @since 2.0.0 */ export interface Choice3 extends Profunctor3 { readonly left: (pab: Kind3) => Kind3, Either> readonly right: (pbc: Kind3) => Kind3, Either> } /** * @category model * @since 2.0.0 */ export interface Choice4 extends Profunctor4 { readonly left: (pab: Kind4) => Kind4, Either> readonly right: (pbc: Kind4) => Kind4, Either> } /** * Compose a value acting on a sum from two values, each acting on one of * the components of the sum. * * Specializing `split` to function application would look like this: * * ```purescript * split :: forall a b c d. (a -> b) -> (c -> d) -> (Either a c) -> (Either b d) * ``` * * We take two functions, `f` and `g`, and we transform them into a single function which * takes an `Either`and maps `f` over the left side and `g` over the right side. Just like * `bimap` would do for the `Bifunctor` instance of `Either`. * * @since 2.10.0 */ export function split

( P: Choice4

, C: Category4

): ( pab: Kind4, pcd: Kind4 ) => Kind4, Either> export function split

( P: Choice3

, C: Category3

): (pab: Kind3, pcd: Kind3) => Kind3, Either> export function split

( P: Choice2

, C: Category2

): (pab: Kind2, pcd: Kind2) => Kind2, Either> export function split

( P: Choice

, C: Category

): (pab: HKT2, pcd: HKT2) => HKT2, Either> export function split

( P: Choice

, C: Category

): (pab: HKT2, pcd: HKT2) => HKT2, Either> { return (pab: HKT2, pcd: HKT2) => C.compose(P.right(pcd), P.left(pab)) } /** * Compose a value which eliminates a sum from two values, each eliminating * one side of the sum. * * This combinator is useful when assembling values from smaller components, * because it provides a way to support two different types of input. * * Specializing `fanIn` to function application would look like this: * * ```purescript * fanIn :: forall a b c d. (a -> c) -> (b -> c) -> Either a b -> c * ``` * * We take two functions, `f` and `g`, which both return the same type `c` and we transform them into a * single function which takes an `Either` value with the parameter type of `f` on the left side and * the parameter type of `g` on the right side. The function then runs either `f` or `g`, depending on * whether the `Either` value is a `Left` or a `Right`. * This allows us to bundle two different computations which both have the same result type into one * function which will run the appropriate computation based on the parameter supplied in the `Either` value. * * @since 2.10.0 */ export function fanIn

( P: Choice4

, C: Category4

): (pac: Kind4, pbc: Kind4) => Kind4, C> export function fanIn

( P: Choice3

, C: Category3

): (pac: Kind3, pbc: Kind3) => Kind3, C> export function fanIn

( P: Choice2

, C: Category2

): (pac: Kind2, pbc: Kind2) => Kind2, C> export function fanIn

( P: Choice

, C: Category

): (pac: HKT2, pbc: HKT2) => HKT2, C> export function fanIn

( P: Choice

, C: Category

): (pac: HKT2, pbc: HKT2) => HKT2, C> { const splitPC = split(P, C) return (pac: HKT2, pbc: HKT2): HKT2, C> => C.compose( P.promap(C.id(), (cc: Either) => (cc._tag === 'Left' ? cc.left : cc.right), identity), splitPC(pac, pbc) ) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`split`](#split) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function splitChoice( F: Category3 & Choice3 ): (pab: Kind3, pcd: Kind3) => Kind3, Either> /** @deprecated */ export function splitChoice( F: Category2 & Choice2 ): (pab: Kind2, pcd: Kind2) => Kind2, Either> /** @deprecated */ export function splitChoice( F: Category & Choice ): (pab: HKT2, pcd: HKT2) => HKT2, Either> export function splitChoice( F: Category & Choice ): (pab: HKT2, pcd: HKT2) => HKT2, Either> { return split(F, F) } /** * Use [`fanIn`](#fanIn) instead. * * @since 2.0.0 * @deprecated */ export function fanin( F: Category3 & Choice3 ): (pac: Kind3, pbc: Kind3) => Kind3, C> /** @deprecated */ export function fanin( F: Category2 & Choice2 ): (pac: Kind2, pbc: Kind2) => Kind2, C> /** @deprecated */ export function fanin( F: Category & Choice ): (pac: HKT2, pbc: HKT2) => HKT2, C> export function fanin( F: Category & Choice ): (pac: HKT2, pbc: HKT2) => HKT2, C> { return fanIn(F, F) } ================================================ FILE: src/Comonad.ts ================================================ /** * @since 2.0.0 */ import { Extend, Extend1, Extend2, Extend2C, Extend3, Extend3C, Extend4 } from './Extend' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Comonad extends Extend { readonly extract: (wa: HKT) => A } /** * @category model * @since 2.0.0 */ export interface Comonad1 extends Extend1 { readonly extract: (wa: Kind) => A } /** * @category model * @since 2.0.0 */ export interface Comonad2 extends Extend2 { readonly extract: (wa: Kind2) => A } /** * @category model * @since 2.0.0 */ export interface Comonad2C extends Extend2C { readonly extract: (wa: Kind2) => A } /** * @category model * @since 2.0.0 */ export interface Comonad3 extends Extend3 { readonly extract: (wa: Kind3) => A } /** * @category model * @since 2.10.0 */ export interface Comonad3C extends Extend3C { readonly extract: (wa: Kind3) => A } /** * @category model * @since 2.10.0 */ export interface Comonad4 extends Extend4 { readonly extract: (wa: Kind4) => A } ================================================ FILE: src/Compactable.ts ================================================ /** * `Compactable` represents data structures which can be _compacted_/_filtered_. This is a generalization of * `catOptions` as a new function `compact`. `compact` has relations with `Functor`, `Applicative`, * `Monad`, `Alternative`, and `Traversable` in that we can use these classes to provide the ability to * operate on a data type by eliminating intermediate `None`s. This is useful for representing the filtering out of * values, or failure. * * Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Compactable.purs * * @since 2.0.0 */ import { Either } from './Either' import { pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3C, FunctorComposition, FunctorComposition2C1, FunctorComposition11, FunctorComposition12, FunctorComposition12C, FunctorComposition21, FunctorComposition22, FunctorComposition22C, FunctorComposition23, FunctorComposition23C, getFunctorComposition, map } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { getLeft, getRight, Option } from './Option' import * as S from './Separated' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Compactable { readonly URI: F /** * Compacts a data structure unwrapping inner Option */ readonly compact: (fa: HKT>) => HKT /** * Separates a data structure moving inner Left to the left side and inner Right to the right side of Separated */ readonly separate: (fa: HKT>) => S.Separated, HKT> } /** * @category model * @since 2.0.0 */ export interface Compactable1 { readonly URI: F readonly compact: (fa: Kind>) => Kind readonly separate: (fa: Kind>) => S.Separated, Kind> } /** * @category model * @since 2.0.0 */ export interface Compactable2 { readonly URI: F readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => S.Separated, Kind2> } /** * @category model * @since 2.0.0 */ export interface Compactable2C { readonly URI: F readonly _E: E readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => S.Separated, Kind2> } /** * @category model * @since 2.0.0 */ export interface Compactable3 { readonly URI: F readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => S.Separated, Kind3> } /** * @category model * @since 2.2.0 */ export interface Compactable3C { readonly URI: F readonly _E: E readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => S.Separated, Kind3> } /** * @category model * @since 2.0.0 */ export interface Compactable4 { readonly URI: F readonly compact: (fa: Kind4>) => Kind4 readonly separate: ( fa: Kind4> ) => S.Separated, Kind4> } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `compact` composition. * * @since 2.10.0 */ export function compact( F: Functor2, G: Compactable2C ): (fa: Kind2>>) => Kind2> export function compact( F: Functor1, G: Compactable2C ): (fa: Kind>>) => Kind> export function compact( F: Functor1, G: Compactable1 ): (fa: Kind>>) => Kind> export function compact(F: Functor, G: Compactable): (fa: HKT>>) => HKT> export function compact( F: Functor, G: Compactable ): (fa: HKT>>) => HKT> { return (fga) => F.map(fga, G.compact) } /** * `separate` composition. * * @since 2.10.0 */ export function separate( F: Functor2, C: Compactable2C, G: Functor2 ): ( fge: Kind2>> ) => S.Separated>, Kind2>> export function separate( F: Functor1, C: Compactable2C, G: Functor2 ): (fge: Kind>>) => S.Separated>, Kind>> export function separate( F: Functor1, C: Compactable1, G: Functor1 ): (fge: Kind>>) => S.Separated>, Kind>> export function separate( F: Functor, C: Compactable, G: Functor ): (fge: HKT>>) => S.Separated>, HKT>> export function separate( F: Functor, C: Compactable, G: Functor ): (fge: HKT>>) => S.Separated>, HKT>> { const _compact = compact(F, C) const _map = map(F, G) return (fge) => S.separated(_compact(pipe(fge, _map(getLeft))), _compact(pipe(fge, _map(getRight)))) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition extends FunctorComposition { readonly compact: (fga: HKT>>) => HKT> readonly separate: (fge: HKT>>) => Separated>, HKT>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition11 extends FunctorComposition11 { readonly compact: (fga: Kind>>) => Kind> readonly separate: (fge: Kind>>) => Separated>, Kind>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition12 extends FunctorComposition12 { readonly compact: (fga: Kind>>) => Kind> readonly separate: ( fge: Kind>> ) => Separated>, Kind>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition12C extends FunctorComposition12C { readonly compact: (fga: Kind>>) => Kind> readonly separate: ( fge: Kind>> ) => Separated>, Kind>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition21 extends FunctorComposition21 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition2C1 extends FunctorComposition2C1 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition22 extends FunctorComposition22 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface CompactableComposition22C extends FunctorComposition22C { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface CompactableComposition23 extends FunctorComposition23 { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface CompactableComposition23C extends FunctorComposition23C { readonly compact: (fga: Kind2>>) => Kind2> readonly separate: ( fge: Kind2>> ) => Separated>, Kind2>> } /** * Use [`compact`](#compact) and [`separate`](#separate) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getCompactableComposition( F: Functor2, G: Compactable3C & Functor3C ): CompactableComposition23C /** @deprecated */ export function getCompactableComposition( F: Functor2, G: Compactable2C & Functor2C ): CompactableComposition22C /** @deprecated */ export function getCompactableComposition( F: Functor2, G: Compactable2 & Functor2 ): CompactableComposition22 /** @deprecated */ export function getCompactableComposition( F: Functor2C, G: Compactable1 & Functor1 ): CompactableComposition2C1 /** @deprecated */ export function getCompactableComposition( F: Functor2, G: Compactable1 & Functor1 ): CompactableComposition21 /** @deprecated */ export function getCompactableComposition( F: Functor1, G: Compactable2C & Functor2C ): CompactableComposition12 /** @deprecated */ export function getCompactableComposition( F: Functor1, G: Compactable2 & Functor2 ): CompactableComposition12 /** @deprecated */ export function getCompactableComposition( F: Functor1, G: Compactable1 & Functor1 ): CompactableComposition11 /** @deprecated */ export function getCompactableComposition( F: Functor, G: Compactable & Functor ): CompactableComposition /** @deprecated */ export function getCompactableComposition( F: Functor, G: Compactable & Functor ): CompactableComposition { const map = getFunctorComposition(F, G).map return { map, compact: compact(F, G), separate: separate(F, G, G) } } /** * Use [`Separated`](./Separated.ts.html#separated) instead. * * @since 2.0.0 * @deprecated */ export interface Separated { readonly left: A readonly right: B } ================================================ FILE: src/Console.ts ================================================ /** * @since 2.0.0 */ import { IO } from './IO' /** * @since 2.0.0 */ export const log = (a: A): IO => () => console.log(a) /** * @since 2.0.0 */ export const warn = (a: A): IO => () => console.warn(a) /** * @since 2.0.0 */ export const error = (a: A): IO => () => console.error(a) /** * @since 2.0.0 */ export const info = (a: A): IO => () => console.info(a) ================================================ FILE: src/Const.ts ================================================ /** * The `Const` type constructor, which wraps its first type argument and ignores its second. * That is, `Const` is isomorphic to `E` for any `A`. * * `Const` has some useful instances. For example, the `Applicative` instance allows us to collect results using a `Monoid` * while ignoring return values. * * @since 2.0.0 */ import { Applicative2C } from './Applicative' import { Apply2C } from './Apply' import { Bifunctor2 } from './Bifunctor' import { BooleanAlgebra } from './BooleanAlgebra' import { Bounded } from './Bounded' import { Contravariant2 } from './Contravariant' import { Eq } from './Eq' import { identity, pipe, unsafeCoerce } from './function' import { flap as flap_, Functor2 } from './Functor' import { HeytingAlgebra } from './HeytingAlgebra' import { Monoid } from './Monoid' import { Ord } from './Ord' import { Ring } from './Ring' import { Semigroup } from './Semigroup' import { Semiring } from './Semiring' import { Show } from './Show' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export type Const = E & { readonly _A: A } /** * @category constructors * @since 2.0.0 */ export const make: (e: E) => Const = unsafeCoerce /** * @category instances * @since 2.0.0 */ export function getShow(S: Show): Show> { return { show: (c) => `make(${S.show(c)})` } } /** * @category instances * @since 2.0.0 */ export const getEq: (E: Eq) => Eq> = identity /** * @category instances * @since 2.6.0 */ export const getOrd: (O: Ord) => Ord> = identity /** * @category instances * @since 2.6.0 */ export const getBounded: (B: Bounded) => Bounded> = identity as any /** * @category instances * @since 2.6.0 */ export const getSemigroup: (S: Semigroup) => Semigroup> = identity as any /** * @category instances * @since 2.6.0 */ export const getMonoid: (M: Monoid) => Monoid> = identity as any /** * @category instances * @since 2.6.0 */ export const getSemiring: (S: Semiring) => Semiring> = identity as any /** * @category instances * @since 2.6.0 */ export const getRing: (S: Ring) => Ring> = identity as any /** * @category instances * @since 2.6.0 */ export const getHeytingAlgebra: (H: HeytingAlgebra) => HeytingAlgebra> = identity as any /** * @category instances * @since 2.6.0 */ export const getBooleanAlgebra: (H: BooleanAlgebra) => BooleanAlgebra> = identity as any /** * @category instances * @since 2.0.0 */ export function getApply(S: Semigroup): Apply2C { return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => make(S.concat(fab, fa)) } } /** * @category instances * @since 2.0.0 */ export function getApplicative(M: Monoid): Applicative2C { const A = getApply(M) return { URI, _E: undefined as any, map: A.map, ap: A.ap, of: () => make(M.empty) } } const _contramap: Contravariant2['contramap'] = (fa, f) => pipe(fa, contramap(f)) /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _bimap: Bifunctor2['bimap'] = (fa, f, g) => pipe(fa, bimap(f, g)) /* istanbul ignore next */ const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapLeft(f)) /** * @since 2.0.0 */ export const contramap: (f: (b: B) => A) => (fa: Const) => Const = () => unsafeCoerce /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Const) => Const = () => unsafeCoerce /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.6.2 */ export const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Const) => Const = (f) => (fa) => make(f(fa)) /** * Map a function over the first type argument of a bifunctor. * * @category error handling * @since 2.6.2 */ export const mapLeft: (f: (e: E) => G) => (fa: Const) => Const = (f) => (fa) => make(f(fa)) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Const' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Const } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.7.0 */ export const Contravariant: Contravariant2 = { URI, contramap: _contramap } /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `C.Functor` instead of `C.const_` * (where `C` is from `import C from 'fp-ts/Const'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const const_: Functor2 & Contravariant2 & Bifunctor2 = { URI, map: _map, contramap: _contramap, bimap: _bimap, mapLeft: _mapLeft } ================================================ FILE: src/Contravariant.ts ================================================ /** * @since 2.0.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Contravariant { readonly URI: F readonly contramap: (fa: HKT, f: (b: B) => A) => HKT } /** * @category model * @since 2.0.0 */ export interface Contravariant1 { readonly URI: F readonly contramap: (fa: Kind, f: (b: B) => A) => Kind } /** * @category model * @since 2.0.0 */ export interface Contravariant2 { readonly URI: F readonly contramap: (fa: Kind2, f: (b: B) => A) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Contravariant2C { readonly URI: F readonly _E: E readonly contramap: (fa: Kind2, f: (b: B) => A) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Contravariant3 { readonly URI: F readonly contramap: (fa: Kind3, f: (b: B) => A) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Contravariant3C { readonly URI: F readonly _E: E readonly contramap: (fa: Kind3, f: (b: B) => A) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Contravariant4 { readonly URI: F readonly contramap: (fa: Kind4, f: (b: B) => A) => Kind4 } ================================================ FILE: src/Date.ts ================================================ /** * @since 2.0.0 */ import * as E from './Eq' import { pipe } from './function' import { IO } from './IO' import * as N from './number' import * as O from './Ord' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.10.0 */ export const Eq: E.Eq = { equals: (first, second) => first.valueOf() === second.valueOf() } /** * @category instances * @since 2.6.0 */ export const eqDate: E.Eq = { equals: (x, y) => x.getDate() === y.getDate() } /** * @category instances * @since 2.6.0 */ export const eqMonth: E.Eq = { equals: (x, y) => x.getMonth() === y.getMonth() } /** * @category instances * @since 2.6.0 */ export const eqYear: E.Eq = { equals: (x, y) => x.getFullYear() === y.getFullYear() } /** * @example * import { Ord } from 'fp-ts/Date' * * assert.deepStrictEqual(Ord.compare(new Date(1, 1, 2020), new Date(1, 1, 2021)), -1) * * @category instances * @since 2.10.0 */ export const Ord: O.Ord = /*#__PURE__*/ pipe( N.Ord, /*#__PURE__*/ O.contramap((date) => date.valueOf()) ) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Returns the current `Date` * * @category constructors * @since 2.0.0 */ export const create: IO = () => new Date() /** * Returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC * * @since 2.0.0 */ export const now: IO = () => new Date().getTime() ================================================ FILE: src/DistributiveLattice.ts ================================================ /** * A `DistributiveLattice` must satisfy the following laws in addition to `Lattice` laws: * * - Distributivity for meet: `a ∨ (b ∧ c) <-> (a ∨ b) ∧ (a ∨ c)` * - Distributivity for join: `a ∧ (b ∨ c) <-> (a ∧ b) ∨ (a ∧ c)` * * @since 2.0.0 */ import { Lattice } from './Lattice' import { max, min, Ord } from './Ord' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface DistributiveLattice extends Lattice {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export function getMinMaxDistributiveLattice(O: Ord): DistributiveLattice { return { meet: min(O), join: max(O) } } ================================================ FILE: src/Either.ts ================================================ /** * ```ts * type Either = Left | Right * ``` * * Represents a value of one of two possible types (a disjoint union). * * An instance of `Either` is either an instance of `Left` or `Right`. * * A common use of `Either` is as an alternative to `Option` for dealing with possible missing values. In this usage, * `None` is replaced with a `Left` which can contain useful information. `Right` takes the place of `Some`. Convention * dictates that `Left` is used for failure and `Right` is used for success. * * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * const double = (n: number): number => n * 2 * * export const imperative = (as: ReadonlyArray): string => { * const head = (as: ReadonlyArray): number => { * if (as.length === 0) { * throw new Error('empty array') * } * return as[0] * } * const inverse = (n: number): number => { * if (n === 0) { * throw new Error('cannot divide by zero') * } * return 1 / n * } * try { * return `Result is ${inverse(double(head(as)))}` * } catch (err: any) { * return `Error is ${err.message}` * } * } * * export const functional = (as: ReadonlyArray): string => { * const head = (as: ReadonlyArray): E.Either => * as.length === 0 ? E.left('empty array') : E.right(as[0]) * const inverse = (n: number): E.Either => * n === 0 ? E.left('cannot divide by zero') : E.right(1 / n) * return pipe( * as, * head, * E.map(double), * E.flatMap(inverse), * E.match( * (err) => `Error is ${err}`, // onLeft handler * (head) => `Result is ${head}` // onRight handler * ) * ) * } * * assert.deepStrictEqual(imperative([1, 2, 3]), functional([1, 2, 3])) * assert.deepStrictEqual(imperative([]), functional([])) * assert.deepStrictEqual(imperative([0]), functional([0])) * * @since 2.0.0 */ import { Alt2, Alt2C } from './Alt' import { Applicative as ApplicativeHKT, Applicative2, Applicative2C, getApplicativeMonoid } from './Applicative' import { apFirst as apFirst_, Apply2, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import { Bifunctor2 } from './Bifunctor' import * as chainable from './Chain' import { ChainRec2, ChainRec2C, tailRec } from './ChainRec' import { Compactable2C } from './Compactable' import { Eq } from './Eq' import { Extend2 } from './Extend' import { Filterable2C } from './Filterable' import { Foldable2 } from './Foldable' import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, FromEither2, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_ } from './FromEither' import { dual, flow, identity, LazyArg, pipe } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor2, let as let__ } from './Functor' import { HKT } from './HKT' import * as _ from './internal' import { Monad2, Monad2C } from './Monad' import { MonadThrow2, MonadThrow2C } from './MonadThrow' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { Pointed2 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import { PipeableTraverse2, Traversable2 } from './Traversable' import { wiltDefault, Witherable2C, witherDefault } from './Witherable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Left { readonly _tag: 'Left' readonly left: E } /** * @category model * @since 2.0.0 */ export interface Right { readonly _tag: 'Right' readonly right: A } /** * @category model * @since 2.0.0 */ export type Either = Left | Right // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this * structure. * * @category constructors * @since 2.0.0 */ export const left: (e: E) => Either = _.left /** * Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias * of this structure. * * @category constructors * @since 2.0.0 */ export const right: (a: A) => Either = _.right /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => Either): (ma: Either) => Either (ma: Either, f: (a: A) => Either): Either } = /*#__PURE__*/ dual( 2, (ma: Either, f: (a: A) => Either): Either => (isLeft(ma) ? ma : f(ma.right)) ) const _map: Monad2['map'] = (fa, f) => pipe(fa, map(f)) const _ap: Monad2['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _reduce: Foldable2['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable2['foldMap'] = (M) => (fa, f) => { const foldMapM = foldMap(M) return pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable2['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) const _traverse = ( F: ApplicativeHKT ): ((ta: Either, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } const _bimap: Bifunctor2['bimap'] = (fa, f, g) => pipe(fa, bimap(f, g)) const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapLeft(f)) /* istanbul ignore next */ const _alt: Alt2['alt'] = (fa, that) => pipe(fa, alt(that)) /* istanbul ignore next */ const _extend: Extend2['extend'] = (wa, f) => pipe(wa, extend(f)) const _chainRec: ChainRec2['chainRec'] = (a, f) => tailRec(f(a), (e) => isLeft(e) ? right(left(e.left)) : isLeft(e.right) ? left(f(e.right.left)) : right(right(e.right.right)) ) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Either' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Either } } /** * @category instances * @since 2.0.0 */ export const getShow = (SE: Show, SA: Show): Show> => ({ show: (ma) => (isLeft(ma) ? `left(${SE.show(ma.left)})` : `right(${SA.show(ma.right)})`) }) /** * @category instances * @since 2.0.0 */ export const getEq = (EL: Eq, EA: Eq): Eq> => ({ equals: (x, y) => x === y || (isLeft(x) ? isLeft(y) && EL.equals(x.left, y.left) : isRight(y) && EA.equals(x.right, y.right)) }) /** * Semigroup returning the left-most non-`Left` value. If both operands are `Right`s then the inner values are * concatenated using the provided `Semigroup` * * @example * import { getSemigroup, left, right } from 'fp-ts/Either' * import { SemigroupSum } from 'fp-ts/number' * * const S = getSemigroup(SemigroupSum) * assert.deepStrictEqual(S.concat(left('a'), left('b')), left('a')) * assert.deepStrictEqual(S.concat(left('a'), right(2)), right(2)) * assert.deepStrictEqual(S.concat(right(1), left('b')), right(1)) * assert.deepStrictEqual(S.concat(right(1), right(2)), right(3)) * * @category instances * @since 2.0.0 */ export const getSemigroup = (S: Semigroup): Semigroup> => ({ concat: (x, y) => (isLeft(y) ? x : isLeft(x) ? y : right(S.concat(x.right, y.right))) }) /** * Builds a `Compactable` instance for `Either` given `Monoid` for the left side. * * @category filtering * @since 2.10.0 */ export const getCompactable = (M: Monoid): Compactable2C => { const empty = left(M.empty) return { URI, _E: undefined as any, compact: (ma) => (isLeft(ma) ? ma : ma.right._tag === 'None' ? empty : right(ma.right.value)), separate: (ma) => isLeft(ma) ? separated(ma, ma) : isLeft(ma.right) ? separated(right(ma.right.left), empty) : separated(empty, right(ma.right.right)) } } /** * Builds a `Filterable` instance for `Either` given `Monoid` for the left side * * @category filtering * @since 2.10.0 */ export const getFilterable = (M: Monoid): Filterable2C => { const empty = left(M.empty) const { compact, separate } = getCompactable(M) const filter = (ma: Either, predicate: Predicate): Either => isLeft(ma) ? ma : predicate(ma.right) ? ma : empty const partition = (ma: Either, p: Predicate): Separated, Either> => { return isLeft(ma) ? separated(ma, ma) : p(ma.right) ? separated(empty, right(ma.right)) : separated(right(ma.right), empty) } return { URI, _E: undefined as any, map: _map, compact, separate, filter, filterMap: (ma, f) => { if (isLeft(ma)) { return ma } const ob = f(ma.right) return ob._tag === 'None' ? empty : right(ob.value) }, partition, partitionMap: (ma, f) => { if (isLeft(ma)) { return separated(ma, ma) } const e = f(ma.right) return isLeft(e) ? separated(right(e.left), empty) : separated(empty, right(e.right)) } } } /** * Builds `Witherable` instance for `Either` given `Monoid` for the left side * * @category filtering * @since 2.0.0 */ export const getWitherable = (M: Monoid): Witherable2C => { const F_ = getFilterable(M) const C = getCompactable(M) return { URI, _E: undefined as any, map: _map, compact: F_.compact, separate: F_.separate, filter: F_.filter, filterMap: F_.filterMap, partition: F_.partition, partitionMap: F_.partitionMap, traverse: _traverse, sequence, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, wither: witherDefault(Traversable, C), wilt: wiltDefault(Traversable, C) } } /** * The default [`Applicative`](#applicative) instance returns the first error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * @example * import * as A from 'fp-ts/Apply' * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as S from 'fp-ts/Semigroup' * import * as string from 'fp-ts/string' * * const parseString = (u: unknown): E.Either => * typeof u === 'string' ? E.right(u) : E.left('not a string') * * const parseNumber = (u: unknown): E.Either => * typeof u === 'number' ? E.right(u) : E.left('not a number') * * interface Person { * readonly name: string * readonly age: number * } * * const parsePerson = ( * input: Record * ): E.Either => * pipe( * E.Do, * E.apS('name', parseString(input.name)), * E.apS('age', parseNumber(input.age)) * ) * * assert.deepStrictEqual(parsePerson({}), E.left('not a string')) // <= first error * * const Applicative = E.getApplicativeValidation( * pipe(string.Semigroup, S.intercalate(', ')) * ) * * const apS = A.apS(Applicative) * * const parsePersonAll = ( * input: Record * ): E.Either => * pipe( * E.Do, * apS('name', parseString(input.name)), * apS('age', parseNumber(input.age)) * ) * * assert.deepStrictEqual(parsePersonAll({}), E.left('not a string, not a number')) // <= all errors * * @category error handling * @since 2.7.0 */ export const getApplicativeValidation = (SE: Semigroup): Applicative2C => ({ URI, _E: undefined as any, map: _map, ap: (fab, fa) => isLeft(fab) ? isLeft(fa) ? left(SE.concat(fab.left, fa.left)) : fab : isLeft(fa) ? fa : right(fab.right(fa.right)), of }) /** * The default [`Alt`](#alt) instance returns the last error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as S from 'fp-ts/Semigroup' * import * as string from 'fp-ts/string' * * const parseString = (u: unknown): E.Either => * typeof u === 'string' ? E.right(u) : E.left('not a string') * * const parseNumber = (u: unknown): E.Either => * typeof u === 'number' ? E.right(u) : E.left('not a number') * * const parse = (u: unknown): E.Either => * pipe( * parseString(u), * E.alt(() => parseNumber(u)) * ) * * assert.deepStrictEqual(parse(true), E.left('not a number')) // <= last error * * const Alt = E.getAltValidation(pipe(string.Semigroup, S.intercalate(', '))) * * const parseAll = (u: unknown): E.Either => * Alt.alt(parseString(u), () => parseNumber(u)) * * assert.deepStrictEqual(parseAll(true), E.left('not a string, not a number')) // <= all errors * * @category error handling * @since 2.7.0 */ export const getAltValidation = (SE: Semigroup): Alt2C => ({ URI, _E: undefined as any, map: _map, alt: (me, that) => { if (isRight(me)) { return me } const ea = that() return isLeft(ea) ? left(SE.concat(me.left, ea.left)) : ea } }) /** * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Either) => Either = (f) => (fa) => isLeft(fa) ? fa : right(f(fa.right)) /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * Maps the `Right` value of this `Either` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: Either) => Either (self: Either, a: A): Either } = dual(2, as_(Functor)) /** * Maps the `Right` value of this `Either` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: Either) => Either = asUnit_(Functor) /** * @category constructors * @since 2.7.0 */ export const of: (a: A) => Either = right /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.8.0 */ export const apW: (fa: Either) => (fab: Either B>) => Either = (fa) => (fab) => isLeft(fab) ? fab : isLeft(fa) ? fa : right(fab.right(fa.right)) /** * @since 2.0.0 */ export const ap: (fa: Either) => (fab: Either B>) => Either = apW /** * @category instances * @since 2.10.0 */ export const Apply: Apply2 = { URI, map: _map, ap: _ap } /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative2 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad2 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * Left-associative fold of a structure. * * @example * import { pipe } from 'fp-ts/function' * import * as E from 'fp-ts/Either' * * const startWith = 'prefix' * const concat = (a: string, b: string) => `${a}:${b}` * * assert.deepStrictEqual( * pipe(E.right('a'), E.reduce(startWith, concat)), * 'prefix:a' * ) * * assert.deepStrictEqual( * pipe(E.left('e'), E.reduce(startWith, concat)), * 'prefix' * ) * * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Either) => B = (b, f) => (fa) => isLeft(fa) ? b : f(b, fa.right) /** * Map each element of the structure to a monoid, and combine the results. * * @example * import { pipe } from 'fp-ts/function' * import * as E from 'fp-ts/Either' * import * as S from 'fp-ts/string' * * const yell = (a: string) => `${a}!` * * assert.deepStrictEqual( * pipe(E.right('a'), E.foldMap(S.Monoid)(yell)), * 'a!' * ) * * assert.deepStrictEqual( * pipe(E.left('e'), E.foldMap(S.Monoid)(yell)), * S.Monoid.empty * ) * * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Either) => M = (M) => (f) => (fa) => isLeft(fa) ? M.empty : f(fa.right) /** * Right-associative fold of a structure. * * @example * import { pipe } from 'fp-ts/function' * import * as E from 'fp-ts/Either' * * const startWith = 'postfix' * const concat = (a: string, b: string) => `${a}:${b}` * * assert.deepStrictEqual( * pipe(E.right('a'), E.reduceRight(startWith, concat)), * 'a:postfix' * ) * * assert.deepStrictEqual( * pipe(E.left('e'), E.reduceRight(startWith, concat)), * 'postfix' * ) * * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Either) => B = (b, f) => (fa) => isLeft(fa) ? b : f(fa.right, b) /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable2 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * Map each element of a structure to an action, evaluate these actions from left to right, and collect the results. * * @example * import { pipe } from 'fp-ts/function' * import * as RA from 'fp-ts/ReadonlyArray' * import * as E from 'fp-ts/Either' * import * as O from 'fp-ts/Option' * * assert.deepStrictEqual( * pipe(E.right(['a']), E.traverse(O.Applicative)(RA.head)), * O.some(E.right('a')) * ) * * assert.deepStrictEqual( * pipe(E.right([]), E.traverse(O.Applicative)(RA.head)), * O.none * ) * * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse2 = (F: ApplicativeHKT) => (f: (a: A) => HKT) => (ta: Either): HKT> => isLeft(ta) ? F.of(left(ta.left)) : F.map>(f(ta.right), right) /** * Evaluate each monadic action in the structure from left to right, and collect the results. * * @example * import { pipe } from 'fp-ts/function' * import * as E from 'fp-ts/Either' * import * as O from 'fp-ts/Option' * * assert.deepStrictEqual( * pipe(E.right(O.some('a')), E.sequence(O.Applicative)), * O.some(E.right('a')) * ) * * assert.deepStrictEqual( * pipe(E.right(O.none), E.sequence(O.Applicative)), * O.none * ) * * @category traversing * @since 2.6.3 */ export const sequence: Traversable2['sequence'] = (F: ApplicativeHKT) => (ma: Either>): HKT> => { return isLeft(ma) ? F.of(left(ma.left)) : F.map>(ma.right, right) } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable2 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.0.0 */ export const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Either) => Either = (f, g) => (fa) => isLeft(fa) ? left(f(fa.left)) : right(g(fa.right)) /** * Map a function over the first type argument of a bifunctor. * * @category error handling * @since 2.0.0 */ export const mapLeft: (f: (e: E) => G) => (fa: Either) => Either = (f) => (fa) => isLeft(fa) ? left(f(fa.left)) : fa /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the error and the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW: (that: LazyArg>) => (fa: Either) => Either = (that) => (fa) => isLeft(fa) ? that() : fa /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * In case of `Either` returns the left-most non-`Left` value (or the right-most `Left` value if both values are `Left`). * * | x | y | pipe(x, alt(() => y) | * | -------- | -------- | -------------------- | * | left(a) | left(b) | left(b) | * | left(a) | right(2) | right(2) | * | right(1) | left(b) | right(1) | * | right(1) | right(2) | right(1) | * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * E.left('a'), * E.alt(() => E.left('b')) * ), * E.left('b') * ) * assert.deepStrictEqual( * pipe( * E.left('a'), * E.alt(() => E.right(2)) * ), * E.right(2) * ) * assert.deepStrictEqual( * pipe( * E.right(1), * E.alt(() => E.left('b')) * ), * E.right(1) * ) * assert.deepStrictEqual( * pipe( * E.right(1), * E.alt(() => E.right(2)) * ), * E.right(1) * ) * * @category error handling * @since 2.0.0 */ export const alt: (that: LazyArg>) => (fa: Either) => Either = altW /** * @category instances * @since 2.7.0 */ export const Alt: Alt2 = { URI, map: _map, alt: _alt } /** * @since 2.0.0 */ export const extend: (f: (wa: Either) => B) => (wa: Either) => Either = (f) => (wa) => isLeft(wa) ? wa : right(f(wa)) /** * @category instances * @since 2.7.0 */ export const Extend: Extend2 = { URI, map: _map, extend: _extend } /** * @category instances * @since 2.7.0 */ export const ChainRec: ChainRec2 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRec } /** * @since 2.6.3 */ export const throwError: MonadThrow2['throwError'] = left /** * @category instances * @since 2.7.0 */ export const MonadThrow: MonadThrow2 = { URI, map: _map, ap: _ap, of, chain: flatMap, throwError } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither2 = { URI, fromEither: identity } /** * @example * import { fromPredicate, left, right } from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * 1, * fromPredicate( * (n) => n > 0, * () => 'error' * ) * ), * right(1) * ) * assert.deepStrictEqual( * pipe( * -1, * fromPredicate( * (n) => n > 0, * () => 'error' * ) * ), * left('error') * ) * * @category lifting * @since 2.0.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Either (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Either (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Either } = /*#__PURE__*/ fromPredicate_(FromEither) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as O from 'fp-ts/Option' * * assert.deepStrictEqual( * pipe( * O.some(1), * E.fromOption(() => 'error') * ), * E.right(1) * ) * assert.deepStrictEqual( * pipe( * O.none, * E.fromOption(() => 'error') * ), * E.left('error') * ) * * @category conversions * @since 2.0.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => Either = /*#__PURE__*/ fromOption_(FromEither) // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * Returns `true` if the either is an instance of `Left`, `false` otherwise. * * @category refinements * @since 2.0.0 */ export const isLeft: (ma: Either) => ma is Left = _.isLeft /** * Returns `true` if the either is an instance of `Right`, `false` otherwise. * * @category refinements * @since 2.0.0 */ export const isRight: (ma: Either) => ma is Right = _.isRight /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW = (onLeft: (e: E) => B, onRight: (a: A) => C) => (ma: Either): B | C => isLeft(ma) ? onLeft(ma.left) : onRight(ma.right) /** * Alias of [`matchW`](#matchw). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchW /** * Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the first function, * if the value is a `Right` the inner value is applied to the second function. * * @example * import { match, left, right } from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * function onLeft(errors: Array): string { * return `Errors: ${errors.join(', ')}` * } * * function onRight(value: number): string { * return `Ok: ${value}` * } * * assert.strictEqual( * pipe( * right(1), * match(onLeft, onRight) * ), * 'Ok: 1' * ) * assert.strictEqual( * pipe( * left(['error 1', 'error 2']), * match(onLeft, onRight) * ), * 'Errors: error 1, error 2' * ) * * @category pattern matching * @since 2.10.0 */ export const match: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Either) => B = matchW /** * Alias of [`match`](#match). * * @category pattern matching * @since 2.0.0 */ export const fold: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Either) => B = match /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.6.0 */ export const getOrElseW = (onLeft: (e: E) => B) => (ma: Either): A | B => isLeft(ma) ? onLeft(ma.left) : ma.right /** * Returns the wrapped value if it's a `Right` or a default value if is a `Left`. * * @example * import { getOrElse, left, right } from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * right(1), * getOrElse(() => 0) * ), * 1 * ) * assert.deepStrictEqual( * pipe( * left('error'), * getOrElse(() => 0) * ), * 0 * ) * * @category error handling * @since 2.0.0 */ export const getOrElse: (onLeft: (e: E) => A) => (ma: Either) => A = getOrElseW // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Less strict version of [`apFirst`](#apfirst) * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const apFirstW: (second: Either) => (first: Either) => Either = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * Less strict version of [`apSecond`](#apsecond) * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const apSecondW: (second: Either) => (first: Either) => Either = apSecond as any /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: Either, f: (a: A) => Either): Either (f: (a: A) => Either): (self: Either) => Either } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: (mma: Either>) => Either = /*#__PURE__*/ flatMap(identity) /** * The `flatten` function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level. * * @example * import * as E from 'fp-ts/Either' * * assert.deepStrictEqual(E.flatten(E.right(E.right('a'))), E.right('a')) * assert.deepStrictEqual(E.flatten(E.right(E.left('e'))), E.left('e')) * assert.deepStrictEqual(E.flatten(E.left('e')), E.left('e')) * * @category sequencing * @since 2.0.0 */ export const flatten: (mma: Either>) => Either = flattenW /** * @since 2.0.0 */ export const duplicate: (ma: Either) => Either> = /*#__PURE__*/ extend(identity) /** * Use `liftOption`. * * @category legacy * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Either = /*#__PURE__*/ fromOptionK_(FromEither) /** * Use `flatMapOption`. * * @category legacy * @since 2.11.0 */ export const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: Either) => Either = /*#__PURE__*/ chainOptionK_( FromEither, Chain ) /** * Use `flatMapOption`. * * @category legacy * @since 2.13.2 */ export const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: Either) => Either = chainOptionK as any /** @internal */ interface EitherTypeLambda extends _.TypeLambda { readonly type: Either } /** @internal */ const _FromEither: _.FromEither = { fromEither: FromEither.fromEither } /** * @category lifting * @since 2.15.0 */ export const liftNullable: , B, E>( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => Either> = /*#__PURE__*/ _.liftNullable(_FromEither) /** * @category lifting * @since 2.15.0 */ export const liftOption: , B, E>( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => Either = /*#__PURE__*/ _.liftOption(_FromEither) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** * @category sequencing * @since 2.15.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: Either ) => Either> (self: Either, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): Either< E1 | E2, NonNullable > } = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): (self: Either) => Either (self: Either, f: (a: A) => Option, onNone: (a: A) => E2): Either } = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap) /** * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * E.right(1), * E.filterOrElse( * (n) => n > 0, * () => 'error' * ) * ), * E.right(1) * ) * assert.deepStrictEqual( * pipe( * E.right(-1), * E.filterOrElse( * (n) => n > 0, * () => 'error' * ) * ), * E.left('error') * ) * assert.deepStrictEqual( * pipe( * E.left('a'), * E.filterOrElse( * (n) => n > 0, * () => 'error' * ) * ), * E.left('a') * ) * * @category filtering * @since 2.0.0 */ export const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (self: Either) => Either (predicate: Predicate, onFalse: (a: A) => E): (self: Either) => Either (predicate: Predicate, onFalse: (a: A) => E): (self: Either) => Either } = /*#__PURE__*/ filterOrElse_(FromEither, Chain) /** * Less strict version of [`filterOrElse`](#filterorelse). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category filtering * @since 2.9.0 */ export const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: Either ) => Either (predicate: Predicate, onFalse: (a: A) => E2): (mb: Either) => Either (predicate: Predicate, onFalse: (a: A) => E2): (ma: Either) => Either } = filterOrElse /** * Returns a `Right` if is a `Left` (and vice versa). * * @since 2.0.0 */ export const swap = (ma: Either): Either => (isLeft(ma) ? right(ma.left) : left(ma.right)) /** * Less strict version of [`orElse`](#orelse). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category error handling * @since 2.10.0 */ export const orElseW = (onLeft: (e: E1) => Either) => (ma: Either): Either => isLeft(ma) ? onLeft(ma.left) : ma /** * Useful for recovering from errors. * * @category error handling * @since 2.0.0 */ export const orElse: (onLeft: (e: E1) => Either) => (ma: Either) => Either = orElseW /** * Takes a default and a nullable value, if the value is not nully, turn it into a `Right`, if the value is nully use * the provided default as a `Left`. * * @example * import { fromNullable, left, right } from 'fp-ts/Either' * * const parse = fromNullable('nully') * * assert.deepStrictEqual(parse(1), right(1)) * assert.deepStrictEqual(parse(null), left('nully')) * * @category conversions * @since 2.0.0 */ export const fromNullable = (e: E) => (a: A): Either> => a == null ? left(e) : right(a as NonNullable) /** * Constructs a new `Either` from a function that might throw. * * See also [`tryCatchK`](#trycatchk). * * @example * import * as E from 'fp-ts/Either' * * const unsafeHead = (as: ReadonlyArray): A => { * if (as.length > 0) { * return as[0] * } else { * throw new Error('empty array') * } * } * * const head = (as: ReadonlyArray): E.Either => * E.tryCatch(() => unsafeHead(as), e => (e instanceof Error ? e : new Error('unknown error'))) * * assert.deepStrictEqual(head([]), E.left(new Error('empty array'))) * assert.deepStrictEqual(head([1, 2, 3]), E.right(1)) * * @category interop * @since 2.0.0 */ export const tryCatch = (f: LazyArg, onThrow: (e: unknown) => E): Either => { try { return right(f()) } catch (e) { return left(onThrow(e)) } } /** * Converts a function that may throw to one returning a `Either`. * * @category interop * @since 2.10.0 */ export const tryCatchK = , B, E>( f: (...a: A) => B, onThrow: (error: unknown) => E ): ((...a: A) => Either) => (...a) => tryCatch(() => f(...a), onThrow) /** * Use `liftNullable`. * * @category legacy * @since 2.9.0 */ export const fromNullableK = ( e: E ): (, B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Either>) => { const from = fromNullable(e) return (f) => flow(f, from) } /** * Use `flatMapNullable`. * * @category legacy * @since 2.9.0 */ export const chainNullableK = ( e: E ): ((f: (a: A) => B | null | undefined) => (ma: Either) => Either>) => { const from = fromNullableK(e) return (f) => flatMap(from(f)) } /** * @category conversions * @since 2.10.0 */ export const toUnion: (fa: Either) => E | A = /*#__PURE__*/ foldW(identity, identity) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Default value for the `onError` argument of `tryCatch` * * @since 2.0.0 */ export function toError(e: unknown): Error { try { return e instanceof Error ? e : new Error(String(e)) } catch (error) { return new Error() } } /** * @since 2.0.0 */ export function elem(E: Eq): { (a: A): (ma: Either) => boolean (a: A, ma: Either): boolean } export function elem(E: Eq): (a: A, ma?: Either) => boolean | ((ma: Either) => boolean) { return (a, ma?) => { if (ma === undefined) { const elemE = elem(E) return (ma) => elemE(a, ma) } return isLeft(ma) ? false : E.equals(a, ma.right) } } /** * Returns `false` if `Left` or returns the result of the application of the given predicate to the `Right` value. * * @example * import { exists, left, right } from 'fp-ts/Either' * * const gt2 = exists((n: number) => n > 2) * * assert.strictEqual(gt2(left('a')), false) * assert.strictEqual(gt2(right(1)), false) * assert.strictEqual(gt2(right(3)), true) * * @since 2.0.0 */ export const exists = (predicate: Predicate) => (ma: Either): boolean => isLeft(ma) ? false : predicate(ma.right) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: Either = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => Either ) => (fa: Either) => Either = bind as any /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: Either ) => (fa: Either) => Either = apS as any /** * @since 2.11.0 */ export const ApT: Either = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => Either) => (as: ReadonlyNonEmptyArray): Either> => { const e = f(0, _.head(as)) if (isLeft(e)) { return e } const out: NonEmptyArray = [e.right] for (let i = 1; i < as.length; i++) { const e = f(i, as[i]) if (isLeft(e)) { return e } out.push(e.right) } return right(out) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => Either ): ((as: ReadonlyArray) => Either>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => Either ) => (as: ReadonlyArray) => Either> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => Either ): ((as: ReadonlyArray) => Either>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (as: ReadonlyArray>) => Either> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: (f: (a: A) => Either) => (ma: Either) => Either = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Either) => (ma: Either) => Either = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => Either) => (ma: Either) => Either = tap /** * Alias of `tap`. * * @category legacy * @since 2.8.0 */ export const chainFirstW: (f: (a: A) => Either) => (ma: Either) => Either = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`Json`](./Json.ts.html) module instead. * * @category zone of death * @since 2.6.7 * @deprecated */ export type Json = boolean | number | string | null | JsonArray | JsonRecord /** * Use [`Json`](./Json.ts.html) module instead. * * @category zone of death * @since 2.6.7 * @deprecated */ export interface JsonRecord { readonly [key: string]: Json } /** * Use [`Json`](./Json.ts.html) module instead. * * @category zone of death * @since 2.6.7 * @deprecated */ export interface JsonArray extends ReadonlyArray {} /** * Use [`parse`](./Json.ts.html#parse) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function parseJSON(s: string, onError: (reason: unknown) => E): Either { return tryCatch(() => JSON.parse(s), onError) } /** * Use [`stringify`](./Json.ts.html#stringify) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const stringifyJSON = (u: unknown, onError: (reason: unknown) => E): Either => tryCatch(() => { const s = JSON.stringify(u) if (typeof s !== 'string') { throw new Error('Converting unsupported structure to JSON') } return s }, onError) /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `E.Functor` instead of `E.either` * (where `E` is from `import E from 'fp-ts/Either'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const either: Monad2 & Foldable2 & Traversable2 & Bifunctor2 & Alt2 & Extend2 & ChainRec2 & MonadThrow2 = { URI, map: _map, of, ap: _ap, chain: flatMap, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, bimap: _bimap, mapLeft: _mapLeft, alt: _alt, extend: _extend, chainRec: _chainRec, throwError: throwError } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values * are concatenated using the provided `Semigroup` * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplySemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(Apply) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplyMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(Applicative) /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getValidationSemigroup = (SE: Semigroup, SA: Semigroup): Semigroup> => getApplySemigroup_(getApplicativeValidation(SE))(SA) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getValidationMonoid = (SE: Semigroup, MA: Monoid): Monoid> => getApplicativeMonoid(getApplicativeValidation(SE))(MA) /** * Use [`getApplicativeValidation`](#getapplicativevalidation) and [`getAltValidation`](#getaltvalidation) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getValidation( SE: Semigroup ): Monad2C & Foldable2 & Traversable2 & Bifunctor2 & Alt2C & Extend2 & ChainRec2C & MonadThrow2C { const ap = getApplicativeValidation(SE).ap const alt = getAltValidation(SE).alt return { URI, _E: undefined as any, map: _map, of, chain: flatMap, bimap: _bimap, mapLeft: _mapLeft, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, extend: _extend, traverse: _traverse, sequence, chainRec: _chainRec, throwError, ap, alt } } ================================================ FILE: src/EitherT.ts ================================================ /** * The error monad transformer. It can be used to add error handling to other monads. * * The `of` function yields a successful computation, while `chain` sequences two subcomputations, failing on the first error. * * @since 2.0.0 */ import { ApplicativeComposition12, ApplicativeComposition22, ApplicativeCompositionHKT2 } from './Applicative' import { ap as ap_, Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C } from './Apply' import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C } from './Chain' import * as E from './Either' import { flow, LazyArg, pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, map as map_ } from './Functor' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C } from './Monad' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C } from './Pointed' import { Semigroup } from './Semigroup' import Either = E.Either // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function right(F: Pointed3): (a: A) => Kind3> export function right( F: Pointed3C ): (a: A) => Kind3> export function right(F: Pointed2): (a: A) => Kind2> export function right(F: Pointed2C): (a: A) => Kind2> export function right(F: Pointed1): (a: A) => Kind> export function right(F: Pointed): (a: A) => HKT> export function right(F: Pointed): (a: A) => HKT> { return flow(E.right, F.of) } /** * @since 2.10.0 */ export function left(F: Pointed3): (e: E) => Kind3> export function left(F: Pointed3C): (e: E) => Kind3> export function left(F: Pointed2): (e: E) => Kind2> export function left(F: Pointed2C): (e: E) => Kind2> export function left(F: Pointed1): (e: E) => Kind> export function left(F: Pointed): (e: E) => HKT> export function left(F: Pointed): (e: E) => HKT> { return flow(E.left, F.of) } /** * @since 2.10.0 */ export function rightF( F: Functor3 ): (fa: Kind3) => Kind3> export function rightF( F: Functor3C ): (fa: Kind3) => Kind3> export function rightF( F: Functor2 ): (fa: Kind2) => Kind2> export function rightF( F: Functor2C ): (fa: Kind2) => Kind2> export function rightF(F: Functor1): (fa: Kind) => Kind> export function rightF(F: Functor): (fa: HKT) => HKT> export function rightF(F: Functor): (fa: HKT) => HKT> { return (fa) => F.map(fa, E.right) } /** * @since 2.10.0 */ export function leftF( F: Functor3 ): (fe: Kind3) => Kind3> export function leftF( F: Functor3C ): (fe: Kind3) => Kind3> export function leftF( F: Functor2 ): (fe: Kind2) => Kind2> export function leftF( F: Functor2C ): (fe: Kind2) => Kind2> export function leftF(F: Functor1): (fe: Kind) => Kind> export function leftF(F: Functor): (fe: HKT) => HKT> export function leftF(F: Functor): (fe: HKT) => HKT> { return (fe) => F.map(fe, E.left) } /** * @since 2.12.0 */ export function fromNullable( F: Pointed3 ): (e: E) => (a: A) => Kind3>> export function fromNullable( F: Pointed3C ): (e: E) => (a: A) => Kind3>> export function fromNullable( F: Pointed2 ): (e: E) => (a: A) => Kind2>> export function fromNullable( F: Pointed2C ): (e: E) => (a: A) => Kind2>> export function fromNullable( F: Pointed1 ): (e: E) => (a: A) => Kind>> export function fromNullable(F: Pointed): (e: E) => (a: A) => HKT>> export function fromNullable(F: Pointed): (e: E) => (a: A) => HKT>> { return (e) => flow(E.fromNullable(e), F.of) } /** * @since 2.12.0 */ export function fromNullableK( F: Pointed3 ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export function fromNullableK( F: Pointed3C ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export function fromNullableK( F: Pointed2 ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export function fromNullableK( F: Pointed2C ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export function fromNullableK( F: Pointed1 ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind>> export function fromNullableK( F: Pointed ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => HKT>> export function fromNullableK( F: Pointed ): ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => HKT>> { const fromNullableF = fromNullable(F) return (e) => { const fromNullableFE = fromNullableF(e) return (f) => flow(f, fromNullableFE) } } /** * @since 2.12.0 */ export function chainNullableK( M: Monad3 ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export function chainNullableK( M: Monad3C ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export function chainNullableK( M: Monad2 ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind2>) => Kind2>> export function chainNullableK( M: Monad2C ): ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: Kind2>) => Kind2>> export function chainNullableK( M: Monad1 ): ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: Kind>) => Kind>> export function chainNullableK( M: Monad ): ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: HKT>) => HKT>> export function chainNullableK( M: Monad ): ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: HKT>) => HKT>> { const chainM = chain(M) const fromNullableKM = fromNullableK(M) return (e) => { const fromNullableKMe = fromNullableKM(e) return (f) => chainM(fromNullableKMe(f)) } } /** * @since 2.10.0 */ export function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> export function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> { return map_(F, E.Functor) } /** * @since 2.10.0 */ export function ap( F: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply2 ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C ): ( fa: Kind2> ) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply1 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export function ap( F: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> { return ap_(F, E.Apply) } /** * @since 2.10.0 */ export function chain( M: Monad3 ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export function chain( M: Monad3C ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export function chain( M: Monad2 ): ( f: (a: A) => Kind2> ) => (ma: Kind2>) => Kind2> export function chain( M: Monad2C ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export function chain( M: Monad1 ): (f: (a: A) => Kind>) => (ma: Kind>) => Kind> export function chain( M: Monad ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> export function chain( M: Monad ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> { const flatMapM = flatMap(M) return (f) => (ma) => flatMapM(ma, f) } /** @internal */ export function flatMap( M: Monad2 ): (ma: Kind2>, f: (a: A) => Kind2>) => Kind2> /** @internal */ export function flatMap( M: Monad1 ): (ma: Kind>, f: (a: A) => Kind>) => Kind> /** @internal */ export function flatMap( M: Monad ): (ma: HKT>, f: (a: A) => HKT>) => HKT> /** @internal */ export function flatMap( M: Monad ): (ma: HKT>, f: (a: A) => HKT>) => HKT> { return (ma, f) => M.chain(ma, (e) => (E.isLeft(e) ? M.of(e) : f(e.right))) } /** * @since 2.10.0 */ export function alt( M: Monad3 ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export function alt( M: Monad3C ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export function alt( M: Monad2 ): ( second: LazyArg>> ) => (first: Kind2>) => Kind2> export function alt( M: Monad2C ): ( second: LazyArg>> ) => (first: Kind2>) => Kind2> export function alt( M: Monad1 ): (second: LazyArg>>) => (first: Kind>) => Kind> export function alt( M: Monad ): (second: LazyArg>>) => (first: HKT>) => HKT> export function alt( M: Monad ): (second: LazyArg>>) => (first: HKT>) => HKT> { return (second) => (first) => M.chain(first, (e) => (E.isLeft(e) ? second() : M.of(e))) } /** * @since 2.10.0 */ export function bimap( F: Functor3 ): ( f: (e: E) => G, g: (a: A) => B ) => (self: Kind3>) => Kind3> export function bimap( F: Functor3C ): ( f: (e: E) => G, g: (a: A) => B ) => (self: Kind3>) => Kind3> export function bimap( F: Functor2 ): (f: (e: E) => G, g: (a: A) => B) => (self: Kind2>) => Kind2> export function bimap( F: Functor2C ): (f: (e: E) => G, g: (a: A) => B) => (self: Kind2>) => Kind2> export function bimap( F: Functor1 ): (f: (e: E) => G, g: (a: A) => B) => (self: Kind>) => Kind> export function bimap( F: Functor ): (f: (e: E) => G, g: (a: A) => B) => (self: HKT>) => HKT> export function bimap( F: Functor ): (f: (e: E) => G, g: (a: A) => B) => (self: HKT>) => HKT> { const mapBothF = mapBoth(F) return (f, g) => (self) => mapBothF(self, f, g) } /** @internal */ export function mapBoth( F: Functor2 ): (self: Kind2>, f: (e: E) => G, g: (a: A) => B) => Kind2> /** @internal */ export function mapBoth( F: Functor1 ): (self: Kind>, f: (e: E) => G, g: (a: A) => B) => Kind> /** @internal */ export function mapBoth( F: Functor ): (self: HKT>, f: (e: E) => G, g: (a: A) => B) => HKT> /** @internal */ export function mapBoth( F: Functor ): (self: HKT>, f: (e: E) => G, g: (a: A) => B) => HKT> { return (self, f, g) => F.map(self, E.bimap(f, g)) } /** * @since 2.10.0 */ export function mapLeft( F: Functor3 ): (f: (e: E) => G) => (self: Kind3>) => Kind3> export function mapLeft( F: Functor3C ): (f: (e: E) => G) => (self: Kind3>) => Kind3> export function mapLeft( F: Functor2 ): (f: (e: E) => G) => (self: Kind2>) => Kind2> export function mapLeft( F: Functor2C ): (f: (e: E) => G) => (self: Kind2>) => Kind2> export function mapLeft( F: Functor1 ): (f: (e: E) => G) => (self: Kind>) => Kind> export function mapLeft( F: Functor ): (f: (e: E) => G) => (self: HKT>) => HKT> export function mapLeft( F: Functor ): (f: (e: E) => G) => (self: HKT>) => HKT> { const mapErrorF = mapError(F) return (f) => (self) => mapErrorF(self, f) } /** @internal */ export function mapError( F: Functor2 ): (self: Kind2>, f: (e: E) => G) => Kind2> /** @internal */ export function mapError( F: Functor1 ): (self: Kind>, f: (e: E) => G) => Kind> /** @internal */ export function mapError( F: Functor ): (self: HKT>, f: (e: E) => G) => HKT> /** @internal */ export function mapError( F: Functor ): (self: HKT>, f: (e: E) => G) => HKT> { return (self, f) => F.map(self, E.mapLeft(f)) } /** * @category error handling * @since 2.10.0 */ export function altValidation( M: Monad3, S: Semigroup ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export function altValidation( M: Monad3C, S: Semigroup ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export function altValidation( M: Monad2, S: Semigroup ): ( second: LazyArg>> ) => (first: Kind2>) => Kind2> export function altValidation( M: Monad2C, S: Semigroup ): (second: LazyArg>>) => (first: Kind2>) => Kind2> export function altValidation( M: Monad1, S: Semigroup ): (second: LazyArg>>) => (first: Kind>) => Kind> export function altValidation( M: Monad, S: Semigroup ): (second: LazyArg>>) => (first: HKT>) => HKT> export function altValidation( M: Monad, S: Semigroup ): (second: LazyArg>>) => (first: HKT>) => HKT> { return (second) => (first) => M.chain( first, E.match( (e1) => M.map( second(), E.mapLeft((e2) => S.concat(e1, e2)) ), right(M) ) ) } /** * @category pattern matching * @since 2.11.0 */ export function match( F: Functor3 ): ( onLeft: (e: E) => B, onRight: (a: A) => B ) => (ma: Kind3>) => Kind3 export function match( F: Functor3C ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind3>) => Kind3 export function match( F: Functor2 ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind2>) => Kind2 export function match( F: Functor2C ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind2>) => Kind2 export function match( F: Functor1 ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: Kind>) => Kind export function match( F: Functor ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: HKT>) => HKT export function match( F: Functor ): (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: HKT>) => HKT { return (onLeft, onRight) => (ma) => F.map(ma, E.match(onLeft, onRight)) } /** * @since 2.10.0 */ export function matchE( M: Chain3 ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export function matchE( M: Chain3C ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export function matchE( M: Chain2 ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export function matchE( M: Chain2C ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export function matchE( M: Chain1 ): (onLeft: (e: E) => Kind, onRight: (a: A) => Kind) => (ma: Kind>) => Kind export function matchE( M: Chain ): (onLeft: (e: E) => HKT, onRight: (a: A) => HKT) => (ma: HKT>) => HKT export function matchE( M: Chain ): (onLeft: (e: E) => HKT, onRight: (a: A) => HKT) => (ma: HKT>) => HKT { return (onLeft, onRight) => (ma) => M.chain(ma, E.match(onLeft, onRight)) } /** * @since 2.10.0 */ export function getOrElse( M: Monad3 ): (onLeft: (e: E) => Kind3) => (ma: Kind3>) => Kind3 export function getOrElse( M: Monad3C ): (onLeft: (e: E) => Kind3) => (ma: Kind3>) => Kind3 export function getOrElse( M: Monad2 ): (onLeft: (e: E) => Kind2) => (ma: Kind2>) => Kind2 export function getOrElse( M: Monad2C ): (onLeft: (e: E) => Kind2) => (ma: Kind2>) => Kind2 export function getOrElse( M: Monad1 ): (onLeft: (e: E) => Kind) => (ma: Kind>) => Kind export function getOrElse( M: Monad ): (onLeft: (e: E) => HKT) => (ma: HKT>) => HKT export function getOrElse( M: Monad ): (onLeft: (e: E) => HKT) => (ma: HKT>) => HKT { return (onLeft) => (ma) => M.chain(ma, E.match(onLeft, M.of)) } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function orElse( M: Monad3 ): ( onLeft: (e: E1) => Kind3> ) => (ma: Kind3>) => Kind3> export function orElse( M: Monad3C ): ( onLeft: (e: E1) => Kind3> ) => (ma: Kind3>) => Kind3> export function orElse( M: Monad2 ): ( onLeft: (e: E1) => Kind2> ) => (ma: Kind2>) => Kind2> export function orElse( M: Monad2C ): ( onLeft: (e: E1) => Kind2> ) => (ma: Kind2>) => Kind2> export function orElse( M: Monad1 ): (onLeft: (e: E1) => Kind>) => (ma: Kind>) => Kind> export function orElse( M: Monad ): (onLeft: (e: E1) => HKT>) => (ma: HKT>) => HKT> export function orElse( M: Monad ): (onLeft: (e: E1) => HKT>) => (ma: HKT>) => HKT> { return (onLeft) => (ma) => M.chain(ma, (e) => (E.isLeft(e) ? onLeft(e.left) : M.of(e))) } /** * @category error handling * @since 2.11.0 */ export function orElseFirst( M: Monad3 ): ( onLeft: (e: E) => Kind3> ) => (ma: Kind3>) => Kind3> export function orElseFirst( M: Monad3C ): ( onLeft: (e: E) => Kind3> ) => (ma: Kind3>) => Kind3> export function orElseFirst( M: Monad2 ): ( onLeft: (e: E) => Kind2> ) => (ma: Kind2>) => Kind2> export function orElseFirst( M: Monad2C ): ( onLeft: (e: E) => Kind2> ) => (ma: Kind2>) => Kind2> export function orElseFirst( M: Monad1 ): (onLeft: (e: E) => Kind>) => (ma: Kind>) => Kind> export function orElseFirst( M: Monad ): (onLeft: (e: E) => HKT>) => (ma: HKT>) => HKT> export function orElseFirst( M: Monad ): (onLeft: (e: E) => HKT>) => (ma: HKT>) => HKT> { const tapErrorM = tapError(M) return (onLeft) => (ma) => tapErrorM(ma, onLeft) } /** @internal */ export function tapError( M: Monad2 ): (ma: Kind2>, onLeft: (e: E) => Kind2>) => Kind2> /** @internal */ export function tapError( M: Monad1 ): (ma: Kind>, onLeft: (e: E) => Kind>) => Kind> /** @internal */ export function tapError( M: Monad ): (ma: HKT>, onLeft: (e: E) => HKT>) => HKT> /** @internal */ export function tapError( M: Monad ): (ma: HKT>, onLeft: (e: E) => HKT>) => HKT> { const orElseM = orElse(M) return (ma, onLeft) => pipe( ma, orElseM((e) => M.map(onLeft(e), (eb) => (E.isLeft(eb) ? eb : E.left(e)))) ) } /** * @category error handling * @since 2.11.0 */ export function orLeft( M: Monad3 ): ( onLeft: (e: E1) => Kind3 ) => (fa: Kind3>) => Kind3> export function orLeft( M: Monad3C ): ( onLeft: (e: E1) => Kind3 ) => (fa: Kind3>) => Kind3> export function orLeft( M: Monad2 ): ( onLeft: (e: E1) => Kind2 ) => (fa: Kind2>) => Kind2> export function orLeft( M: Monad2C ): (onLeft: (e: E1) => Kind2) => (fa: Kind2>) => Kind2> export function orLeft( M: Monad1 ): (onLeft: (e: E1) => Kind) => (fa: Kind>) => Kind> export function orLeft( M: Monad ): (onLeft: (e: E1) => HKT) => (fa: HKT>) => HKT> export function orLeft( M: Monad ): (onLeft: (e: E1) => HKT) => (fa: HKT>) => HKT> { return (onLeft) => (ma) => M.chain( ma, E.match( (e) => M.map(onLeft(e), E.left), (a) => M.of(E.right(a)) ) ) } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function swap( F: Functor3 ): (ma: Kind3>) => Kind3> export function swap( F: Functor3C ): (ma: Kind3>) => Kind3> export function swap( F: Functor2 ): (ma: Kind2>) => Kind2> export function swap( F: Functor2C ): (ma: Kind2>) => Kind2> export function swap(F: Functor1): (ma: Kind>) => Kind> export function swap(F: Functor): (ma: HKT>) => HKT> export function swap(F: Functor): (ma: HKT>) => HKT> { return (ma) => F.map(ma, E.swap) } /** * @since 2.10.0 */ export function toUnion( F: Functor3 ): (fa: Kind3>) => Kind3 export function toUnion( F: Functor3C ): (fa: Kind3>) => Kind3 export function toUnion( F: Functor2 ): (fa: Kind2>) => Kind2 export function toUnion( F: Functor2C ): (fa: Kind2>) => Kind2 export function toUnion(F: Functor1): (fa: Kind>) => Kind export function toUnion(F: Functor): (fa: HKT>) => HKT export function toUnion(F: Functor): (fa: HKT>) => HKT { return (fa) => F.map(fa, E.toUnion) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- // eslint-disable-next-line import/first import URI = E.URI /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface EitherT extends HKT> {} /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface EitherM extends ApplicativeCompositionHKT2 { readonly chain: (ma: EitherT, f: (a: A) => EitherT) => EitherT readonly alt: (fa: EitherT, that: LazyArg>) => EitherT readonly bimap: (ma: EitherT, f: (e: E) => N, g: (a: A) => B) => EitherT readonly mapLeft: (ma: EitherT, f: (e: E) => N) => EitherT readonly fold: (ma: EitherT, onLeft: (e: E) => HKT, onRight: (a: A) => HKT) => HKT readonly getOrElse: (ma: EitherT, onLeft: (e: E) => HKT) => HKT readonly orElse: (ma: EitherT, onLeft: (e: E) => EitherT) => EitherT readonly swap: (ma: EitherT) => EitherT readonly rightM: (ma: HKT) => EitherT readonly leftM: (me: HKT) => EitherT readonly left: (e: E) => EitherT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export type EitherT1 = Kind> /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface EitherM1 extends ApplicativeComposition12 { readonly chain: (ma: EitherT1, f: (a: A) => EitherT1) => EitherT1 readonly alt: (fa: EitherT1, that: LazyArg>) => EitherT1 readonly bimap: (ma: EitherT1, f: (e: E) => N, g: (a: A) => B) => EitherT1 readonly mapLeft: (ma: EitherT1, f: (e: E) => N) => EitherT1 readonly fold: ( ma: EitherT1, onLeft: (e: E) => Kind, onRight: (a: A) => Kind ) => Kind readonly getOrElse: (ma: EitherT1, onLeft: (e: E) => Kind) => Kind readonly orElse: (ma: EitherT1, onLeft: (e: E) => EitherT1) => EitherT1 readonly swap: (ma: EitherT1) => EitherT1 readonly rightM: (ma: Kind) => EitherT1 readonly leftM: (me: Kind) => EitherT1 readonly left: (e: E) => EitherT1 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export type EitherT2 = Kind2> /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface EitherM2 extends ApplicativeComposition22 { readonly chain: (ma: EitherT2, f: (a: A) => EitherT2) => EitherT2 readonly alt: (fa: EitherT2, that: LazyArg>) => EitherT2 readonly bimap: (ma: EitherT2, f: (e: E) => N, g: (a: A) => B) => EitherT2 readonly mapLeft: (ma: EitherT2, f: (e: E) => N) => EitherT2 readonly fold: ( ma: EitherT2, onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2 ) => Kind2 readonly getOrElse: (ma: EitherT2, onLeft: (e: E) => Kind2) => Kind2 readonly orElse: ( ma: EitherT2, onLeft: (e: E) => EitherT2 ) => EitherT2 readonly swap: (ma: EitherT2) => EitherT2 readonly rightM: (ma: Kind2) => EitherT2 readonly leftM: (me: Kind2) => EitherT2 readonly left: (e: E) => EitherT2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export function getEitherM(M: Monad2): EitherM2 /** @deprecated */ export function getEitherM(M: Monad1): EitherM1 /** @deprecated */ export function getEitherM(M: Monad): EitherM /** @deprecated */ /* istanbul ignore next */ export function getEitherM(M: Monad): EitherM { const _ap = ap(M) const _map = map(M) const _chain = chain(M) const _alt = alt(M) const _bimap = bimap(M) const _mapLeft = mapLeft(M) const _fold = matchE(M) const _getOrElse = getOrElse(M) const _orElse = orElse(M) return { map: (fa, f) => pipe(fa, _map(f)), ap: (fab, fa) => pipe(fab, _ap(fa)), of: right(M), chain: (ma, f) => pipe(ma, _chain(f)), alt: (fa, that) => pipe(fa, _alt(that)), bimap: (fea, f, g) => pipe(fea, _bimap(f, g)), mapLeft: (fea, f) => pipe(fea, _mapLeft(f)), fold: (fa, onLeft, onRight) => pipe(fa, _fold(onLeft, onRight)), getOrElse: (fa, onLeft) => pipe(fa, _getOrElse(onLeft)), orElse: (fa, f) => pipe(fa, _orElse(f)), swap: swap(M), rightM: rightF(M), leftM: leftF(M), left: left(M) } } ================================================ FILE: src/Endomorphism.ts ================================================ /** * @since 2.11.0 */ import { flow, identity } from './function' import { Monoid } from './Monoid' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export interface Endomorphism { (a: A): A } /** * @category type lambdas * @since 2.11.0 */ export const URI = 'Endomorphism' /** * @category type lambdas * @since 2.11.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Endomorphism } } /** * Endomorphism form a `Semigroup` where the `concat` operation is the usual function composition. * * @category instances * @since 2.11.0 */ export const getSemigroup = (): Semigroup> => ({ concat: (first, second) => flow(first, second) }) /** * Endomorphism form a `Monoid` where the `empty` value is the `identity` function. * * @category instances * @since 2.11.0 */ export const getMonoid = (): Monoid> => ({ concat: getSemigroup().concat, empty: identity }) ================================================ FILE: src/Eq.ts ================================================ /** * The `Eq` type class represents types which support decidable equality. * * Instances must satisfy the following laws: * * 1. Reflexivity: `E.equals(a, a) === true` * 2. Symmetry: `E.equals(a, b) === E.equals(b, a)` * 3. Transitivity: if `E.equals(a, b) === true` and `E.equals(b, c) === true`, then `E.equals(a, c) === true` * * @since 2.0.0 */ import { Contravariant1 } from './Contravariant' import { pipe } from './function' import { Monoid } from './Monoid' import { ReadonlyRecord } from './ReadonlyRecord' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Eq { readonly equals: (x: A, y: A) => boolean } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export const fromEquals = (equals: Eq['equals']): Eq => ({ equals: (x, y) => x === y || equals(x, y) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export const struct = (eqs: { [K in keyof A]: Eq }): Eq<{ readonly [K in keyof A]: A[K] }> => fromEquals((first, second) => { for (const key in eqs) { if (!eqs[key].equals(first[key], second[key])) { return false } } return true }) /** * Given a tuple of `Eq`s returns a `Eq` for the tuple * * @example * import { tuple } from 'fp-ts/Eq' * import * as S from 'fp-ts/string' * import * as N from 'fp-ts/number' * import * as B from 'fp-ts/boolean' * * const E = tuple(S.Eq, N.Eq, B.Eq) * assert.strictEqual(E.equals(['a', 1, true], ['a', 1, true]), true) * assert.strictEqual(E.equals(['a', 1, true], ['b', 1, true]), false) * assert.strictEqual(E.equals(['a', 1, true], ['a', 2, true]), false) * assert.strictEqual(E.equals(['a', 1, true], ['a', 1, false]), false) * * @since 2.10.0 */ export const tuple = >(...eqs: { [K in keyof A]: Eq }): Eq> => fromEquals((first, second) => eqs.every((E, i) => E.equals(first[i], second[i]))) /* istanbul ignore next */ const contramap_: (fa: Eq, f: (b: B) => A) => Eq = (fa, f) => pipe(fa, contramap(f)) /** * A typical use case for `contramap` would be like, given some `User` type, to construct an `Eq`. * * We can do so with a function from `User -> X` where `X` is some value that we know how to compare * for equality (meaning we have an `Eq`) * * For example, given the following `User` type, we want to construct an `Eq` that just looks at the `key` field * for each user (since it's known to be unique). * * If we have a way of comparing `UUID`s for equality (`eqUUID: Eq`) and we know how to go from `User -> UUID`, * using `contramap` we can do this * * @example * import { contramap, Eq } from 'fp-ts/Eq' * import { pipe } from 'fp-ts/function' * import * as S from 'fp-ts/string' * * type UUID = string * * interface User { * readonly key: UUID * readonly firstName: string * readonly lastName: string * } * * const eqUUID: Eq = S.Eq * * const eqUserByKey: Eq = pipe( * eqUUID, * contramap((user) => user.key) * ) * * assert.deepStrictEqual( * eqUserByKey.equals( * { key: 'k1', firstName: 'a1', lastName: 'b1' }, * { key: 'k2', firstName: 'a1', lastName: 'b1' } * ), * false * ) * assert.deepStrictEqual( * eqUserByKey.equals( * { key: 'k1', firstName: 'a1', lastName: 'b1' }, * { key: 'k1', firstName: 'a2', lastName: 'b1' } * ), * true * ) * * @since 2.0.0 */ export const contramap: (f: (b: B) => A) => (fa: Eq) => Eq = (f) => (fa) => fromEquals((x, y) => fa.equals(f(x), f(y))) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Eq' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Eq } } /** * @category instances * @since 2.5.0 */ export const eqStrict: Eq = { equals: (a, b) => a === b } const empty: Eq = { equals: () => true } /** * @category instances * @since 2.10.0 */ export const getSemigroup = (): Semigroup> => ({ concat: (x, y) => fromEquals((a, b) => x.equals(a, b) && y.equals(a, b)) }) /** * @category instances * @since 2.6.0 */ export const getMonoid = (): Monoid> => ({ concat: getSemigroup().concat, empty }) /** * @category instances * @since 2.7.0 */ export const Contravariant: Contravariant1 = { URI, contramap: contramap_ } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`tuple`](#tuple) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getTupleEq: >>( ...eqs: T ) => Eq<{ [K in keyof T]: T[K] extends Eq ? A : never }> = tuple /** * Use [`struct`](#struct) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getStructEq: >(eqs: { [K in keyof O]: Eq }) => Eq = struct /** * Use [`eqStrict`](#eqstrict) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const strictEqual: (a: A, b: A) => boolean = eqStrict.equals /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Contravariant` instance, pass `E.Contravariant` instead of `E.eq` * (where `E` is from `import E from 'fp-ts/Eq'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const eq: Contravariant1 = Contravariant /** * Use [`Eq`](./boolean.ts.html#eq) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const eqBoolean: Eq = eqStrict /** * Use [`Eq`](./string.ts.html#eq) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const eqString: Eq = eqStrict /** * Use [`Eq`](./number.ts.html#eq) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const eqNumber: Eq = eqStrict /** * Use [`Eq`](./Date.ts.html#eq) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const eqDate: Eq = { equals: (first, second) => first.valueOf() === second.valueOf() } ================================================ FILE: src/Extend.ts ================================================ /** * @since 2.0.0 */ import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4 } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Extend extends Functor { readonly extend: (wa: HKT, f: (wa: HKT) => B) => HKT } /** * @category model * @since 2.0.0 */ export interface Extend1 extends Functor1 { readonly extend: (wa: Kind, f: (wa: Kind) => B) => Kind } /** * @category model * @since 2.0.0 */ export interface Extend2 extends Functor2 { readonly extend: (wa: Kind2, f: (wa: Kind2) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Extend2C extends Functor2C { readonly extend: (wa: Kind2, f: (wa: Kind2) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Extend3 extends Functor3 { readonly extend: (wa: Kind3, f: (wa: Kind3) => B) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Extend3C extends Functor3C { readonly extend: (wa: Kind3, f: (wa: Kind3) => B) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Extend4 extends Functor4 { readonly extend: (wa: Kind4, f: (wa: Kind4) => B) => Kind4 } ================================================ FILE: src/Field.ts ================================================ /** * Adapted from https://github.com/purescript/purescript-prelude/blob/master/src/Data/Field.purs * * @since 2.0.0 */ import { Eq } from './Eq' import { Ring } from './Ring' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Field extends Ring { readonly degree: (a: A) => number readonly div: (x: A, y: A) => A readonly mod: (x: A, y: A) => A } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * The *greatest common divisor* of two values * * @since 2.0.0 */ export function gcd(E: Eq, field: Field): (x: A, y: A) => A { const zero = field.zero const f = (x: A, y: A): A => (E.equals(y, zero) ? x : f(y, field.mod(x, y))) return f } /** * The *least common multiple* of two values * * @since 2.0.0 */ export function lcm(E: Eq, F: Field): (x: A, y: A) => A { const zero = F.zero const gcdSF = gcd(E, F) return (x, y) => (E.equals(x, zero) || E.equals(y, zero) ? zero : F.div(F.mul(x, y), gcdSF(x, y))) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`Field`](./number.ts.html#field) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const fieldNumber: Field = { add: (x, y) => x + y, zero: 0, mul: (x, y) => x * y, one: 1, sub: (x, y) => x - y, degree: (_) => 1, div: (x, y) => x / y, mod: (x, y) => x % y } ================================================ FILE: src/Filterable.ts ================================================ /** * `Filterable` represents data structures which can be _partitioned_/_filtered_. * * Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Filterable.purs * * @since 2.0.0 */ import { compact, Compactable, Compactable1, Compactable2, Compactable2C, Compactable3, Compactable3C, Compactable4, CompactableComposition, CompactableComposition11, CompactableComposition12, CompactableComposition12C, CompactableComposition21, CompactableComposition22, CompactableComposition23, separate } from './Compactable' import { Either } from './Either' import { pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4, FunctorComposition, FunctorComposition11, FunctorComposition12, FunctorComposition12C, FunctorComposition21, FunctorComposition22, FunctorComposition23, getFunctorComposition } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { getLeft, getRight, Option } from './Option' import { not, Predicate } from './Predicate' import { Refinement } from './Refinement' import { Separated, separated } from './Separated' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export interface Filter { (fa: HKT, refinement: Refinement): HKT (fa: HKT, predicate: Predicate): HKT } /** * @since 2.0.0 */ export interface Partition { (fa: HKT, refinement: Refinement): Separated, HKT> (fa: HKT, predicate: Predicate): Separated, HKT> } /** * @category model * @since 2.0.0 */ export interface Filterable extends Functor, Compactable { /** * Partition a data structure based on an either predicate. */ readonly partitionMap: (fa: HKT, f: (a: A) => Either) => Separated, HKT> /** * Partition a data structure based on a boolean predicate. */ readonly partition: Partition /** * Map over a data structure and filter based on an option predicate. */ readonly filterMap: (fa: HKT, f: (a: A) => Option) => HKT /** * Filter a data structure based on a boolean predicate. */ readonly filter: Filter } /** * @since 2.0.0 */ export interface Filter1 { (fa: Kind, refinement: Refinement): Kind (fa: Kind, predicate: Predicate): Kind } /** * @since 2.0.0 */ export interface Partition1 { (fa: Kind, refinement: Refinement): Separated, Kind> (fa: Kind, predicate: Predicate): Separated, Kind> } /** * @category model * @since 2.0.0 */ export interface Filterable1 extends Functor1, Compactable1 { readonly partitionMap: (fa: Kind, f: (a: A) => Either) => Separated, Kind> readonly partition: Partition1 readonly filterMap: (fa: Kind, f: (a: A) => Option) => Kind readonly filter: Filter1 } /** * @since 2.0.0 */ export interface Filter2 { (fa: Kind2, refinement: Refinement): Kind2 (fa: Kind2, predicate: Predicate): Kind2 } /** * @since 2.0.0 */ export interface Partition2 { (fa: Kind2, refinement: Refinement): Separated, Kind2> (fa: Kind2, predicate: Predicate): Separated, Kind2> } /** * @category model * @since 2.0.0 */ export interface Filterable2 extends Functor2, Compactable2 { readonly partitionMap: ( fa: Kind2, f: (a: A) => Either ) => Separated, Kind2> readonly partition: Partition2 readonly filterMap: (fa: Kind2, f: (a: A) => Option) => Kind2 readonly filter: Filter2 } /** * @since 2.0.0 */ export interface Filter2C { (fa: Kind2, refinement: Refinement): Kind2 (fa: Kind2, predicate: Predicate): Kind2 } /** * @since 2.0.0 */ export interface Partition2C { (fa: Kind2, refinement: Refinement): Separated, Kind2> (fa: Kind2, predicate: Predicate): Separated, Kind2> } /** * @category model * @since 2.0.0 */ export interface Filterable2C extends Functor2C, Compactable2C { readonly partitionMap: ( fa: Kind2, f: (a: A) => Either ) => Separated, Kind2> readonly partition: Partition2C readonly filterMap: (fa: Kind2, f: (a: A) => Option) => Kind2 readonly filter: Filter2C } /** * @since 2.0.0 */ export interface Filter3 { (fa: Kind3, refinement: Refinement): Kind3 (fa: Kind3, predicate: Predicate): Kind3 } /** * @since 2.0.0 */ export interface Partition3 { (fa: Kind3, refinement: Refinement): Separated< Kind3, Kind3 > (fa: Kind3, predicate: Predicate): Separated, Kind3> } /** * @category model * @since 2.0.0 */ export interface Filterable3 extends Functor3, Compactable3 { readonly partitionMap: ( fa: Kind3, f: (a: A) => Either ) => Separated, Kind3> readonly partition: Partition3 readonly filterMap: (fa: Kind3, f: (a: A) => Option) => Kind3 readonly filter: Filter3 } /** * @since 2.2.0 */ export interface Filter3C { (fa: Kind3, refinement: Refinement): Kind3 (fa: Kind3, predicate: Predicate): Kind3 } /** * @since 2.2.0 */ export interface Partition3C { (fa: Kind3, refinement: Refinement): Separated< Kind3, Kind3 > (fa: Kind3, predicate: Predicate): Separated, Kind3> } /** * @category model * @since 2.2.0 */ export interface Filterable3C extends Functor3C, Compactable3C { readonly partitionMap: ( fa: Kind3, f: (a: A) => Either ) => Separated, Kind3> readonly partition: Partition3C readonly filterMap: (fa: Kind3, f: (a: A) => Option) => Kind3 readonly filter: Filter3C } /** * @since 2.0.0 */ export interface Filter4 { (fa: Kind4, refinement: Refinement): Kind4 (fa: Kind4, predicate: Predicate): Kind4 } /** * @since 2.0.0 */ export interface Partition4 { (fa: Kind4, refinement: Refinement): Separated< Kind4, Kind4 > (fa: Kind4, predicate: Predicate): Separated, Kind4> } /** * @category model * @since 2.0.0 */ export interface Filterable4 extends Functor4, Compactable4 { readonly partitionMap: ( fa: Kind4, f: (a: A) => Either ) => Separated, Kind4> readonly partition: Partition4 readonly filterMap: (fa: Kind4, f: (a: A) => Option) => Kind4 readonly filter: Filter4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `filter` composition. * * @since 2.10.0 */ export function filter( F: Functor2, G: Filterable2C ): { (refinement: Refinement): (fga: Kind2>) => Kind2> (predicate: Predicate): (fgb: Kind2>) => Kind2> (predicate: Predicate): (fga: Kind2>) => Kind2> } export function filter( F: Functor1, G: Filterable2C ): { (refinement: Refinement): (fga: Kind>) => Kind> (predicate: Predicate): (fgb: Kind>) => Kind> (predicate: Predicate): (fga: Kind>) => Kind> } export function filter( F: Functor1, G: Filterable1 ): { (refinement: Refinement): (fga: Kind>) => Kind> (predicate: Predicate): (fgb: Kind>) => Kind> (predicate: Predicate): (fga: Kind>) => Kind> } export function filter( F: Functor, G: Filterable ): { (refinement: Refinement): (fga: HKT>) => HKT> (predicate: Predicate): (fgb: HKT>) => HKT> (predicate: Predicate): (fga: HKT>) => HKT> } export function filter( F: Functor, G: Filterable ): (predicate: Predicate) => (fga: HKT>) => HKT> { return (predicate) => (fga) => F.map(fga, (ga) => G.filter(ga, predicate)) } /** * `filterMap` composition. * * @since 2.10.0 */ export function filterMap( F: Functor2, G: Filterable2C ): (f: (a: A) => Option) => (fga: Kind2>) => Kind2> export function filterMap( F: Functor1, G: Filterable2C ): (f: (a: A) => Option) => (fga: Kind>) => Kind> export function filterMap( F: Functor1, G: Filterable1 ): (f: (a: A) => Option) => (fga: Kind>) => Kind> export function filterMap( F: Functor, G: Filterable ): (f: (a: A) => Option) => (fga: HKT>) => HKT> export function filterMap( F: Functor, G: Filterable ): (f: (a: A) => Option) => (fga: HKT>) => HKT> { return (f) => (fga) => F.map(fga, (ga) => G.filterMap(ga, f)) } /** * `partition` composition. * * @since 2.10.0 */ export function partition( F: Functor2, G: Filterable2C ): { (refinement: Refinement): ( fga: Kind2> ) => Separated>, Kind2>> (predicate: Predicate): ( fgb: Kind2> ) => Separated>, Kind2>> (predicate: Predicate): ( fga: Kind2> ) => Separated>, Kind2>> } export function partition( F: Functor1, G: Filterable2C ): { (refinement: Refinement): ( fga: Kind> ) => Separated>, Kind>> (predicate: Predicate): ( fgb: Kind> ) => Separated>, Kind>> (predicate: Predicate): ( fga: Kind> ) => Separated>, Kind>> } export function partition( F: Functor1, G: Filterable1 ): { (refinement: Refinement): ( fga: Kind> ) => Separated>, Kind>> (predicate: Predicate): ( fgb: Kind> ) => Separated>, Kind>> (predicate: Predicate): (fga: Kind>) => Separated>, Kind>> } export function partition( F: Functor, G: Filterable ): { (refinement: Refinement): ( fga: HKT> ) => Separated>, HKT>> (predicate: Predicate): (fgb: HKT>) => Separated>, HKT>> (predicate: Predicate): (fga: HKT>) => Separated>, HKT>> } export function partition( F: Functor, G: Filterable ): (predicate: Predicate) => (fga: HKT>) => Separated>, HKT>> { const _filter = filter(F, G) return (predicate) => { const left = _filter(not(predicate)) const right = _filter(predicate) return (fgb) => separated(left(fgb), right(fgb)) } } /** * `partitionMap` composition. * * @since 2.10.0 */ export function partitionMap( F: Functor2, G: Filterable2C ): ( f: (a: A) => Either ) => (fa: Kind2>) => Separated>, Kind2>> export function partitionMap( F: Functor1, G: Filterable2C ): ( f: (a: A) => Either ) => (fa: Kind>) => Separated>, Kind>> export function partitionMap( F: Functor1, G: Filterable1 ): ( f: (a: A) => Either ) => (fa: Kind>) => Separated>, Kind>> export function partitionMap( F: Functor, G: Filterable ): (f: (a: A) => Either) => (fa: HKT>) => Separated>, HKT>> export function partitionMap( F: Functor, G: Filterable ): (f: (a: A) => Either) => (fa: HKT>) => Separated>, HKT>> { const _filterMap = filterMap(F, G) return (f) => (fga) => separated( pipe( fga, _filterMap((a) => getLeft(f(a))) ), pipe( fga, _filterMap((a) => getRight(f(a))) ) ) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition extends FunctorComposition, CompactableComposition { readonly partitionMap: ( fa: HKT>, f: (a: A) => Either ) => Separated>, HKT>> readonly partition: ( fa: HKT>, predicate: Predicate ) => Separated>, HKT>> readonly filterMap: (fa: HKT>, f: (a: A) => Option) => HKT> readonly filter: (fa: HKT>, predicate: Predicate) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition11 extends FunctorComposition11, CompactableComposition11 { readonly partitionMap: ( fa: Kind>, f: (a: A) => Either ) => Separated>, Kind>> readonly partition: ( fa: Kind>, predicate: Predicate ) => Separated>, Kind>> readonly filterMap: (fa: Kind>, f: (a: A) => Option) => Kind> readonly filter: (fa: Kind>, predicate: Predicate) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition12 extends FunctorComposition12, CompactableComposition12 { readonly partitionMap: ( fa: Kind>, f: (a: A) => Either ) => Separated>, Kind>> readonly partition: ( fa: Kind>, predicate: Predicate ) => Separated>, Kind>> readonly filterMap: (fa: Kind>, f: (a: A) => Option) => Kind> readonly filter: (fa: Kind>, predicate: Predicate) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition12C extends FunctorComposition12C, CompactableComposition12C { readonly partitionMap: ( fa: Kind>, f: (a: A) => Either ) => Separated>, Kind>> readonly partition: ( fa: Kind>, predicate: Predicate ) => Separated>, Kind>> readonly filterMap: (fa: Kind>, f: (a: A) => Option) => Kind> readonly filter: (fa: Kind>, predicate: Predicate) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition21 extends FunctorComposition21, CompactableComposition21 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: (fa: Kind2>, f: (a: A) => Option) => Kind2> readonly filter: (fa: Kind2>, predicate: Predicate) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition2C1 extends FunctorComposition21, CompactableComposition21 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: (fa: Kind2>, f: (a: A) => Option) => Kind2> readonly filter: (fa: Kind2>, predicate: Predicate) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition22 extends FunctorComposition22, CompactableComposition22 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: ( fa: Kind2>, f: (a: A) => Option ) => Kind2> readonly filter: ( fa: Kind2>, predicate: Predicate ) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FilterableComposition22C extends FunctorComposition22, CompactableComposition22 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: ( fa: Kind2>, f: (a: A) => Option ) => Kind2> readonly filter: (fa: Kind2>, predicate: Predicate) => Kind2> } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface FilterableComposition23C extends FunctorComposition23, CompactableComposition23 { readonly partitionMap: ( fa: Kind2>, f: (a: A) => Either ) => Separated>, Kind2>> readonly partition: ( fa: Kind2>, predicate: Predicate ) => Separated>, Kind2>> readonly filterMap: ( fa: Kind2>, f: (a: A) => Option ) => Kind2> readonly filter: ( fa: Kind2>, predicate: Predicate ) => Kind2> } /** * Use * * - [`filter`](#filter) * - [`filterMap`](#filtermap) * - [`partition`](#partition) * - [`partitionMap`](#partitionmap) * * instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getFilterableComposition( F: Functor2, G: Filterable3C ): FilterableComposition23C /** @deprecated */ export function getFilterableComposition( F: Functor2, G: Filterable2C ): FilterableComposition22C /** @deprecated */ export function getFilterableComposition( F: Functor2, G: Filterable2 ): FilterableComposition22 /** @deprecated */ export function getFilterableComposition( F: Functor2C, G: Filterable1 ): FilterableComposition2C1 /** @deprecated */ export function getFilterableComposition( F: Functor2, G: Filterable1 ): FilterableComposition21 /** @deprecated */ export function getFilterableComposition( F: Functor1, G: Filterable2C ): FilterableComposition12C /** @deprecated */ export function getFilterableComposition( F: Functor1, G: Filterable2 ): FilterableComposition12 /** @deprecated */ export function getFilterableComposition( F: Functor1, G: Filterable1 ): FilterableComposition11 /** @deprecated */ export function getFilterableComposition(F: Functor, G: Filterable): FilterableComposition /** @deprecated */ export function getFilterableComposition(F: Functor, G: Filterable): FilterableComposition { const map = getFunctorComposition(F, G).map const _compact = compact(F, G) const _separate = separate(F, G, G) const _filter = filter(F, G) const _filterMap = filterMap(F, G) const _partition = partition(F, G) const _partitionMap = partitionMap(F, G) return { map, compact: _compact, separate: _separate, filter: (fga, f) => pipe(fga, _filter(f)), filterMap: (fga, f) => pipe(fga, _filterMap(f)), partition: (fga, p) => pipe(fga, _partition(p)), partitionMap: (fga, f) => pipe(fga, _partitionMap(f)) } } ================================================ FILE: src/FilterableWithIndex.ts ================================================ /** * @since 2.0.0 */ import { Either } from './Either' import { Filterable, Filterable1, Filterable2, Filterable2C, Filterable3, Filterable3C, Filterable4 } from './Filterable' import { FunctorWithIndex, FunctorWithIndex1, FunctorWithIndex2, FunctorWithIndex2C, FunctorWithIndex3, FunctorWithIndex3C, FunctorWithIndex4 } from './FunctorWithIndex' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Option } from './Option' import { Separated } from './Separated' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export type RefinementWithIndex = (i: I, a: A) => a is B /** * @since 2.0.0 */ export type PredicateWithIndex = (i: I, a: A) => boolean /** * @since 2.0.0 */ export interface FilterWithIndex { (fa: HKT, refinementWithIndex: RefinementWithIndex): HKT (fa: HKT, predicateWithIndex: PredicateWithIndex): HKT } /** * @since 2.0.0 */ export interface PartitionWithIndex { (fa: HKT, refinementWithIndex: RefinementWithIndex): Separated, HKT> (fa: HKT, predicateWithIndex: PredicateWithIndex): Separated, HKT> } /** * @category model * @since 2.0.0 */ export interface FilterableWithIndex extends FunctorWithIndex, Filterable { readonly partitionMapWithIndex: ( fa: HKT, f: (i: I, a: A) => Either ) => Separated, HKT> readonly partitionWithIndex: PartitionWithIndex readonly filterMapWithIndex: (fa: HKT, f: (i: I, a: A) => Option) => HKT readonly filterWithIndex: FilterWithIndex } /** * @since 2.0.0 */ export interface FilterWithIndex1 { (fa: Kind, refinementWithIndex: RefinementWithIndex): Kind (fa: Kind, predicateWithIndex: PredicateWithIndex): Kind } /** * @since 2.0.0 */ export interface PartitionWithIndex1 { (fa: Kind, refinementWithIndex: RefinementWithIndex): Separated, Kind> (fa: Kind, predicateWithIndex: PredicateWithIndex): Separated, Kind> } /** * @category model * @since 2.0.0 */ export interface FilterableWithIndex1 extends FunctorWithIndex1, Filterable1 { readonly partitionMapWithIndex: ( fa: Kind, f: (i: I, a: A) => Either ) => Separated, Kind> readonly partitionWithIndex: PartitionWithIndex1 readonly filterMapWithIndex: (fa: Kind, f: (i: I, a: A) => Option) => Kind readonly filterWithIndex: FilterWithIndex1 } /** * @since 2.0.0 */ export interface FilterWithIndex2 { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Kind2 (fa: Kind2, predicateWithIndex: PredicateWithIndex): Kind2 } /** * @since 2.0.0 */ export interface PartitionWithIndex2 { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Separated< Kind2, Kind2 > (fa: Kind2, predicateWithIndex: PredicateWithIndex): Separated, Kind2> } /** * @category model * @since 2.0.0 */ export interface FilterableWithIndex2 extends FunctorWithIndex2, Filterable2 { readonly partitionMapWithIndex: ( fa: Kind2, f: (i: I, a: A) => Either ) => Separated, Kind2> readonly partitionWithIndex: PartitionWithIndex2 readonly filterMapWithIndex: (fa: Kind2, f: (i: I, a: A) => Option) => Kind2 readonly filterWithIndex: FilterWithIndex2 } /** * @since 2.0.0 */ export interface FilterWithIndex2C { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Kind2 (fa: Kind2, predicateWithIndex: PredicateWithIndex): Kind2 } /** * @since 2.0.0 */ export interface PartitionWithIndex2C { (fa: Kind2, refinementWithIndex: RefinementWithIndex): Separated< Kind2, Kind2 > (fa: Kind2, predicateWithIndex: PredicateWithIndex): Separated, Kind2> } /** * @category model * @since 2.0.0 */ export interface FilterableWithIndex2C extends FunctorWithIndex2C, Filterable2C { readonly partitionMapWithIndex: ( fa: Kind2, f: (i: I, a: A) => Either ) => Separated, Kind2> readonly partitionWithIndex: PartitionWithIndex2C readonly filterMapWithIndex: (fa: Kind2, f: (i: I, a: A) => Option) => Kind2 readonly filterWithIndex: FilterWithIndex2C } /** * @since 2.0.0 */ export interface FilterWithIndex3 { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Kind3 (fa: Kind3, predicateWithIndex: PredicateWithIndex): Kind3 } /** * @since 2.2.0 */ export interface FilterWithIndex3C { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Kind3 (fa: Kind3, predicateWithIndex: PredicateWithIndex): Kind3 } /** * @category model * @since 2.2.0 */ export interface FilterableWithIndex3C extends FunctorWithIndex3C, Filterable3C { readonly partitionMapWithIndex: ( fa: Kind3, f: (i: I, a: A) => Either ) => Separated, Kind3> readonly partitionWithIndex: PartitionWithIndex3C readonly filterMapWithIndex: (fa: Kind3, f: (i: I, a: A) => Option) => Kind3 readonly filterWithIndex: FilterWithIndex3C } /** * @since 2.0.0 */ export interface PartitionWithIndex3 { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Separated< Kind3, Kind3 > (fa: Kind3, predicateWithIndex: PredicateWithIndex): Separated< Kind3, Kind3 > } /** * @since 2.2.0 */ export interface PartitionWithIndex3C { (fa: Kind3, refinementWithIndex: RefinementWithIndex): Separated< Kind3, Kind3 > (fa: Kind3, predicateWithIndex: PredicateWithIndex): Separated< Kind3, Kind3 > } /** * @category model * @since 2.0.0 */ export interface FilterableWithIndex3 extends FunctorWithIndex3, Filterable3 { readonly partitionMapWithIndex: ( fa: Kind3, f: (i: I, a: A) => Either ) => Separated, Kind3> readonly partitionWithIndex: PartitionWithIndex3 readonly filterMapWithIndex: (fa: Kind3, f: (i: I, a: A) => Option) => Kind3 readonly filterWithIndex: FilterWithIndex3 } /** * @since 2.0.0 */ export interface FilterWithIndex4 { (fa: Kind4, refinementWithIndex: RefinementWithIndex): Kind4< F, S, R, E, B > (fa: Kind4, predicateWithIndex: PredicateWithIndex): Kind4 } /** * @since 2.0.0 */ export interface PartitionWithIndex4 { (fa: Kind4, refinementWithIndex: RefinementWithIndex): Separated< Kind4, Kind4 > (fa: Kind4, predicateWithIndex: PredicateWithIndex): Separated< Kind4, Kind4 > } /** * @category model * @since 2.0.0 */ export interface FilterableWithIndex4 extends FunctorWithIndex4, Filterable4 { readonly partitionMapWithIndex: ( fa: Kind4, f: (i: I, a: A) => Either ) => Separated, Kind4> readonly partitionWithIndex: PartitionWithIndex4 readonly filterMapWithIndex: ( fa: Kind4, f: (i: I, a: A) => Option ) => Kind4 readonly filterWithIndex: FilterWithIndex4 } ================================================ FILE: src/Foldable.ts ================================================ /** * @since 2.0.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3 } from './Applicative' import { constant, pipe } from './function' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C } from './Monad' import { Monoid } from './Monoid' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Foldable { readonly URI: F readonly reduce: (fa: HKT, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: HKT, f: (a: A) => M) => M readonly reduceRight: (fa: HKT, b: B, f: (a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface Foldable1 { readonly URI: F readonly reduce: (fa: Kind, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind, f: (a: A) => M) => M readonly reduceRight: (fa: Kind, b: B, f: (a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface Foldable2 { readonly URI: F readonly reduce: (fa: Kind2, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2, b: B, f: (a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface Foldable2C { readonly URI: F readonly _E: E readonly reduce: (fa: Kind2, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2, b: B, f: (a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface Foldable3 { readonly URI: F readonly reduce: (fa: Kind3, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind3, f: (a: A) => M) => M readonly reduceRight: (fa: Kind3, b: B, f: (a: A, b: B) => B) => B } /** * @category model * @since 2.2.0 */ export interface Foldable3C { readonly URI: F readonly _E: E readonly reduce: (fa: Kind3, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind3, f: (a: A) => M) => M readonly reduceRight: (fa: Kind3, b: B, f: (a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface Foldable4 { readonly URI: F readonly reduce: (fa: Kind4, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind4, f: (a: A) => M) => M readonly reduceRight: (fa: Kind4, b: B, f: (a: A, b: B) => B) => B } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `reduce` composition. * * @since 2.10.0 */ export function reduce( F: Foldable1, G: Foldable1 ): (b: B, f: (b: B, a: A) => B) => (fga: Kind>) => B export function reduce( F: Foldable, G: Foldable ): (b: B, f: (b: B, a: A) => B) => (fga: HKT>) => B export function reduce( F: Foldable, G: Foldable ): (b: B, f: (b: B, a: A) => B) => (fga: HKT>) => B { return (b, f) => (fga) => F.reduce(fga, b, (b, ga) => G.reduce(ga, b, f)) } /** * `foldMap` composition. * * @since 2.10.0 */ export function foldMap( F: Foldable1, G: Foldable1 ): (M: Monoid) => (f: (a: A) => M) => (fga: Kind>) => M export function foldMap( F: Foldable, G: Foldable ): (M: Monoid) => (f: (a: A) => M) => (fga: HKT>) => M export function foldMap( F: Foldable, G: Foldable ): (M: Monoid) => (f: (a: A) => M) => (fga: HKT>) => M { return (M) => { const foldMapF = F.foldMap(M) const foldMapG = G.foldMap(M) return (f) => (fga) => foldMapF(fga, (ga) => foldMapG(ga, f)) } } /** * `reduceRight` composition. * * @since 2.10.0 */ export function reduceRight( F: Foldable1, G: Foldable1 ): (b: B, f: (a: A, b: B) => B) => (fga: Kind>) => B export function reduceRight( F: Foldable, G: Foldable ): (b: B, f: (a: A, b: B) => B) => (fga: HKT>) => B export function reduceRight( F: Foldable, G: Foldable ): (b: B, f: (a: A, b: B) => B) => (fga: HKT>) => B { return (b, f) => (fga) => F.reduceRight(fga, b, (ga, b) => G.reduceRight(ga, b, f)) } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Similar to 'reduce', but the result is encapsulated in a monad. * * Note: this function is not generally stack-safe, e.g., for monads which build up thunks a la `IO`. * * @example * import { reduceM } from 'fp-ts/Foldable' * import { Monad, some } from 'fp-ts/Option' * import { make, Foldable } from 'fp-ts/Tree' * import { pipe } from 'fp-ts/function' * * const t = make(1, [make(2, []), make(3, []), make(4, [])]) * assert.deepStrictEqual(pipe(t, reduceM(Monad, Foldable)(0, (b, a) => (a > 2 ? some(b + a) : some(b)))), some(7)) * * @since 2.8.0 */ export function reduceM( M: Monad3, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind3) => (fa: Kind) => Kind3 export function reduceM( M: Monad3C, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind3) => (fa: Kind) => Kind3 export function reduceM( M: Monad2, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind2) => (fa: Kind) => Kind2 export function reduceM( M: Monad2C, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind2) => (fa: Kind) => Kind2 export function reduceM( M: Monad1, F: Foldable1 ): (b: B, f: (b: B, a: A) => Kind) => (fa: Kind) => Kind export function reduceM( M: Monad, F: Foldable ): (b: B, f: (b: B, a: A) => HKT) => (fa: HKT) => HKT export function reduceM( M: Monad, F: Foldable ): (b: B, f: (b: B, a: A) => HKT) => (fa: HKT) => HKT { return (b, f) => (fa) => F.reduce(fa, M.of(b), (mb, a) => M.chain(mb, (b) => f(b, a))) } // TODO: curry in v3 /** * Fold a data structure, accumulating values in some `Monoid`, combining adjacent elements using the specified separator * * @example * import { intercalate } from 'fp-ts/Foldable' * import * as S from 'fp-ts/string' * import { make, Foldable } from 'fp-ts/Tree' * * const t = make('a', [make('b', []), make('c', []), make('d', [])]) * assert.strictEqual(intercalate(S.Monoid, Foldable)('|', t), 'a|b|c|d') * * @since 2.0.0 */ export function intercalate( M: Monoid, F: Foldable3 ): (middle: M, fm: Kind3) => M export function intercalate(M: Monoid, F: Foldable2): (middle: M, fm: Kind2) => M export function intercalate( M: Monoid, F: Foldable2C ): (middle: M, fm: Kind2) => M export function intercalate(M: Monoid, F: Foldable1): (middle: M, fm: Kind) => M export function intercalate(M: Monoid, F: Foldable): (middle: M, fm: HKT) => M export function intercalate(M: Monoid, F: Foldable): (middle: M, fm: HKT) => M { interface Acc { readonly init: boolean readonly acc: M } return (middle, fm) => { const go = ({ init, acc }: Acc, x: M): Acc => init ? { init: false, acc: x } : { init: false, acc: M.concat(M.concat(acc, middle), x) } return F.reduce(fm, { init: true, acc: M.empty }, go).acc } } /** * Transforms a `Foldable` into a `toReadonlyArray`. * * @example * import { toReadonlyArray } from 'fp-ts/Foldable' * import { Foldable, make } from 'fp-ts/Tree' * * const t = make(1, [make(2, []), make(3, []), make(4, [])]) * assert.deepStrictEqual(toReadonlyArray(Foldable)(t), [1, 2, 3, 4]) * * @since 2.10.0 */ export function toReadonlyArray( F: Foldable4 ): (fa: Kind4) => ReadonlyArray export function toReadonlyArray(F: Foldable3): (fa: Kind3) => ReadonlyArray export function toReadonlyArray( F: Foldable3C ): (fa: Kind3) => ReadonlyArray export function toReadonlyArray(F: Foldable2): (fa: Kind2) => ReadonlyArray export function toReadonlyArray(F: Foldable2C): (fa: Kind2) => ReadonlyArray export function toReadonlyArray(F: Foldable1): (fa: Kind) => ReadonlyArray export function toReadonlyArray(F: Foldable): (fa: HKT) => ReadonlyArray export function toReadonlyArray(F: Foldable): (fa: HKT) => ReadonlyArray { return (fa: HKT) => F.reduce(fa, [], (acc: Array, a) => { acc.push(a) return acc }) } /** * Traverse a data structure, performing some effects encoded by an `Applicative` functor at each value, ignoring the * final result. * * @example * import { Foldable } from 'fp-ts/Array' * import { traverse_ } from 'fp-ts/Foldable' * import { Applicative } from 'fp-ts/IO' * * let log = '' * const append = (s: string) => () => (log += s) * traverse_(Applicative, Foldable)(['a', 'b', 'c'], append)() * assert.strictEqual(log, 'abc') * * @since 2.0.0 */ export function traverse_( M: Applicative3, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind3) => Kind3 export function traverse_( M: Applicative2, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind2) => Kind2 export function traverse_( M: Applicative2C, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind2) => Kind2 export function traverse_( M: Applicative1, F: Foldable1 ): (fa: Kind, f: (a: A) => Kind) => Kind export function traverse_( M: Applicative, F: Foldable ): (fa: HKT, f: (a: A) => HKT) => HKT export function traverse_( M: Applicative, F: Foldable ): (fa: HKT, f: (a: A) => HKT) => HKT { const applyFirst = (mu: HKT, mb: HKT): HKT => M.ap(M.map(mu, constant), mb) const mu: HKT = M.of(undefined) return (fa, f) => F.reduce(fa, mu, (mu, a) => applyFirst(mu, f(a))) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`reduceM`](#reducem) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export function foldM( M: Monad3, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind3) => Kind3 /** @deprecated */ export function foldM( M: Monad3C, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind3) => Kind3 /** @deprecated */ export function foldM( M: Monad2, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind2) => Kind2 /** @deprecated */ export function foldM( M: Monad2C, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind2) => Kind2 /** @deprecated */ export function foldM( M: Monad1, F: Foldable1 ): (fa: Kind, b: B, f: (b: B, a: A) => Kind) => Kind /** @deprecated */ export function foldM( M: Monad, F: Foldable ): (fa: HKT, b: B, f: (b: B, a: A) => HKT) => HKT export function foldM( M: Monad, F: Foldable ): (fa: HKT, b: B, f: (b: B, a: A) => HKT) => HKT { return (fa, b, f) => F.reduce(fa, M.of(b), (mb, a) => M.chain(mb, (b) => f(b, a))) } /** * Use [`toReadonlyArray`](#toreadonlyarray) instead * * @category zone of death * @since 2.8.0 * @deprecated */ export const toArray = toReadonlyArray /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition { readonly reduce: (fga: HKT>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: HKT>, f: (a: A) => M) => M readonly reduceRight: (fa: HKT>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition11 { readonly reduce: (fga: Kind>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition12 { readonly reduce: (fga: Kind>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition12C { readonly reduce: (fga: Kind>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition21 { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition2C1 { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition22 { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableComposition22C { readonly reduce: (fga: Kind2>, b: B, f: (b: B, a: A) => B) => B readonly foldMap: (M: Monoid) => (fa: Kind2>, f: (a: A) => M) => M readonly reduceRight: (fa: Kind2>, b: B, f: (a: A, b: B) => B) => B } /** * Use * * - [reduce](#reduce) * - [foldMap](#foldmap) * - [reduceRight](#reduceright) * * instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getFoldableComposition( F: Foldable2, G: Foldable2C ): FoldableComposition22C /** @deprecated */ export function getFoldableComposition( F: Foldable2, G: Foldable2 ): FoldableComposition22 /** @deprecated */ export function getFoldableComposition( F: Foldable2C, G: Foldable1 ): FoldableComposition2C1 /** @deprecated */ export function getFoldableComposition( F: Foldable2, G: Foldable1 ): FoldableComposition21 /** @deprecated */ export function getFoldableComposition( F: Foldable1, G: Foldable2C ): FoldableComposition12C /** @deprecated */ export function getFoldableComposition( F: Foldable1, G: Foldable2 ): FoldableComposition12 /** @deprecated */ export function getFoldableComposition( F: Foldable1, G: Foldable1 ): FoldableComposition11 /** @deprecated */ export function getFoldableComposition(F: Foldable, G: Foldable): FoldableComposition /** @deprecated */ export function getFoldableComposition(F: Foldable, G: Foldable): FoldableComposition { const _reduce = reduce(F, G) const _foldMap = foldMap(F, G) const _reduceRight = reduceRight(F, G) return { reduce: (fga, b, f) => pipe(fga, _reduce(b, f)), foldMap: (M) => { const foldMapM = _foldMap(M) return (fga, f) => pipe(fga, foldMapM(f)) }, reduceRight: (fga, b, f) => pipe(fga, _reduceRight(b, f)) } } ================================================ FILE: src/FoldableWithIndex.ts ================================================ /** * A `Foldable` with an additional index. * A `FoldableWithIndex` instance must be compatible with its `Foldable` instance * * ```ts * reduce(fa, b, f) = reduceWithIndex(fa, b, (_, b, a) => f(b, a)) * foldMap(M)(fa, f) = foldMapWithIndex(M)(fa, (_, a) => f(a)) * reduceRight(fa, b, f) = reduceRightWithIndex(fa, b, (_, a, b) => f(a, b)) * ``` * * @since 2.0.0 */ import { Foldable, Foldable1, Foldable2, Foldable2C, Foldable3, Foldable3C, Foldable4, FoldableComposition, FoldableComposition2C1, FoldableComposition11, FoldableComposition12, FoldableComposition12C, FoldableComposition21, FoldableComposition22, FoldableComposition22C, getFoldableComposition } from './Foldable' import { pipe } from './function' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monoid } from './Monoid' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface FoldableWithIndex extends Foldable { readonly reduceWithIndex: (fa: HKT, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: HKT, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: HKT, b: B, f: (i: I, a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface FoldableWithIndex1 extends Foldable1 { readonly reduceWithIndex: (fa: Kind, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind, b: B, f: (i: I, a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface FoldableWithIndex2 extends Foldable2 { readonly reduceWithIndex: (fa: Kind2, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind2, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind2, b: B, f: (i: I, a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface FoldableWithIndex2C extends Foldable2C { readonly reduceWithIndex: (fa: Kind2, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind2, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind2, b: B, f: (i: I, a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface FoldableWithIndex3 extends Foldable3 { readonly reduceWithIndex: (fa: Kind3, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind3, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind3, b: B, f: (i: I, a: A, b: B) => B) => B } /** * @category model * @since 2.2.0 */ export interface FoldableWithIndex3C extends Foldable3C { readonly reduceWithIndex: (fa: Kind3, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind3, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind3, b: B, f: (i: I, a: A, b: B) => B) => B } /** * @category model * @since 2.0.0 */ export interface FoldableWithIndex4 extends Foldable4 { readonly reduceWithIndex: (fa: Kind4, b: B, f: (i: I, b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fa: Kind4, f: (i: I, a: A) => M) => M readonly reduceRightWithIndex: (fa: Kind4, b: B, f: (i: I, a: A, b: B) => B) => B } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `reduceWithIndex` composition. * * @since 2.10.0 */ export function reduceWithIndex( F: FoldableWithIndex1, G: FoldableWithIndex1 ): (b: B, f: (ij: readonly [I, J], b: B, a: A) => B) => (fga: Kind>) => B export function reduceWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (b: B, f: (ij: readonly [I, J], b: B, a: A) => B) => (fga: HKT>) => B export function reduceWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (b: B, f: (ij: readonly [I, J], b: B, a: A) => B) => (fga: HKT>) => B { return (b, f) => (fga) => F.reduceWithIndex(fga, b, (i, b, ga) => G.reduceWithIndex(ga, b, (j, b, a) => f([i, j], b, a))) } /** * `foldMapWithIndex` composition. * * @since 2.10.0 */ export function foldMapWithIndex( F: FoldableWithIndex1, G: FoldableWithIndex1 ): (M: Monoid) => (f: (ij: readonly [I, J], a: A) => M) => (fga: Kind>) => M export function foldMapWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (M: Monoid) => (f: (ij: readonly [I, J], a: A) => M) => (fga: HKT>) => M export function foldMapWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (M: Monoid) => (f: (ij: readonly [I, J], a: A) => M) => (fga: HKT>) => M { return (M) => { const foldMapWithIndexF = F.foldMapWithIndex(M) const foldMapWithIndexG = G.foldMapWithIndex(M) return (f) => (fga) => foldMapWithIndexF(fga, (i, ga) => foldMapWithIndexG(ga, (j, a) => f([i, j], a))) } } /** * `reduceRightWithIndex` composition. * * @since 2.10.0 */ export function reduceRightWithIndex( F: FoldableWithIndex1, G: FoldableWithIndex1 ): (b: B, f: (ij: readonly [I, J], a: A, b: B) => B) => (fga: Kind>) => B export function reduceRightWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (b: B, f: (ij: readonly [I, J], a: A, b: B) => B) => (fga: HKT>) => B export function reduceRightWithIndex( F: FoldableWithIndex, G: FoldableWithIndex ): (b: B, f: (ij: readonly [I, J], a: A, b: B) => B) => (fga: HKT>) => B { return (b, f) => (fga) => F.reduceRightWithIndex(fga, b, (i, ga, b) => G.reduceRightWithIndex(ga, b, (j, a, b) => f([i, j], a, b))) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition extends FoldableComposition { readonly reduceWithIndex: (fga: HKT>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: HKT>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: HKT>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition11 extends FoldableComposition11 { readonly reduceWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition12 extends FoldableComposition12 { readonly reduceWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition12C extends FoldableComposition12C { readonly reduceWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition21 extends FoldableComposition21 { readonly reduceWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: ( M: Monoid ) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition2C1 extends FoldableComposition2C1 { readonly reduceWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: (M: Monoid) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition22 extends FoldableComposition22 { readonly reduceWithIndex: ( fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B ) => B readonly foldMapWithIndex: ( M: Monoid ) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: ( fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B ) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FoldableWithIndexComposition22C extends FoldableComposition22C { readonly reduceWithIndex: (fga: Kind2>, b: B, f: (i: [FI, GI], b: B, a: A) => B) => B readonly foldMapWithIndex: ( M: Monoid ) => (fga: Kind2>, f: (i: [FI, GI], a: A) => M) => M readonly reduceRightWithIndex: ( fga: Kind2>, b: B, f: (i: [FI, GI], a: A, b: B) => B ) => B } /** * Use * * - [reduceWithIndex](#reducewithindex) * - [foldMapWithIndex](#foldmapwithindex) * - [reduceRightWithIndex](#reducerightwithindex) * * instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex2, G: FoldableWithIndex2C ): FoldableWithIndexComposition22C /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex2, G: FoldableWithIndex2 ): FoldableWithIndexComposition22 /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex2C, G: FoldableWithIndex1 ): FoldableWithIndexComposition2C1 /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex2, G: FoldableWithIndex1 ): FoldableWithIndexComposition21 /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex1, G: FoldableWithIndex2 ): FoldableWithIndexComposition12 /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex1, G: FoldableWithIndex2 ): FoldableWithIndexComposition12 /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex1, G: FoldableWithIndex1 ): FoldableWithIndexComposition11 /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex, G: FoldableWithIndex ): FoldableWithIndexComposition /** @deprecated */ export function getFoldableWithIndexComposition( F: FoldableWithIndex, G: FoldableWithIndex ): FoldableWithIndexComposition { const FC = getFoldableComposition(F, G) const _reduceWithIndex = reduceWithIndex(F, G) const _foldMapWithIndex = foldMapWithIndex(F, G) const _reduceRightWithIndex = reduceRightWithIndex(F, G) return { reduce: FC.reduce, foldMap: FC.foldMap, reduceRight: FC.reduceRight, reduceWithIndex: (fga, b, f: any) => pipe(fga, _reduceWithIndex(b, f)), foldMapWithIndex: (M) => { const foldMapWithIndexM = _foldMapWithIndex(M) return (fga, f: any) => pipe(fga, foldMapWithIndexM(f)) }, reduceRightWithIndex: (fga, b, f: any) => pipe(fga, _reduceRightWithIndex(b, f)) } } ================================================ FILE: src/FromEither.ts ================================================ /** * The `FromEither` type class represents those data types which support errors. * * @since 2.10.0 */ import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4, tap } from './Chain' import { Either } from './Either' import { flow, LazyArg } from './function' import { HKT2, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import * as _ from './internal' import { Option } from './Option' import { Predicate } from './Predicate' import { Refinement } from './Refinement' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.10.0 */ export interface FromEither { readonly URI: F readonly fromEither: (e: Either) => HKT2 } /** * @category model * @since 2.11.0 */ export interface FromEither1 { readonly URI: F readonly fromEither: (fa: Either) => Kind } /** * @category model * @since 2.10.0 */ export interface FromEither2 { readonly URI: F readonly fromEither: (fa: Either) => Kind2 } /** * @category model * @since 2.10.0 */ export interface FromEither2C { readonly URI: F readonly _E: E readonly fromEither: (fa: Either) => Kind2 } /** * @category model * @since 2.10.0 */ export interface FromEither3 { readonly URI: F readonly fromEither: (fa: Either) => Kind3 } /** * @category model * @since 2.10.0 */ export interface FromEither3C { readonly URI: F readonly _E: E readonly fromEither: (fa: Either) => Kind3 } /** * @category model * @since 2.10.0 */ export interface FromEither4 { readonly URI: F readonly fromEither: (fa: Either) => Kind4 } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.10.0 */ export function fromOption( F: FromEither4 ): (onNone: LazyArg) => (fa: Option) => Kind4 export function fromOption( F: FromEither3 ): (onNone: LazyArg) => (fa: Option) => Kind3 export function fromOption( F: FromEither3C ): (onNone: LazyArg) => (fa: Option) => Kind3 export function fromOption( F: FromEither2 ): (onNone: LazyArg) => (fa: Option) => Kind2 export function fromOption( F: FromEither2C ): (onNone: LazyArg) => (fa: Option) => Kind2 export function fromOption(F: FromEither): (onNone: LazyArg) => (ma: Option) => HKT2 export function fromOption(F: FromEither): (onNone: LazyArg) => (ma: Option) => HKT2 { return (onNone) => (ma) => F.fromEither(_.isNone(ma) ? _.left(onNone()) : _.right(ma.value)) } /** * @category lifting * @since 2.10.0 */ export function fromPredicate( F: FromEither4 ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind4 } export function fromPredicate( F: FromEither3 ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } export function fromPredicate( F: FromEither3C ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } export function fromPredicate( F: FromEither2 ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } export function fromPredicate( F: FromEither2C ): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } export function fromPredicate(F: FromEither): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => HKT2 } export function fromPredicate(F: FromEither): { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (b: B) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => HKT2 } { return (predicate: Predicate, onFalse: (a: A) => E) => (a: A) => F.fromEither(predicate(a) ? _.right(a) : _.left(onFalse(a))) } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function fromOptionK( F: FromEither4 ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind4 export function fromOptionK( F: FromEither3 ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind3 export function fromOptionK( F: FromEither3C ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind3 export function fromOptionK( F: FromEither2 ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind2 export function fromOptionK( F: FromEither2C ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => Kind2 export function fromOptionK( F: FromEither ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => HKT2 export function fromOptionK( F: FromEither ): ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => HKT2 { const fromOptionF = fromOption(F) return (onNone) => { const from = fromOptionF(onNone) return (f) => flow(f, from) } } /** * @since 2.10.0 */ export function chainOptionK( F: FromEither4, M: Chain4 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind4) => Kind4 export function chainOptionK( F: FromEither3, M: Chain3 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind3) => Kind3 export function chainOptionK( F: FromEither3C, M: Chain3C ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind3) => Kind3 export function chainOptionK( F: FromEither2, M: Chain2 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind2) => Kind2 export function chainOptionK( F: FromEither2C, M: Chain2C ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind2) => Kind2 export function chainOptionK( F: FromEither, M: Chain ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: HKT2) => HKT2 export function chainOptionK( F: FromEither2, M: Chain2 ): (onNone: LazyArg) => (f: (a: A) => Option) => (ma: Kind2) => Kind2 { const fromOptionKF = fromOptionK(F) return (onNone) => { const from = fromOptionKF(onNone) return (f) => (ma) => M.chain(ma, from(f)) } } /** * @since 2.10.0 */ export function fromEitherK( F: FromEither4 ): , E, B>(f: (...a: A) => Either) => (...a: A) => Kind4 export function fromEitherK( F: FromEither3 ): , E, B>(f: (...a: A) => Either) => (...a: A) => Kind3 export function fromEitherK( F: FromEither3C ): , B>(f: (...a: A) => Either) => (...a: A) => Kind3 export function fromEitherK( F: FromEither2 ): , E, B>(f: (...a: A) => Either) => (...a: A) => Kind2 export function fromEitherK( F: FromEither2C ): , B>(f: (...a: A) => Either) => (...a: A) => Kind2 export function fromEitherK( F: FromEither1 ): , B>(f: (...a: A) => Either) => (...a: A) => Kind export function fromEitherK( F: FromEither ): , E, B>(f: (...a: A) => Either) => (...a: A) => HKT2 export function fromEitherK( F: FromEither ): , E, B>(f: (...a: A) => Either) => (...a: A) => HKT2 { return (f) => flow(f, F.fromEither) } /** * @since 2.10.0 */ export function chainEitherK( F: FromEither4, M: Chain4 ): (f: (a: A) => Either) => (ma: Kind4) => Kind4 export function chainEitherK( F: FromEither3, M: Chain3 ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export function chainEitherK( F: FromEither3C, M: Chain3C ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export function chainEitherK( F: FromEither2, M: Chain2 ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export function chainEitherK( F: FromEither2C, M: Chain2C ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export function chainEitherK( F: FromEither1, M: Chain1 ): (f: (a: A) => Either) => (ma: Kind) => Kind export function chainEitherK( F: FromEither, M: Chain ): (f: (a: A) => Either) => (ma: HKT2) => HKT2 export function chainEitherK( F: FromEither2, M: Chain2 ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 { const fromEitherKF = fromEitherK(F) return (f) => (ma) => M.chain(ma, fromEitherKF(f)) } /** * @since 2.12.0 */ export function chainFirstEitherK( F: FromEither4, M: Chain4 ): (f: (a: A) => Either) => (ma: Kind4) => Kind4 export function chainFirstEitherK( F: FromEither3, M: Chain3 ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export function chainFirstEitherK( F: FromEither3C, M: Chain3C ): (f: (a: A) => Either) => (ma: Kind3) => Kind3 export function chainFirstEitherK( F: FromEither2, M: Chain2 ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export function chainFirstEitherK( F: FromEither2C, M: Chain2C ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 export function chainFirstEitherK( F: FromEither1, M: Chain1 ): (f: (a: A) => Either) => (ma: Kind) => Kind export function chainFirstEitherK( F: FromEither, M: Chain ): (f: (a: A) => Either) => (ma: HKT2) => HKT2 export function chainFirstEitherK( F: FromEither2, M: Chain2 ): (f: (a: A) => Either) => (ma: Kind2) => Kind2 { const tapEitherM = tapEither(F, M) return (f) => (ma) => tapEitherM(ma, f) } /** * @since 2.10.0 */ export function filterOrElse( F: FromEither4, M: Chain4 ): { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind4 ) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): ( mb: Kind4 ) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind4) => Kind4 } export function filterOrElse( F: FromEither3, M: Chain3 ): { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind3 ) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind3) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } export function filterOrElse( F: FromEither3C, M: Chain3C ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind3) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind3) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } export function filterOrElse( F: FromEither2, M: Chain2 ): { (refinement: Refinement, onFalse: (a: A) => E): (self: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (self: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (self: Kind2) => Kind2 } export function filterOrElse( F: FromEither2C, M: Chain2C ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } export function filterOrElse( F: FromEither, M: Chain ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: HKT2) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (mb: HKT2) => HKT2 (predicate: Predicate, onFalse: (a: A) => E): (ma: HKT2) => HKT2 } export function filterOrElse( F: FromEither2, M: Chain2 ): { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (mb: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } { return (predicate: Predicate, onFalse: (a: A) => E) => (ma: Kind2): Kind2 => M.chain(ma, (a) => F.fromEither(predicate(a) ? _.right(a) : _.left(onFalse(a)))) } /** @internal */ export function tapEither( F: FromEither4, M: Chain4 ): (self: Kind4, f: (a: A) => Either) => Kind4 /** @internal */ export function tapEither( F: FromEither3, M: Chain3 ): (self: Kind3, f: (a: A) => Either) => Kind3 /** @internal */ export function tapEither( F: FromEither3C, M: Chain3C ): (self: Kind3, f: (a: A) => Either) => Kind3 /** @internal */ export function tapEither( F: FromEither2, M: Chain2 ): (self: Kind2, f: (a: A) => Either) => Kind2 /** @internal */ export function tapEither( F: FromEither2C, M: Chain2C ): (self: Kind2, f: (a: A) => Either) => Kind2 /** @internal */ export function tapEither( F: FromEither1, M: Chain1 ): (self: Kind, f: (a: A) => Either) => Kind /** @internal */ export function tapEither( F: FromEither, M: Chain ): (self: HKT2, f: (a: A) => Either) => HKT2 /** @internal */ export function tapEither( F: FromEither2, M: Chain2 ): (self: Kind2, f: (a: A) => Either) => Kind2 { const fromEither = fromEitherK(F) const tapM = tap(M) return (self, f) => tapM(self, fromEither(f)) } ================================================ FILE: src/FromIO.ts ================================================ /** * Lift a computation from the `IO` monad * * @since 2.10.0 */ import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4, tap } from './Chain' import { flow } from './function' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { IO } from './IO' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.10.0 */ export interface FromIO { readonly URI: F readonly fromIO: (fa: IO) => HKT } /** * @category model * @since 2.10.0 */ export interface FromIO1 { readonly URI: F readonly fromIO: (fa: IO) => Kind } /** * @category model * @since 2.10.0 */ export interface FromIO2 { readonly URI: F readonly fromIO: (fa: IO) => Kind2 } /** * @category model * @since 2.10.0 */ export interface FromIO2C { readonly URI: F readonly _E: E readonly fromIO: (fa: IO) => Kind2 } /** * @category model * @since 2.10.0 */ export interface FromIO3 { readonly URI: F readonly fromIO: (fa: IO) => Kind3 } /** * @category model * @since 2.10.0 */ export interface FromIO3C { readonly URI: F readonly _E: E readonly fromIO: (fa: IO) => Kind3 } /** * @category model * @since 2.10.0 */ export interface FromIO4 { readonly URI: F readonly fromIO: (fa: IO) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function fromIOK( F: FromIO4 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind4 export function fromIOK( F: FromIO3 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind3 export function fromIOK( F: FromIO3C ): , B>(f: (...a: A) => IO) => (...a: A) => Kind3 export function fromIOK( F: FromIO2 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind2 export function fromIOK( F: FromIO2C ): , B>(f: (...a: A) => IO) => (...a: A) => Kind2 export function fromIOK( F: FromIO1 ): , B>(f: (...a: A) => IO) => (...a: A) => Kind export function fromIOK( F: FromIO ): , B>(f: (...a: A) => IO) => (...a: A) => HKT export function fromIOK( F: FromIO ): , B>(f: (...a: A) => IO) => (...a: A) => HKT { return (f) => flow(f, F.fromIO) } /** * @since 2.10.0 */ export function chainIOK( F: FromIO4, M: Chain4 ): (f: (a: A) => IO) => (first: Kind4) => Kind4 export function chainIOK( F: FromIO3, M: Chain3 ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export function chainIOK( F: FromIO3C, M: Chain3C ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export function chainIOK( F: FromIO2, M: Chain2 ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export function chainIOK( F: FromIO2C, M: Chain2C ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export function chainIOK( F: FromIO1, M: Chain1 ): (f: (a: A) => IO) => (first: Kind) => Kind export function chainIOK(F: FromIO, M: Chain): (f: (a: A) => IO) => (first: HKT) => HKT export function chainIOK(F: FromIO, M: Chain): (f: (a: A) => IO) => (first: HKT) => HKT { return (f) => { const g = flow(f, F.fromIO) return (first) => M.chain(first, g) } } /** * @since 2.10.0 */ export function chainFirstIOK( F: FromIO4, M: Chain4 ): (f: (a: A) => IO) => (first: Kind4) => Kind4 export function chainFirstIOK( F: FromIO3, M: Chain3 ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export function chainFirstIOK( F: FromIO3C, M: Chain3C ): (f: (a: A) => IO) => (first: Kind3) => Kind3 export function chainFirstIOK( F: FromIO2, M: Chain2 ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export function chainFirstIOK( F: FromIO2C, M: Chain2C ): (f: (a: A) => IO) => (first: Kind2) => Kind2 export function chainFirstIOK( F: FromIO1, M: Chain1 ): (f: (a: A) => IO) => (first: Kind) => Kind export function chainFirstIOK( F: FromIO, M: Chain ): (f: (a: A) => IO) => (first: HKT) => HKT export function chainFirstIOK( F: FromIO, M: Chain ): (f: (a: A) => IO) => (first: HKT) => HKT { const tapIOM = tapIO(F, M) return (f) => (first) => tapIOM(first, f) } /** @internal */ export function tapIO( F: FromIO4, M: Chain4 ): (self: Kind4, f: (a: A) => IO) => Kind4 /** @internal */ export function tapIO( F: FromIO3, M: Chain3 ): (self: Kind3, f: (a: A) => IO) => Kind3 /** @internal */ export function tapIO( F: FromIO3C, M: Chain3C ): (self: Kind3, f: (a: A) => IO) => Kind3 /** @internal */ export function tapIO( F: FromIO2, M: Chain2 ): (self: Kind2, f: (a: A) => IO) => Kind2 /** @internal */ export function tapIO( F: FromIO2C, M: Chain2C ): (self: Kind2, f: (a: A) => IO) => Kind2 /** @internal */ export function tapIO( F: FromIO1, M: Chain1 ): (self: Kind, f: (a: A) => IO) => Kind /** @internal */ export function tapIO(F: FromIO, M: Chain): (self: HKT, f: (a: A) => IO) => HKT /** @internal */ export function tapIO(F: FromIO, M: Chain): (self: HKT, f: (a: A) => IO) => HKT { const chainFirstM = tap(M) return (self, f) => chainFirstM(self, flow(f, F.fromIO)) } ================================================ FILE: src/FromReader.ts ================================================ /** * Lift a computation from the `Reader` monad. * * @since 2.11.0 */ import { Chain, Chain2, Chain3, Chain3C, Chain4, tap } from './Chain' import { flow } from './function' import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' import * as R from './Reader' import Reader = R.Reader // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.11.0 */ export interface FromReader { readonly URI: F readonly fromReader: (fa: Reader) => HKT2 } /** * @category model * @since 2.11.0 */ export interface FromReader2 { readonly URI: F readonly fromReader: (fa: Reader) => Kind2 } /** * @category model * @since 2.11.0 */ export interface FromReader3 { readonly URI: F readonly fromReader: (fa: Reader) => Kind3 } /** * @category model * @since 2.11.0 */ export interface FromReader3C { readonly URI: F readonly _E: E readonly fromReader: (fa: Reader) => Kind3 } /** * @category model * @since 2.11.0 */ export interface FromReader4 { readonly URI: F readonly fromReader: (fa: Reader) => Kind4 } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.11.0 */ export function ask(F: FromReader4): () => Kind4 export function ask(F: FromReader3): () => Kind3 export function ask(F: FromReader3C): () => Kind3 export function ask(F: FromReader2): () => Kind2 export function ask(F: FromReader): () => HKT2 export function ask(F: FromReader): () => HKT2 { return () => F.fromReader(R.ask()) } /** * @category constructors * @since 2.11.0 */ export function asks(F: FromReader4): (f: (r: R) => A) => Kind4 export function asks(F: FromReader3): (f: (r: R) => A) => Kind3 export function asks(F: FromReader3C): (f: (r: R) => A) => Kind3 export function asks(F: FromReader2): (f: (r: R) => A) => Kind2 export function asks(F: FromReader): (f: (r: R) => A) => HKT2 export function asks(F: FromReader): (f: (r: R) => A) => HKT2 { return F.fromReader } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function fromReaderK( F: FromReader4 ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind4 export function fromReaderK( F: FromReader3 ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind3 export function fromReaderK( F: FromReader3C ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind3 export function fromReaderK( F: FromReader2 ): , R, B>(f: (...a: A) => Reader) => (...a: A) => Kind2 export function fromReaderK( F: FromReader ): , R, B>(f: (...a: A) => Reader) => (...a: A) => HKT2 export function fromReaderK( F: FromReader ): , R, B>(f: (...a: A) => Reader) => (...a: A) => HKT2 { return (f) => flow(f, F.fromReader) } /** * @since 2.11.0 */ export function chainReaderK( F: FromReader4, M: Chain4 ): (f: (a: A) => Reader) => (ma: Kind4) => Kind4 export function chainReaderK( F: FromReader3, M: Chain3 ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export function chainReaderK( F: FromReader3C, M: Chain3C ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export function chainReaderK( F: FromReader2, M: Chain2 ): (f: (a: A) => Reader) => (ma: Kind2) => Kind2 export function chainReaderK( F: FromReader, M: Chain ): (f: (a: A) => Reader) => (ma: HKT2) => HKT2 export function chainReaderK( F: FromReader2, M: Chain2 ): (f: (a: A) => Reader) => (ma: Kind2) => Kind2 { const fromReaderKF = fromReaderK(F) return (f) => (ma) => M.chain(ma, fromReaderKF(f)) } /** * @since 2.11.0 */ export function chainFirstReaderK( F: FromReader4, M: Chain4 ): (f: (a: A) => Reader) => (ma: Kind4) => Kind4 export function chainFirstReaderK( F: FromReader3, M: Chain3 ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export function chainFirstReaderK( F: FromReader3C, M: Chain3C ): (f: (a: A) => Reader) => (ma: Kind3) => Kind3 export function chainFirstReaderK( F: FromReader2, M: Chain2 ): (f: (a: A) => Reader) => (ma: Kind2) => Kind2 export function chainFirstReaderK( F: FromReader, M: Chain ): (f: (a: A) => Reader) => (ma: HKT2) => HKT2 export function chainFirstReaderK( F: FromReader2, M: Chain2 ): (f: (a: A) => Reader) => (ma: Kind2) => Kind2 { const tapM = tapReader(F, M) return (f) => (self) => tapM(self, f) } /** @internal */ export function tapReader( F: FromReader4, M: Chain4 ): (self: Kind4, f: (a: A) => Reader) => Kind4 /** @internal */ export function tapReader( F: FromReader3, M: Chain3 ): (self: Kind3, f: (a: A) => Reader) => Kind3 /** @internal */ export function tapReader( F: FromReader3C, M: Chain3C ): (self: Kind3, f: (a: A) => Reader) => Kind3 /** @internal */ export function tapReader( F: FromReader2, M: Chain2 ): (self: Kind2, f: (a: A) => Reader) => Kind2 export function tapReader( F: FromReader, M: Chain ): (self: HKT2, f: (a: A) => Reader) => HKT2 /** @internal */ export function tapReader( F: FromReader2, M: Chain2 ): (self: Kind2, f: (a: A) => Reader) => Kind2 { const tapM = tap(M) return (self, f) => tapM(self, flow(f, F.fromReader)) } ================================================ FILE: src/FromState.ts ================================================ /** * Lift a computation from the `State` monad. * * @since 2.11.0 */ import { Chain, Chain2, Chain3, Chain4 } from './Chain' import { Endomorphism } from './Endomorphism' import { flow } from './function' import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' import * as S from './State' import State = S.State // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.11.0 */ export interface FromState { readonly URI: F readonly fromState: (fa: State) => HKT2 } /** * @category model * @since 2.11.0 */ export interface FromState2 { readonly URI: F readonly fromState: (fa: State) => Kind2 } /** * @category model * @since 2.11.0 */ export interface FromState3 { readonly URI: F readonly fromState: (fa: State) => Kind3 } /** * @category model * @since 2.11.0 */ export interface FromState3C { readonly URI: F readonly _E: E readonly fromState: (fa: State) => Kind3 } /** * @category model * @since 2.11.0 */ export interface FromState4 { readonly URI: F readonly fromState: (fa: State) => Kind4 } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.11.0 */ export function get(F: FromState4): () => Kind4 export function get(F: FromState3): () => Kind3 export function get(F: FromState3C): () => Kind3 export function get(F: FromState2): () => Kind2 export function get(F: FromState): () => HKT2 export function get(F: FromState): () => HKT2 { return () => F.fromState(S.get()) } /** * @category constructors * @since 2.11.0 */ export function put(F: FromState4): (s: S) => Kind4 export function put(F: FromState3): (s: S) => Kind3 export function put(F: FromState3C): (s: S) => Kind3 export function put(F: FromState2): (s: S) => Kind2 export function put(F: FromState): (s: S) => HKT2 export function put(F: FromState): (s: S) => HKT2 { return (s) => F.fromState(S.put(s)) } /** * @category constructors * @since 2.11.0 */ export function modify(F: FromState4): (f: Endomorphism) => Kind4 export function modify(F: FromState3): (f: Endomorphism) => Kind3 export function modify(F: FromState3C): (f: Endomorphism) => Kind3 export function modify(F: FromState2): (f: Endomorphism) => Kind2 export function modify(F: FromState): (f: Endomorphism) => HKT2 export function modify(F: FromState): (f: Endomorphism) => HKT2 { return flow(S.modify, F.fromState) } /** * @category constructors * @since 2.11.0 */ export function gets(F: FromState4): (f: (s: S) => A) => Kind4 export function gets(F: FromState3): (f: (s: S) => A) => Kind3 export function gets(F: FromState3C): (f: (s: S) => A) => Kind3 export function gets(F: FromState2): (f: (s: S) => A) => Kind2 export function gets(F: FromState): (f: (s: S) => A) => HKT2 export function gets(F: FromState): (f: (s: S) => A) => HKT2 { return flow(S.gets, F.fromState) } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function fromStateK( F: FromState4 ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind4 export function fromStateK( F: FromState3 ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind3 export function fromStateK( F: FromState3C ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind3 export function fromStateK( F: FromState2 ): , S, B>(f: (...a: A) => State) => (...a: A) => Kind2 export function fromStateK( F: FromState ): , S, B>(f: (...a: A) => State) => (...a: A) => HKT2 export function fromStateK( F: FromState ): , S, B>(f: (...a: A) => State) => (...a: A) => HKT2 { return (f) => flow(f, F.fromState) } /** * @since 2.11.0 */ export function chainStateK( F: FromState4, M: Chain4 ): (f: (a: A) => State) => (ma: Kind4) => Kind4 export function chainStateK( F: FromState3, M: Chain3 ): (f: (a: A) => State) => (ma: Kind3) => Kind3 export function chainStateK( F: FromState2, M: Chain2 ): (f: (a: A) => State) => (ma: Kind2) => Kind2 export function chainStateK( F: FromState, M: Chain ): (f: (a: A) => State) => (ma: HKT2) => HKT2 export function chainStateK( F: FromState2, M: Chain2 ): (f: (a: A) => State) => (ma: Kind2) => Kind2 { const fromStateKF = fromStateK(F) return (f) => (ma) => M.chain(ma, fromStateKF(f)) } ================================================ FILE: src/FromTask.ts ================================================ /** * Lift a computation from the `Task` monad * * @since 2.10.0 */ import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4, tap } from './Chain' import { FromIO, FromIO1, FromIO2, FromIO2C, FromIO3, FromIO3C, FromIO4 } from './FromIO' import { flow } from './function' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Task } from './Task' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.10.0 */ export interface FromTask extends FromIO { readonly fromTask: (fa: Task) => HKT } /** * @category model * @since 2.10.0 */ export interface FromTask1 extends FromIO1 { readonly fromTask: (fa: Task) => Kind } /** * @category model * @since 2.10.0 */ export interface FromTask2 extends FromIO2 { readonly fromTask: (fa: Task) => Kind2 } /** * @category model * @since 2.10.0 */ export interface FromTask2C extends FromIO2C { readonly fromTask: (fa: Task) => Kind2 } /** * @category model * @since 2.10.0 */ export interface FromTask3 extends FromIO3 { readonly fromTask: (fa: Task) => Kind3 } /** * @category model * @since 2.10.0 */ export interface FromTask3C extends FromIO3C { readonly fromTask: (fa: Task) => Kind3 } /** * @category model * @since 2.10.0 */ export interface FromTask4 extends FromIO4 { readonly fromTask: (fa: Task) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function fromTaskK( F: FromTask4 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind4 export function fromTaskK( F: FromTask3 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind3 export function fromTaskK( F: FromTask3C ): , B>(f: (...a: A) => Task) => (...a: A) => Kind3 export function fromTaskK( F: FromTask2 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind2 export function fromTaskK( F: FromTask2C ): , B>(f: (...a: A) => Task) => (...a: A) => Kind2 export function fromTaskK( F: FromTask1 ): , B>(f: (...a: A) => Task) => (...a: A) => Kind export function fromTaskK( F: FromTask ): , B>(f: (...a: A) => Task) => (...a: A) => HKT export function fromTaskK( F: FromTask ): , B>(f: (...a: A) => Task) => (...a: A) => HKT { return (f) => flow(f, F.fromTask) } /** * @since 2.10.0 */ export function chainTaskK( F: FromTask4, M: Chain4 ): (f: (a: A) => Task) => (first: Kind4) => Kind4 export function chainTaskK( F: FromTask3, M: Chain3 ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export function chainTaskK( F: FromTask3C, M: Chain3C ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export function chainTaskK( F: FromTask2, M: Chain2 ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export function chainTaskK( F: FromTask2C, M: Chain2C ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export function chainTaskK( F: FromTask1, M: Chain1 ): (f: (a: A) => Task) => (first: Kind) => Kind export function chainTaskK( F: FromTask, M: Chain ): (f: (a: A) => Task) => (first: HKT) => HKT export function chainTaskK( F: FromTask, M: Chain ): (f: (a: A) => Task) => (first: HKT) => HKT { return (f) => { const g = flow(f, F.fromTask) return (first) => M.chain(first, g) } } /** * @since 2.10.0 */ export function chainFirstTaskK( F: FromTask4, M: Chain4 ): (f: (a: A) => Task) => (first: Kind4) => Kind4 export function chainFirstTaskK( F: FromTask3, M: Chain3 ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export function chainFirstTaskK( F: FromTask3C, M: Chain3C ): (f: (a: A) => Task) => (first: Kind3) => Kind3 export function chainFirstTaskK( F: FromTask2, M: Chain2 ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export function chainFirstTaskK( F: FromTask2C, M: Chain2C ): (f: (a: A) => Task) => (first: Kind2) => Kind2 export function chainFirstTaskK( F: FromTask1, M: Chain1 ): (f: (a: A) => Task) => (first: Kind) => Kind export function chainFirstTaskK( F: FromTask, M: Chain ): (f: (a: A) => Task) => (first: HKT) => HKT export function chainFirstTaskK( F: FromTask, M: Chain ): (f: (a: A) => Task) => (first: HKT) => HKT { const tapTaskM = tapTask(F, M) return (f) => (first) => tapTaskM(first, f) } /** @internal */ export function tapTask( F: FromTask4, M: Chain4 ): (self: Kind4, f: (a: A) => Task) => Kind4 /** @internal */ export function tapTask( F: FromTask3, M: Chain3 ): (self: Kind3, f: (a: A) => Task) => Kind3 /** @internal */ export function tapTask( F: FromTask3C, M: Chain3C ): (self: Kind3, f: (a: A) => Task) => Kind3 /** @internal */ export function tapTask( F: FromTask2, M: Chain2 ): (self: Kind2, f: (a: A) => Task) => Kind2 /** @internal */ export function tapTask( F: FromTask2C, M: Chain2C ): (self: Kind2, f: (a: A) => Task) => Kind2 /** @internal */ export function tapTask( F: FromTask1, M: Chain1 ): (self: Kind, f: (a: A) => Task) => Kind /** @internal */ export function tapTask(F: FromTask, M: Chain): (self: HKT, f: (a: A) => Task) => HKT /** @internal */ export function tapTask(F: FromTask, M: Chain): (self: HKT, f: (a: A) => Task) => HKT { const tapM = tap(M) return (self, f) => tapM(self, flow(f, F.fromTask)) } ================================================ FILE: src/FromThese.ts ================================================ /** * The `FromThese` type class represents those data types which support errors and warnings. * * @since 2.11.0 */ import { flow } from './function' import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' import { These } from './These' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.11.0 */ export interface FromThese { readonly URI: F readonly fromThese: (e: These) => HKT2 } /** * @category model * @since 2.11.0 */ export interface FromThese2 { readonly URI: F readonly fromThese: (fa: These) => Kind2 } /** * @category model * @since 2.11.0 */ export interface FromThese2C { readonly URI: F readonly _E: E readonly fromThese: (fa: These) => Kind2 } /** * @category model * @since 2.11.0 */ export interface FromThese3 { readonly URI: F readonly fromThese: (fa: These) => Kind3 } /** * @category model * @since 2.11.0 */ export interface FromThese3C { readonly URI: F readonly _E: E readonly fromThese: (fa: These) => Kind3 } /** * @category model * @since 2.11.0 */ export interface FromThese4 { readonly URI: F readonly fromThese: (fa: These) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function fromTheseK( F: FromThese4 ): , E, B>(f: (...a: A) => These) => (...a: A) => Kind4 export function fromTheseK( F: FromThese3 ): , E, B>(f: (...a: A) => These) => (...a: A) => Kind3 export function fromTheseK( F: FromThese3C ): , B>(f: (...a: A) => These) => (...a: A) => Kind3 export function fromTheseK( F: FromThese2 ): , E, B>(f: (...a: A) => These) => (...a: A) => Kind2 export function fromTheseK( F: FromThese2C ): , B>(f: (...a: A) => These) => (...a: A) => Kind2 export function fromTheseK( F: FromThese ): , E, B>(f: (...a: A) => These) => (...a: A) => HKT2 export function fromTheseK( F: FromThese ): , E, B>(f: (...a: A) => These) => (...a: A) => HKT2 { return (f) => flow(f, F.fromThese) } ================================================ FILE: src/Functor.ts ================================================ /** * A `Functor` is a type constructor which supports a mapping operation `map`. * * `map` can be used to turn functions `a -> b` into functions `f a -> f b` whose argument and return types use the type * constructor `f` to represent some computational context. * * Instances must satisfy the following laws: * * 1. Identity: `F.map(fa, a => a) <-> fa` * 2. Composition: `F.map(fa, a => bc(ab(a))) <-> F.map(F.map(fa, ab), bc)` * * @since 2.0.0 */ import { pipe } from './function' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Functor { readonly URI: F readonly map: (fa: HKT, f: (a: A) => B) => HKT } /** * @category model * @since 2.0.0 */ export interface Functor1 { readonly URI: F readonly map: (fa: Kind, f: (a: A) => B) => Kind } /** * @category model * @since 2.0.0 */ export interface Functor2 { readonly URI: F readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Functor2C { readonly URI: F readonly _E: E readonly map: (fa: Kind2, f: (a: A) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Functor3 { readonly URI: F readonly map: (fa: Kind3, f: (a: A) => B) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Functor3C { readonly URI: F readonly _E: E readonly map: (fa: Kind3, f: (a: A) => B) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Functor4 { readonly URI: F readonly map: (fa: Kind4, f: (a: A) => B) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `map` composition. * * @since 2.10.0 */ export function map( F: Functor3, G: Functor1 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor2, G: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor2, G: Functor1 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor1, G: Functor3 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export function map( F: Functor1, G: Functor2 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export function map( F: Functor1, G: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export function map( F: Functor, G: Functor2 ): (f: (a: A) => B) => (fa: HKT>) => HKT> export function map( F: Functor, G: Functor1 ): (f: (a: A) => B) => (fa: HKT>) => HKT> export function map( F: Functor, G: Functor ): (f: (a: A) => B) => (fa: HKT>) => HKT> export function map( F: Functor, G: Functor ): (f: (a: A) => B) => (fa: HKT>) => HKT> { return (f) => (fa) => F.map(fa, (ga) => G.map(ga, f)) } /** * @category mapping * @since 2.10.0 */ export function flap( F: Functor4 ): (a: A) => (fab: Kind4 B>) => Kind4 export function flap( F: Functor3 ): (a: A) => (fab: Kind3 B>) => Kind3 export function flap( F: Functor2 ): (a: A) => (fab: Kind2 B>) => Kind2 export function flap(F: Functor1): (a: A) => (fab: Kind B>) => Kind export function flap(F: Functor): (a: A) => (fab: HKT B>) => HKT export function flap(F: Functor): (a: A) => (fab: HKT B>) => HKT { return (a) => (fab) => F.map(fab, (f) => f(a)) } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function bindTo( F: Functor4 ): (name: N) => (fa: Kind4) => Kind4 export function bindTo( F: Functor3 ): (name: N) => (fa: Kind3) => Kind3 export function bindTo( F: Functor3C ): (name: N) => (fa: Kind3) => Kind3 export function bindTo( F: Functor2 ): (name: N) => (fa: Kind2) => Kind2 export function bindTo( F: Functor2C ): (name: N) => (fa: Kind2) => Kind2 export function bindTo( F: Functor1 ): (name: N) => (fa: Kind) => Kind export function bindTo( F: Functor ): (name: N) => (fa: HKT) => HKT export function bindTo( F: Functor ): (name: N) => (fa: HKT) => HKT { return (name) => (fa) => F.map(fa, (a) => ({ [name]: a } as any)) } /** * @since 2.13.0 */ function let_( F: Functor4 ): ( name: Exclude, f: (a: A) => B ) => ( fa: Kind4 ) => Kind4 function let_( F: Functor3 ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind3) => Kind3 function let_( F: Functor3C ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind3) => Kind3 function let_( F: Functor2 ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind2) => Kind2 function let_( F: Functor2C ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind2) => Kind2 function let_( F: Functor1 ): ( name: Exclude, f: (a: A) => B ) => (fa: Kind) => Kind function let_( F: Functor ): ( name: Exclude, f: (a: A) => B ) => (fa: HKT) => HKT function let_( F: Functor ): ( name: Exclude, f: (a: A) => B ) => (fa: HKT) => HKT { return (name, f) => (fa) => F.map(fa, (a) => Object.assign({}, a, { [name]: f(a) }) as any) } export { /** * @since 2.13.0 */ let_ as let } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorCompositionHKT1 { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorCompositionHKT2 { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorCompositionHKT2C { readonly map: (fa: HKT>, f: (a: A) => B) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition11 { readonly map: (fa: Kind>, f: (a: A) => B) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition12 { readonly map: (fa: Kind>, f: (a: A) => B) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition12C { readonly map: (fa: Kind>, f: (a: A) => B) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition21 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition2C1 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition22 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorComposition22C { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface FunctorComposition23 { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface FunctorComposition23C { readonly map: (fa: Kind2>, f: (a: A) => B) => Kind2> } /** * Use [`map`](#map) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getFunctorComposition( F: Functor2, G: Functor3C ): FunctorComposition23C /** @deprecated */ export function getFunctorComposition( F: Functor2, G: Functor2C ): FunctorComposition22C /** @deprecated */ export function getFunctorComposition( F: Functor2, G: Functor2 ): FunctorComposition22 /** @deprecated */ export function getFunctorComposition( F: Functor2C, G: Functor1 ): FunctorComposition2C1 /** @deprecated */ export function getFunctorComposition( F: Functor2, G: Functor1 ): FunctorComposition21 /** @deprecated */ export function getFunctorComposition( F: Functor1, G: Functor2C ): FunctorComposition12C /** @deprecated */ export function getFunctorComposition( F: Functor1, G: Functor2 ): FunctorComposition12 /** @deprecated */ export function getFunctorComposition( F: Functor1, G: Functor1 ): FunctorComposition11 /** @deprecated */ export function getFunctorComposition(F: Functor, G: Functor): FunctorComposition /** @deprecated */ export function getFunctorComposition(F: Functor, G: Functor): FunctorComposition { const _map = map(F, G) return { map: (fga, f) => pipe(fga, _map(f)) } } /** @internal */ export function as( F: Functor4 ): (self: Kind4, a: A) => Kind4 /** @internal */ export function as(F: Functor3): (self: Kind3, a: _) => Kind3 /** @internal */ export function as(F: Functor2): (self: Kind2, a: A) => Kind2 /** @internal */ export function as(F: Functor1): (self: Kind, a: A) => Kind /** @internal */ export function as(F: Functor): (self: HKT, a: A) => HKT /** @internal */ export function as(F: Functor): (self: HKT, b: A) => HKT { return (self, b) => F.map(self, () => b) } /** @internal */ export function asUnit( F: Functor4 ): (self: Kind4) => Kind4 /** @internal */ export function asUnit(F: Functor3): (self: Kind3) => Kind3 /** @internal */ export function asUnit(F: Functor2): (self: Kind2) => Kind2 /** @internal */ export function asUnit(F: Functor1): <_>(self: Kind) => Kind /** @internal */ export function asUnit(F: Functor): <_>(self: HKT) => HKT /** @internal */ export function asUnit(F: Functor): <_>(self: HKT) => HKT { const asM = as(F) return (self) => asM(self, undefined) } ================================================ FILE: src/FunctorWithIndex.ts ================================================ /** * A `FunctorWithIndex` is a type constructor which supports a mapping operation `mapWithIndex`. * * `mapWithIndex` can be used to turn functions `i -> a -> b` into functions `f a -> f b` whose argument and return types use the type * constructor `f` to represent some computational context. * * Instances must satisfy the following laws: * * 1. Identity: `F.mapWithIndex(fa, (_i, a) => a) <-> fa` * 2. Composition: `F.mapWithIndex(fa, (_i, a) => bc(ab(a))) <-> F.mapWithIndex(F.mapWithIndex(fa, ab), bc)` * * @since 2.0.0 */ import { pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4, FunctorComposition, FunctorComposition2C1, FunctorComposition11, FunctorComposition12, FunctorComposition12C, FunctorComposition21, FunctorComposition22, FunctorComposition22C, getFunctorComposition } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface FunctorWithIndex extends Functor { readonly mapWithIndex: (fa: HKT, f: (i: I, a: A) => B) => HKT } /** * @category model * @since 2.0.0 */ export interface FunctorWithIndex1 extends Functor1 { readonly mapWithIndex: (fa: Kind, f: (i: I, a: A) => B) => Kind } /** * @category model * @since 2.0.0 */ export interface FunctorWithIndex2 extends Functor2 { readonly mapWithIndex: (fa: Kind2, f: (i: I, a: A) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface FunctorWithIndex2C extends Functor2C { readonly mapWithIndex: (fa: Kind2, f: (i: I, a: A) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface FunctorWithIndex3 extends Functor3 { readonly mapWithIndex: (fa: Kind3, f: (i: I, a: A) => B) => Kind3 } /** * @category model * @since 2.2.0 */ export interface FunctorWithIndex3C extends Functor3C { readonly mapWithIndex: (fa: Kind3, f: (i: I, a: A) => B) => Kind3 } /** * @category model * @since 2.0.0 */ export interface FunctorWithIndex4 extends Functor4 { readonly mapWithIndex: (fa: Kind4, f: (i: I, a: A) => B) => Kind4 } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `mapWithIndex` composition. * * @since 2.10.0 */ export function mapWithIndex( F: FunctorWithIndex1, G: FunctorWithIndex1 ): (f: (ij: readonly [I, J], a: A) => B) => (fa: Kind>) => Kind> export function mapWithIndex( F: FunctorWithIndex, G: FunctorWithIndex ): (f: (ij: readonly [I, J], a: A) => B) => (fa: HKT>) => HKT> export function mapWithIndex( F: FunctorWithIndex, G: FunctorWithIndex ): (f: (ij: readonly [I, J], a: A) => B) => (fa: HKT>) => HKT> { return (f) => (fa) => F.mapWithIndex(fa, (i, ga) => G.mapWithIndex(ga, (j, a) => f([i, j], a))) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition extends FunctorComposition { readonly mapWithIndex: (fga: HKT>, f: (i: [FI, GI], a: A) => B) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition11 extends FunctorComposition11 { readonly mapWithIndex: (fa: Kind>, f: (i: [FI, GI], a: A) => B) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition12 extends FunctorComposition12 { readonly mapWithIndex: (fa: Kind>, f: (i: [FI, GI], a: A) => B) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition12C extends FunctorComposition12C { readonly mapWithIndex: (fa: Kind>, f: (i: [FI, GI], a: A) => B) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition21 extends FunctorComposition21 { readonly mapWithIndex: (fa: Kind2>, f: (i: [FI, GI], a: A) => B) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition2C1 extends FunctorComposition2C1 { readonly mapWithIndex: (fa: Kind2>, f: (i: [FI, GI], a: A) => B) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition22 extends FunctorComposition22 { readonly mapWithIndex: ( fa: Kind2>, f: (i: [FI, GI], a: A) => B ) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface FunctorWithIndexComposition22C extends FunctorComposition22C { readonly mapWithIndex: ( fa: Kind2>, f: (i: [FI, GI], a: A) => B ) => Kind2> } /** * Use [`mapWithIndex`](#mapwithindex) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex2, G: FunctorWithIndex2C ): FunctorWithIndexComposition22C /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex2, G: FunctorWithIndex2 ): FunctorWithIndexComposition22 /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex2C, G: FunctorWithIndex1 ): FunctorWithIndexComposition2C1 /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex2, G: FunctorWithIndex1 ): FunctorWithIndexComposition21 /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex1, G: FunctorWithIndex2C ): FunctorWithIndexComposition12C /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex1, G: FunctorWithIndex2 ): FunctorWithIndexComposition12 /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex1, G: FunctorWithIndex1 ): FunctorWithIndexComposition11 /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex, G: FunctorWithIndex ): FunctorWithIndexComposition /** @deprecated */ export function getFunctorWithIndexComposition( F: FunctorWithIndex, G: FunctorWithIndex ): FunctorWithIndexComposition { const map = getFunctorComposition(F, G).map const _mapWithIndex = mapWithIndex(F, G) return { map, mapWithIndex: (fga, f: any) => pipe(fga, _mapWithIndex(f)) } } ================================================ FILE: src/Group.ts ================================================ /** * A `Group` is a `Monoid` with inverses. Instances must satisfy the following law in addition to the monoid laws: * * - Inverse: `concat(inverse(a), a) <-> empty = concat(a, inverse(a))` * * @since 2.0.0 */ import { Monoid } from './Monoid' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Group extends Monoid { readonly inverse: (a: A) => A } ================================================ FILE: src/HKT.ts ================================================ /** * Type defunctionalization (as describe in [Lightweight higher-kinded polymorphism](https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf)) * * @since 2.0.0 */ /** * `* -> *` constructors * @since 2.0.0 */ export interface HKT { readonly _URI: URI readonly _A: A } /** * `* -> * -> *` constructors * @since 2.0.0 */ export interface HKT2 extends HKT { readonly _E: E } /** * `* -> * -> * -> *` constructors * @since 2.0.0 */ export interface HKT3 extends HKT2 { readonly _R: R } /** * `* -> * -> * -> * -> *` constructors * @since 2.0.0 */ export interface HKT4 extends HKT3 { readonly _S: S } // // inj: type-level dictionaries for HKTs: URI -> concrete type // /** * `* -> *` constructors * @since 2.0.0 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export interface URItoKind {} /** * `* -> * -> *` constructors * @since 2.0.0 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export interface URItoKind2 {} /** * `* -> * -> * -> *` constructors * @since 2.0.0 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export interface URItoKind3 {} /** * `* -> * -> * -> * -> *` constructors * @since 2.0.0 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export interface URItoKind4 {} // // unions of URIs // /** * `* -> *` constructors * @since 2.0.0 */ export type URIS = keyof URItoKind /** * `* -> * -> *` constructors * @since 2.0.0 */ export type URIS2 = keyof URItoKind2 /** * `* -> * -> * -> *` constructors * @since 2.0.0 */ export type URIS3 = keyof URItoKind3 /** * `* -> * -> * -> * -> *` constructors * @since 2.0.0 */ export type URIS4 = keyof URItoKind4 // // prj // /** * `* -> *` constructors * @since 2.0.0 */ export type Kind = URI extends URIS ? URItoKind[URI] : any /** * `* -> * -> *` constructors * @since 2.0.0 */ export type Kind2 = URI extends URIS2 ? URItoKind2[URI] : any /** * `* -> * -> * -> *` constructors * @since 2.0.0 */ export type Kind3 = URI extends URIS3 ? URItoKind3[URI] : any /** * `* -> * -> * -> * -> *` constructors * @since 2.0.0 */ export type Kind4 = URI extends URIS4 ? URItoKind4[URI] : any ================================================ FILE: src/HeytingAlgebra.ts ================================================ /** * Heyting algebras are bounded (distributive) lattices that are also equipped with an additional binary operation * `implies` (also written as `→`). Heyting algebras also define a complement operation `not` (sometimes written as * `¬a`) * * However, in Heyting algebras this operation is only a pseudo-complement, since Heyting algebras do not necessarily * provide the law of the excluded middle. This means that there is no guarantee that `a ∨ ¬a = 1`. * * Heyting algebras model intuitionistic logic. For a model of classical logic, see the boolean algebra type class * implemented as `BooleanAlgebra`. * * A `HeytingAlgebra` must satisfy the following laws in addition to `BoundedDistributiveLattice` laws: * * - Implication: * - `a → a <-> 1` * - `a ∧ (a → b) <-> a ∧ b` * - `b ∧ (a → b) <-> b` * - `a → (b ∧ c) <-> (a → b) ∧ (a → c)` * - Complemented * - `¬a <-> a → 0` * * @since 2.0.0 */ import { BoundedDistributiveLattice } from './BoundedDistributiveLattice' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface HeytingAlgebra extends BoundedDistributiveLattice { readonly implies: (x: A, y: A) => A readonly not: (x: A) => A } ================================================ FILE: src/IO.ts ================================================ /** * ```ts * interface IO { * (): A * } * ``` * * `IO` represents a non-deterministic synchronous computation that can cause side effects, yields a value of * type `A` and **never fails**. * * If you want to represent a synchronous computation that may fail, please see `IOEither`. * If you want to represent a synchronous computation that may yield nothing, please see `IOOption`. * * @since 2.0.0 */ import { Applicative1, getApplicativeMonoid } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_, getApplySemigroup } from './Apply' import * as chainable from './Chain' import { ChainRec1 } from './ChainRec' import { FromIO1 } from './FromIO' import { constant, dual, identity } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import * as _ from './internal' import { Monad1 } from './Monad' import { MonadIO1 } from './MonadIO' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Pointed1 } from './Pointed' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface IO { (): A } const _map: Monad1['map'] = (ma, f) => () => f(ma()) const _ap: Monad1['ap'] = (mab, ma) => () => mab()(ma()) const _chainRec: ChainRec1['chainRec'] = (a, f) => () => { let e = f(a)() while (e._tag === 'Left') { e = f(e.left)() } return e.right } /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: IO) => IO = (f) => (fa) => _map(fa, f) /** * @since 2.0.0 */ export const ap: (fa: IO) => (fab: IO<(a: A) => B>) => IO = (fa) => (fab) => _ap(fab, fa) /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => IO = constant /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => IO): (ma: IO) => IO (ma: IO, f: (a: A) => IO): IO } = /*#__PURE__*/ dual( 2, (ma: IO, f: (a: A) => IO): IO => () => f(ma())() ) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: IO>) => IO = /*#__PURE__*/ flatMap(identity) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'IO' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: IO } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Maps the value to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): <_>(self: IO<_>) => IO <_, A>(self: IO<_>, a: A): IO } = dual(2, as_(Functor)) /** * Maps the value to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: <_>(self: IO<_>) => IO = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: IO, f: (a: A) => IO<_>): IO (f: (a: A) => IO<_>): (self: IO) => IO } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * @category zone of death * @since 2.7.0 * @deprecated */ export const fromIO: (fa: IO) => IO = identity /** * @category instances * @since 2.7.0 */ export const MonadIO: MonadIO1 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO } /** * @category instances * @since 2.7.0 */ export const ChainRec: ChainRec1 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRec } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO1 = { URI, fromIO: identity } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: IO<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * @since 2.11.0 */ export const ApT: IO = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => IO) => (as: ReadonlyNonEmptyArray): IO> => () => { const out: NonEmptyArray = [f(0, _.head(as))()] for (let i = 1; i < as.length; i++) { out.push(f(i, as[i])()) } return out } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => IO ): ((as: ReadonlyArray) => IO>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => IO ) => (as: ReadonlyArray) => IO> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = (f: (a: A) => IO): ((as: ReadonlyArray) => IO>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => IO> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => IO) => (ma: IO) => IO = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => IO) => (first: IO) => IO = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `IO.Functor` instead of `IO.io` * (where `IO` is from `import IO from 'fp-ts/IO'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const io: Monad1 & MonadIO1 & ChainRec1 = { URI, map: _map, of, ap: _ap, chain: flatMap, fromIO, chainRec: _chainRec } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup(Apply) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(Applicative) ================================================ FILE: src/IOEither.ts ================================================ /** * `IOEither` represents a synchronous computation that either yields a value of type `A` or fails yielding an * error of type `E`. * * If you want to represent a synchronous computation that never fails, please see `IO`. * If you want to represent a synchronous computation that may yield nothing, please see `IOOption`. * * @since 2.0.0 */ import { Alt2, Alt2C } from './Alt' import { Applicative2, Applicative2C, getApplicativeMonoid } from './Applicative' import { ap as ap_, apFirst as apFirst_, Apply2, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import { Bifunctor2 } from './Bifunctor' import * as chainable from './Chain' import { compact as compact_, Compactable2C, separate as separate_ } from './Compactable' import * as E from './Either' import * as ET from './EitherT' import { filter as filter_, Filterable2C, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable' import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, FromEither2, fromEitherK as fromEitherK_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_, tapEither as tapEither_ } from './FromEither' import { FromIO2, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor2, let as let__ } from './Functor' import * as _ from './internal' import * as I from './IO' import { Monad2, Monad2C } from './Monad' import { MonadIO2, MonadIO2C } from './MonadIO' import { MonadThrow2, MonadThrow2C } from './MonadThrow' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { Pointed2 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- import Either = E.Either import IO = I.IO /** * @category model * @since 2.0.0 */ export interface IOEither extends IO> {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export const left: (l: E) => IOEither = /*#__PURE__*/ ET.left(I.Pointed) /** * @category constructors * @since 2.0.0 */ export const right: (a: A) => IOEither = /*#__PURE__*/ ET.right(I.Pointed) /** * @category constructors * @since 2.0.0 */ export const rightIO: (ma: IO) => IOEither = /*#__PURE__*/ ET.rightF(I.Functor) /** * @category constructors * @since 2.0.0 */ export const leftIO: (me: IO) => IOEither = /*#__PURE__*/ ET.leftF(I.Functor) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.0.0 */ export const fromEither: (fa: Either) => IOEither = I.of /** * @category conversions * @since 2.7.0 */ export const fromIO: (fa: IO) => IOEither = rightIO /** * @category pattern matching * @since 2.10.0 */ export const match: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: IOEither) => IO = /*#__PURE__*/ ET.match(I.Functor) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW: (onLeft: (e: E) => B, onRight: (a: A) => C) => (ma: IOEither) => IO = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`IO`). * * @category pattern matching * @since 2.10.0 */ export const matchE: (onLeft: (e: E) => IO, onRight: (a: A) => IO) => (ma: IOEither) => IO = /*#__PURE__*/ ET.matchE(I.Monad) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.0.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchEW: ( onLeft: (e: E) => IO, onRight: (a: A) => IO ) => (ma: IOEither) => IO = matchE as any /** * Alias of [`matchEW`](#matchew). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchEW /** * @category error handling * @since 2.0.0 */ export const getOrElse: (onLeft: (e: E) => IO) => (ma: IOEither) => IO = /*#__PURE__*/ ET.getOrElse( I.Monad ) /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.6.0 */ export const getOrElseW: (onLeft: (e: E) => IO) => (ma: IOEither) => IO = getOrElse as any /** * Constructs a new `IOEither` from a function that performs a side effect and might throw * * See also [`tryCatchK`](#trycatchk). * * @category interop * @since 2.0.0 */ export const tryCatch = (f: LazyArg, onThrow: (reason: unknown) => E): IOEither => () => E.tryCatch(f, onThrow) /** * Converts a function that may throw to one returning a `IOEither`. * * @category interop * @since 2.10.0 */ export const tryCatchK = , B, E>( f: (...a: A) => B, onThrow: (reason: unknown) => E ): ((...a: A) => IOEither) => (...a) => tryCatch(() => f(...a), onThrow) /** * @category conversions * @since 2.10.0 */ export const toUnion: (fa: IOEither) => IO = /*#__PURE__*/ ET.toUnion(I.Functor) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category error handling * @since 2.0.0 */ export const orElse: (onLeft: (e: E1) => IOEither) => (ma: IOEither) => IOEither = /*#__PURE__*/ ET.orElse(I.Monad) /** * Less strict version of [`orElse`](#orelse). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category error handling * @since 2.10.0 */ export const orElseW: ( onLeft: (e: E1) => IOEither ) => (ma: IOEither) => IOEither = orElse as any /** * Returns an effect that effectfully "peeks" at the failure of this effect. * * @category error handling * @since 2.15.0 */ export const tapError: { (onLeft: (e: E1) => IOEither): (self: IOEither) => IOEither (self: IOEither, onLeft: (e: E1) => IOEither): IOEither } = /*#__PURE__*/ dual(2, ET.tapError(I.Monad)) /** * @category error handling * @since 2.12.0 */ export const orElseFirstIOK: (onLeft: (e: E) => IO) => (ma: IOEither) => IOEither = (onLeft) => tapError(fromIOK(onLeft)) /** * @category error handling * @since 2.11.0 */ export const orLeft: (onLeft: (e: E1) => IO) => (fa: IOEither) => IOEither = /*#__PURE__*/ ET.orLeft(I.Monad) /** * @since 2.0.0 */ export const swap: (ma: IOEither) => IOEither = /*#__PURE__*/ ET.swap(I.Functor) /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _ap: Apply2['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _apSeq: Apply2['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /* istanbul ignore next */ const _alt: Alt2['alt'] = (fa, that) => pipe(fa, alt(that)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: IOEither) => IOEither = /*#__PURE__*/ ET.map(I.Functor) /** * Returns a `IOEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. * * @example * import * as IOEither from 'fp-ts/IOEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * const g = (n: number) => n * 2 * * assert.deepStrictEqual(IOEither.mapBoth(IOEither.right(1), f, g)(), Either.right(2)) * assert.deepStrictEqual(IOEither.mapBoth(IOEither.left('err'), f, g)(), Either.left(new Error('err'))) * * @category error handling * @since 2.16.0 */ export const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: IOEither) => IOEither (self: IOEither, f: (e: E) => G, g: (a: A) => B): IOEither } = /*#__PURE__*/ dual(3, ET.mapBoth(I.Functor)) /** * Alias of `mapBoth`. * * @category legacy * @since 2.0.0 */ export const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: IOEither) => IOEither = mapBoth /** * Returns a `IOEither` with its error channel mapped using the specified function. * * @example * import * as IOEither from 'fp-ts/IOEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * * assert.deepStrictEqual(IOEither.mapError(IOEither.right(1), f)(), Either.right(1)) * assert.deepStrictEqual(IOEither.mapError(IOEither.left('err'), f)(), Either.left(new Error('err'))) * * @category error handling * @since 2.16.0 */ export const mapError: { (f: (e: E) => G): (self: IOEither) => IOEither (self: IOEither, f: (e: E) => G): IOEither } = /*#__PURE__*/ dual(2, ET.mapError(I.Functor)) /** * Alias of `mapError`. * * @category legacy * @since 2.0.0 */ export const mapLeft: (f: (e: E) => G) => (fa: IOEither) => IOEither = mapError /** * @since 2.0.0 */ export const ap: (fa: IOEither) => (fab: IOEither B>) => IOEither = /*#__PURE__*/ ET.ap(I.Apply) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.8.0 */ export const apW: (fa: IOEither) => (fab: IOEither B>) => IOEither = ap as any /** * @category constructors * @since 2.8.5 */ export const of: (a: A) => IOEither = right /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => IOEither): (ma: IOEither) => IOEither (ma: IOEither, f: (a: A) => IOEither): IOEither } = /*#__PURE__*/ dual(2, ET.flatMap(I.Monad)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: (mma: IOEither>) => IOEither = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: IOEither>) => IOEither = flattenW /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * @category error handling * @since 2.0.0 */ export const alt: (that: LazyArg>) => (fa: IOEither) => IOEither = /*#__PURE__*/ ET.alt(I.Monad) /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the error and the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW: (that: LazyArg>) => (fa: IOEither) => IOEither = alt as any /** * @since 2.7.0 */ export const throwError: MonadThrow2['throwError'] = left /** * @category type lambdas * @since 2.0.0 */ export const URI = 'IOEither' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: IOEither } } /** * The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getApplicativeValidation`](./Either.ts.html#getapplicativevalidation). * * @category error handling * @since 2.7.0 */ export function getApplicativeIOValidation(S: Semigroup): Applicative2C { const ap = ap_(I.Apply, E.getApplicativeValidation(S)) return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => pipe(fab, ap(fa)), of } } /** * The default [`Alt`](#alt) instance returns the last error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getAltValidation`](./Either.ts.html#getaltvalidation). * * @category error handling * @since 2.7.0 */ export function getAltIOValidation(S: Semigroup): Alt2C { const alt = ET.altValidation(I.Monad, S) return { URI, _E: undefined as any, map: _map, alt: (fa, that) => pipe(fa, alt(that)) } } /** * @category filtering * @since 2.10.0 */ export const getCompactable = (M: Monoid): Compactable2C => { const C = E.getCompactable(M) return { URI, _E: undefined as any, compact: compact_(I.Functor, C), separate: separate_(I.Functor, C, E.Functor) } } /** * @category filtering * @since 2.1.0 */ export function getFilterable(M: Monoid): Filterable2C { const F = E.getFilterable(M) const C = getCompactable(M) const filter = filter_(I.Functor, F) const filterMap = filterMap_(I.Functor, F) const partition = partition_(I.Functor, F) const partitionMap = partitionMap_(I.Functor, F) return { URI, _E: undefined as any, map: _map, compact: C.compact, separate: C.separate, filter: (fa: IOEither, predicate: Predicate) => pipe(fa, filter(predicate)), filterMap: (fa, f) => pipe(fa, filterMap(f)), partition: (fa: IOEither, predicate: Predicate) => pipe(fa, partition(predicate)), partitionMap: (fa, f) => pipe(fa, partitionMap(f)) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * Maps the `Right` value of this `IOEither` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: IOEither) => IOEither (self: IOEither, a: A): IOEither } = dual(2, as_(Functor)) /** * Maps the `Right` value of this `IOEither` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: IOEither) => IOEither = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: mapBoth, mapLeft: mapError } /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplyPar: Apply2 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(ApplyPar) /** * Less strict version of [`apFirst`](#apfirst). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const apFirstW: (second: IOEither) => (first: IOEither) => IOEither = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(ApplyPar) /** * Less strict version of [`apSecond`](#apsecond). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const apSecondW: (second: IOEither) => (first: IOEither) => IOEither = apSecond as any /** * Runs computations in parallel. * * @category instances * @since 2.8.4 */ export const ApplicativePar: Applicative2 = { URI, map: _map, ap: _ap, of } /** * Runs computations sequentially. * * @category instances * @since 2.8.4 */ export const ApplicativeSeq: Applicative2 = { URI, map: _map, ap: _apSeq, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad2 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither2 = { URI, fromEither } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO2 = { URI, fromIO } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: IOEither, f: (a: A) => IOEither): IOEither (f: (a: A) => IOEither): (self: IOEither) => IOEither } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as IOE from 'fp-ts/IOEither' * import * as E from 'fp-ts/Either' * * const compute = (value: string) => pipe( * IOE.of(value), * IOE.tapEither(() => value.length > 0 ? E.right('ok') : E.left('error')), * ) * * assert.deepStrictEqual(compute('')(), E.left('error')) * assert.deepStrictEqual(compute('fp-ts')(), E.right('fp-ts')) * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => Either): IOEither } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as IOE from 'fp-ts/IOEither' * import * as E from 'fp-ts/Either' * import * as Console from 'fp-ts/Console' * * const sayHello = (value: string) => Console.log(`Hello, ${value}`) * * // Will produce `Hello, fp-ts` to the stdout * const effectA = IOE.tapIO(IOE.of('fp-ts'), sayHello) * * // No output to the stdout * const effectB = pipe(IOE.left('error'), IOE.tapIO(sayHello)) * * assert.deepStrictEqual(effectA(), E.right('fp-ts')) * assert.deepStrictEqual(effectB(), E.left('error')) * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => IO<_>): IOEither } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * @category instances * @since 2.7.0 */ export const Alt: Alt2 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.7.0 */ export const MonadIO: MonadIO2 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO: fromIO } /** * @category instances * @since 2.7.0 */ export const MonadThrow: MonadThrow2 = { URI, map: _map, ap: _ap, of, chain: flatMap, throwError } /** * @category lifting * @since 2.10.0 */ export const fromIOK: , B>( f: (...a: A) => I.IO ) => (...a: A) => IOEither = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: (f: (a: A) => I.IO) => (first: IOEither) => IOEither = tapIO /** * @category conversions * @since 2.0.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => IOEither = /*#__PURE__*/ fromOption_(FromEither) /** * Use `liftOption`. * * @category legacy * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => IOEither = /*#__PURE__*/ fromOptionK_(FromEither) /** * Use `flatMapOption`. * * @category legacy * @since 2.10.0 */ export const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: IOEither) => IOEither = /*#__PURE__*/ chainOptionK_( FromEither, Chain ) /** * Use `flatMapOption`. * * @category legacy * @since 2.13.2 */ export const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: IOEither) => IOEither = chainOptionK as any /** @internal */ interface IOEitherTypeLambda extends _.TypeLambda { readonly type: IOEither } /** @internal */ const _FromEither: _.FromEither = { fromEither: FromEither.fromEither } /** @internal */ const _FromIO: _.FromIO = { fromIO } /** * @category lifting * @since 2.15.0 */ export const liftNullable: , B, E>( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => IOEither> = /*#__PURE__*/ _.liftNullable(_FromEither) /** * @category lifting * @since 2.15.0 */ export const liftOption: , B, E>( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => IOEither = /*#__PURE__*/ _.liftOption(_FromEither) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** * @category sequencing * @since 2.15.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: IOEither ) => IOEither> (self: IOEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): IOEither< E1 | E2, NonNullable > } = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => Option, onNone: (a: A) => E2): IOEither } = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapEither: { (f: (a: A) => E.Either): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => E.Either): IOEither } = /*#__PURE__*/ _.flatMapEither(_FromEither, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: IOEither) => IOEither (self: IOEither, f: (a: A) => IO): IOEither } = /*#__PURE__*/ _.flatMapIO(_FromIO, _FlatMap) /** * Alias of `flatMapIO`. * @category legacy * @since 2.10.0 */ export const chainIOK: (f: (a: A) => I.IO) => (first: IOEither) => IOEither = flatMapIO /** * Alias of `flatMapEither`. * * @category legacy * @since 2.4.0 */ export const chainEitherK: (f: (a: A) => E.Either) => (ma: IOEither) => IOEither = flatMapEither /** * Alias of `flatMapEither`. * * @category legacy * @since 2.6.1 */ export const chainEitherKW: ( f: (a: A) => Either ) => (ma: IOEither) => IOEither = flatMapEither /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: (f: (a: A) => E.Either) => (ma: IOEither) => IOEither = tapEither /** * Alias of `tapEither`. * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: IOEither) => IOEither = tapEither /** * @category lifting * @since 2.0.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (b: B) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => IOEither } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category filtering * @since 2.0.0 */ export const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: IOEither) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (mb: IOEither) => IOEither (predicate: Predicate, onFalse: (a: A) => E): (ma: IOEither) => IOEither } = /*#__PURE__*/ filterOrElse_(FromEither, Chain) /** * Less strict version of [`filterOrElse`](#filterorelse). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category filtering * @since 2.9.0 */ export const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: IOEither ) => IOEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: IOEither ) => IOEither (predicate: Predicate, onFalse: (a: A) => E2): (ma: IOEither) => IOEither } = filterOrElse /** * @category lifting * @since 2.4.0 */ export const fromEitherK: , B>( f: (...a: A) => E.Either ) => (...a: A) => IOEither = /*#__PURE__*/ fromEitherK_(FromEither) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of * whether the body action throws (\*) or returns. * * (\*) i.e. returns a `Left` * * @since 2.0.0 */ export const bracket = ( acquire: IOEither, use: (a: A) => IOEither, release: (a: A, e: Either) => IOEither ): IOEither => bracketW(acquire, use, release) /** * Less strict version of [`bracket`](#bracket). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const bracketW: ( acquire: IOEither, use: (a: A) => IOEither, release: (a: A, e: E.Either) => IOEither ) => IOEither = (acquire, use, release) => flatMap(acquire, (a) => I.flatMap(use(a), (e) => flatMap(release(a, e), () => I.of(e)))) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: IOEither = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => IOEither ) => (fa: IOEither) => IOEither = bind as any /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(ApplyPar) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: IOEither ) => (fa: IOEither) => IOEither = apS as any /** * @since 2.11.0 */ export const ApT: IOEither = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: ReadonlyNonEmptyArray) => IOEither> = (f) => flow(I.traverseReadonlyNonEmptyArrayWithIndex(f), I.map(E.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => IOEither ): ((as: ReadonlyArray) => IOEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = (f: (index: number, a: A) => IOEither) => (as: ReadonlyNonEmptyArray): IOEither> => () => { const e = f(0, _.head(as))() if (_.isLeft(e)) { return e } const out: NonEmptyArray = [e.right] for (let i = 1; i < as.length; i++) { const e = f(i, as[i])() if (_.isLeft(e)) { return e } out.push(e.right) } return _.right(out) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = ( f: (index: number, a: A) => IOEither ): ((as: ReadonlyArray) => IOEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: ReadonlyArray) => IOEither> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => IOEither ): ((as: ReadonlyArray) => IOEither>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => IOEither> = /*#__PURE__*/ traverseArray(identity) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => IOEither ) => (as: ReadonlyArray) => IOEither> = traverseReadonlyArrayWithIndexSeq /** * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArray = ( f: (a: A) => IOEither ): ((as: ReadonlyArray) => IOEither>) => traverseReadonlyArrayWithIndexSeq((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const sequenceSeqArray: (arr: ReadonlyArray>) => IOEither> = /*#__PURE__*/ traverseSeqArray(identity) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`ApplicativePar`](#applicativepar) instead * * @category zone of death * @since 2.7.0 * @deprecated */ export const Applicative: Applicative2 = ApplicativePar // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => IOEither) => (ma: IOEither) => IOEither = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: (f: (a: A) => IOEither) => (ma: IOEither) => IOEither = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => IOEither) => (ma: IOEither) => IOEither = tap /** * Alias of `tap`. * * @category legacy * @since 2.8.0 */ export const chainFirstW: ( f: (a: A) => IOEither ) => (ma: IOEither) => IOEither = tap /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirst: (onLeft: (e: E) => IOEither) => (ma: IOEither) => IOEither = tapError /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirstW: ( onLeft: (e: E1) => IOEither ) => (ma: IOEither) => IOEither = tapError // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `IOE.Functor` instead of `IOE.ioEither` * (where `IOE` is from `import IOE from 'fp-ts/IOEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const ioEither: Monad2 & Bifunctor2 & Alt2 & MonadIO2 & MonadThrow2 = { URI, bimap: mapBoth, mapLeft: mapError, map: _map, of, ap: _ap, chain: flatMap, alt: _alt, fromIO, throwError } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplySemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(ApplyPar) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplyMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(ApplicativePar) /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup = (S: Semigroup): Semigroup> => getApplySemigroup_(I.Apply)(E.getSemigroup(S)) /** * Use [`getApplicativeIOValidation`](#getapplicativeiovalidation) and [`getAltIOValidation`](#getaltiovalidation). * * @category zone of death * @since 2.0.0 * @deprecated */ export function getIOValidation( SE: Semigroup ): Monad2C & Bifunctor2 & Alt2C & MonadIO2C & MonadThrow2C { const applicativeIOValidation = getApplicativeIOValidation(SE) const altIOValidation = getAltIOValidation(SE) return { URI, _E: undefined as any, map: _map, ap: applicativeIOValidation.ap, of, chain: flatMap, bimap: mapBoth, mapLeft: mapError, alt: altIOValidation.alt, fromIO, throwError } } ================================================ FILE: src/IOOption.ts ================================================ /** * `IOOption` represents a synchronous computation that either yields a value of type `A` or nothing. * * If you want to represent a synchronous computation that never fails, please see `IO`. * If you want to represent a synchronous computation that may fail, please see `IOEither`. * * @since 2.12.0 */ import { Alt1 } from './Alt' import { Alternative1 } from './Alternative' import { Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import * as chainable from './Chain' import { compact as compact_, Compactable1, separate as separate_ } from './Compactable' import { Either } from './Either' import { filter as filter_, Filterable1, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable' import { FromEither1, fromEitherK as fromEitherK_, tapEither as tapEither_ } from './FromEither' import { FromIO1, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import * as _ from './internal' import * as I from './IO' import { IOEither } from './IOEither' import { Monad1 } from './Monad' import { MonadIO1 } from './MonadIO' import * as O from './Option' import * as OT from './OptionT' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Separated } from './Separated' import { guard as guard_, Zero1 } from './Zero' import IO = I.IO import Option = O.Option // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.12.0 */ export interface IOOption extends IO> {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.12.0 */ export const some: (a: A) => IOOption = /*#__PURE__*/ OT.some(I.Pointed) /** * @category lifting * @since 2.12.0 */ export const fromPredicate: { (refinement: Refinement): (a: A) => IOOption (predicate: Predicate): (b: B) => IOOption (predicate: Predicate): (a: A) => IOOption } = /*#__PURE__*/ OT.fromPredicate(I.Pointed) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.12.0 */ export const fromOption: (fa: Option) => IOOption = I.of /** * @category conversions * @since 2.12.0 */ export const fromEither: (fa: Either) => IOOption = /*#__PURE__*/ OT.fromEither(I.Pointed) /** * @category conversions * @since 2.12.0 */ export const fromIO: (fa: IO) => IOOption = /*#__PURE__*/ OT.fromF(I.Functor) /** * @category conversions * @since 2.12.0 */ export const fromIOEither: (fa: IOEither) => IOOption = /*#__PURE__*/ I.map(O.fromEither) /** * @category pattern matching * @since 2.12.0 */ export const match: (onNone: () => B, onSome: (a: A) => B) => (ma: IOOption) => IO = /*#__PURE__*/ OT.match( I.Functor ) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.12.0 */ export const matchW: (onNone: () => B, onSome: (a: A) => C) => (ma: IOOption) => IO = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`IO`). * * @category pattern matching * @since 2.12.0 */ export const matchE: (onNone: () => IO, onSome: (a: A) => IO) => (ma: IOOption) => IO = /*#__PURE__*/ OT.matchE(I.Chain) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.12.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.12.0 */ export const matchEW: (onNone: () => IO, onSome: (a: A) => IO) => (ma: IOOption) => IO = matchE as any /** * @category error handling * @since 2.12.0 */ export const getOrElse: (onNone: LazyArg>) => (fa: IOOption) => IO = /*#__PURE__*/ OT.getOrElse(I.Monad) /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.12.0 */ export const getOrElseW: (onNone: LazyArg>) => (ma: IOOption) => IO = getOrElse as any /** * @category conversions * @since 2.12.0 */ export const toUndefined: (ma: IOOption) => IO = I.map(O.toUndefined) /** * @category conversions * @since 2.12.0 */ export const toNullable: (ma: IOOption) => IO = I.map(O.toNullable) /** * @category conversions * @since 2.12.0 */ export const fromNullable: (a: A) => IOOption> = /*#__PURE__*/ OT.fromNullable(I.Pointed) /** * @category lifting * @since 2.12.0 */ export const fromNullableK: , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => IOOption> = /*#__PURE__*/ OT.fromNullableK(I.Pointed) /** * Alias of `flatMapNullable`. * * @category legacy * @since 2.12.0 */ export const chainNullableK: ( f: (a: A) => B | null | undefined ) => (ma: IOOption) => IOOption> = /*#__PURE__*/ OT.chainNullableK(I.Monad) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category lifting * @since 2.12.0 */ export const fromOptionK: , B>(f: (...a: A) => Option) => (...a: A) => IOOption = /*#__PURE__*/ OT.fromOptionK(I.Pointed) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.12.0 */ export const map: (f: (a: A) => B) => (fa: IOOption) => IOOption = /*#__PURE__*/ OT.map(I.Functor) /** * @since 2.12.0 */ export const ap: (fa: IOOption) => (fab: IOOption<(a: A) => B>) => IOOption = /*#__PURE__*/ OT.ap(I.Apply) /** * @category constructors * @since 2.12.0 */ export const of: (a: A) => IOOption = some /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => IOOption): (ma: IOOption) => IOOption (ma: IOOption, f: (a: A) => IOOption): IOOption } = /*#__PURE__*/ dual(2, OT.flatMap(I.Monad)) /** * @category sequencing * @since 2.12.0 */ export const flatten: (mma: IOOption>) => IOOption = /*#__PURE__*/ flatMap(identity) /** * @category error handling * @since 2.12.0 */ export const alt: (second: LazyArg>) => (first: IOOption) => IOOption = /*#__PURE__*/ OT.alt( I.Monad ) /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category error handling * @since 2.12.0 */ export const altW: (second: LazyArg>) => (first: IOOption) => IOOption = alt as any /** * @since 2.12.0 */ export const zero: () => IOOption = /*#__PURE__*/ OT.zero(I.Pointed) /** * @category constructors * @since 2.12.0 */ export const none: IOOption = /*#__PURE__*/ zero() /** * @category filtering * @since 2.12.0 */ export const compact: Compactable1['compact'] = /*#__PURE__*/ compact_(I.Functor, O.Compactable) /** * @category filtering * @since 2.12.0 */ export const separate: Compactable1['separate'] = /*#__PURE__*/ separate_(I.Functor, O.Compactable, O.Functor) /** * @category filtering * @since 2.12.0 */ export const filter: { (refinement: Refinement): (fb: IOOption) => IOOption (predicate: Predicate): (fb: IOOption) => IOOption (predicate: Predicate): (fa: IOOption) => IOOption } = /*#__PURE__*/ filter_(I.Functor, O.Filterable) /** * @category filtering * @since 2.12.0 */ export const filterMap: (f: (a: A) => Option) => (fga: IOOption) => IOOption = /*#__PURE__*/ filterMap_( I.Functor, O.Filterable ) /** * @category filtering * @since 2.12.0 */ export const partition: { (refinement: Refinement): (fb: IOOption) => Separated, IOOption> (predicate: Predicate): (fb: IOOption) => Separated, IOOption> (predicate: Predicate): (fa: IOOption) => Separated, IOOption> } = /*#__PURE__*/ partition_(I.Functor, O.Filterable) /** * @category filtering * @since 2.12.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: IOOption) => Separated, IOOption> = /*#__PURE__*/ partitionMap_(I.Functor, O.Filterable) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- const _map: Functor1['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _ap: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) /* istanbul ignore next */ const _filter: Filterable1['filter'] = (fa: IOOption, predicate: Predicate) => pipe(fa, filter(predicate)) /* istanbul ignore next */ const _filterMap: Filterable1['filterMap'] = (fa, f) => pipe(fa, filterMap(f)) /* istanbul ignore next */ const _partition: Filterable1['partition'] = (fa: IOOption, predicate: Predicate) => pipe(fa, partition(predicate)) /* istanbul ignore next */ const _partitionMap: Filterable1['partitionMap'] = (fa, f) => pipe(fa, partitionMap(f)) /** * @category type lambdas * @since 2.12.0 */ export const URI = 'IOOption' /** * @category type lambdas * @since 2.12.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: IOOption } } /** * @category instances * @since 2.12.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Maps the `Some` value of this `IOOption` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): <_>(self: IOOption<_>) => IOOption <_, A>(self: IOOption<_>, a: A): IOOption } = dual(2, as_(Functor)) /** * Maps the `Some` value of this `IOOption` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: <_>(self: IOOption<_>) => IOOption = asUnit_(Functor) /** * @category mapping * @since 2.12.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.12.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.12.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.12.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.12.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.12.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.12.0 */ export const Chain: chainable.Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.12.0 */ export const FromEither: FromEither1 = { URI, fromEither } /** * @category instances * @since 2.12.0 */ export const FromIO: FromIO1 = { URI, fromIO } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: IOOption, f: (a: A) => IOOption<_>): IOOption (f: (a: A) => IOOption<_>): (self: IOOption) => IOOption } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as IOO from 'fp-ts/IOOption' * import * as O from 'fp-ts/Option' * import * as E from 'fp-ts/Either' * * const compute = (value: number) => pipe( * IOO.of(value), * IOO.tapEither((value) => value > 0 ? E.right('ok') : E.left('error')), * ) * * assert.deepStrictEqual(compute(1)(), O.of(1)) * assert.deepStrictEqual(compute(-1)(), O.none) * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => Either): IOOption } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as IOO from 'fp-ts/IOOption' * import * as O from 'fp-ts/Option' * import * as Console from 'fp-ts/Console' * * // Will produce `Hello, fp-ts` to the stdout * const effectA = pipe( * IOO.of('fp-ts'), * IOO.tapIO((value) => Console.log(`Hello, ${value}`)), * ) * * // No output to the stdout * const effectB = pipe( * IOO.none as IOO.IOOption, * IOO.tapIO((value) => Console.log(`Hello, ${value}`)), * ) * * async function test() { * assert.deepStrictEqual(effectA(), O.of('fp-ts')) * assert.deepStrictEqual(effectB(), O.none) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => IO<_>): IOOption } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * @category instances * @since 2.12.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.12.0 */ export const Zero: Zero1 = { URI, zero } /** * @category do notation * @since 2.12.0 */ export const guard = /*#__PURE__*/ guard_(Zero, Pointed) /** * @category instances * @since 2.12.0 */ export const Alternative: Alternative1 = { URI, map: _map, ap: _ap, of, alt: _alt, zero } /** * @category instances * @since 2.12.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.12.0 */ export const MonadIO: MonadIO1 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO } /** * @category instances * @since 2.12.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category instances * @since 2.12.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** @internal */ interface IOOptionTypeLambda extends _.TypeLambda { readonly type: IOOption } /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** @internal */ const _FromIO: _.FromIO = { fromIO: FromIO.fromIO } /** @internal */ const _FromEither: _.FromEither = { fromEither } /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => IO): IOOption } = _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapOption: { (f: (a: A) => Option): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => Option): IOOption } = /*#__PURE__*/ dual( 2, (self: IOOption, f: (a: A) => Option): IOOption => flatMap(self, fromOptionK(f)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapEither: { (f: (a: A) => Either<_, B>): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => Either<_, B>): IOOption } = /*#__PURE__*/ _.flatMapEither(_FromEither, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined): (self: IOOption) => IOOption (self: IOOption, f: (a: A) => B | null | undefined): IOOption } = /*#__PURE__*/ dual( 2, (self: IOOption, f: (a: A) => B | null | undefined): IOOption => flatMap(self, fromNullableK(f)) ) /** * @category lifting * @since 2.12.0 */ export const fromIOK: , B>(f: (...a: A) => I.IO) => (...a: A) => IOOption = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.12.0 */ export const chainIOK: (f: (a: A) => I.IO) => (first: IOOption) => IOOption = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.12.0 */ export const chainFirstIOK: (f: (a: A) => I.IO) => (first: IOOption) => IOOption = tapIO /** * @category lifting * @since 2.12.0 */ export const fromEitherK: , B>( f: (...a: A) => Either ) => (...a: A) => IOOption = /*#__PURE__*/ fromEitherK_(FromEither) /** * Alias of `flatMapEither`. * * @category legacy * @since 2.12.0 */ export const chainEitherK: (f: (a: A) => Either) => (ma: IOOption) => IOOption = flatMapEither /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: (f: (a: A) => Either) => (ma: IOOption) => IOOption = tapEither /** * Alias of `flatMapOption`. * * @category legacy * @since 2.12.0 */ export const chainOptionK: (f: (a: A) => Option) => (ma: IOOption) => IOOption = flatMapOption // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.12.0 */ export const Do: IOOption<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.12.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.12.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * @category do notation * @since 2.12.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * @since 2.12.0 */ export const ApT: IOOption = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.12.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => IOOption ): ((as: ReadonlyNonEmptyArray) => IOOption>) => flow(I.traverseReadonlyNonEmptyArrayWithIndex(f), I.map(O.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.12.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => IOOption ): ((as: ReadonlyArray) => IOOption>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.12.0 */ export const chain: (f: (a: A) => IOOption) => (ma: IOOption) => IOOption = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.12.0 */ export const chainFirst: (f: (a: A) => IOOption) => (first: IOOption) => IOOption = tap ================================================ FILE: src/IORef.ts ================================================ /** * Mutable references in the `IO` monad * * @since 2.0.0 */ import { IO } from './IO' /** * @example * import { flatMap } from 'fp-ts/IO' * import { newIORef } from 'fp-ts/IORef' * * assert.strictEqual(flatMap(newIORef(1), ref => flatMap(ref.write(2), () => ref.read))(), 2) * * @category model * @since 2.0.0 */ export class IORef { /** * @since 2.0.0 */ readonly read: IO constructor(private value: A) { this.read = () => this.value this.write = this.write.bind(this) this.modify = this.modify.bind(this) } /** * @since 2.0.0 */ write(a: A): IO { return () => { this.value = a } } /** * @since 2.0.0 */ modify(f: (a: A) => A): IO { return () => { this.value = f(this.value) } } } /** * @category constructors * @since 2.0.0 */ export function newIORef(a: A): IO> { return () => new IORef(a) } ================================================ FILE: src/Identity.ts ================================================ /** * @since 2.0.0 */ import { Alt1 } from './Alt' import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import { bind as bind_, Chain1, tap as tap_ } from './Chain' import { ChainRec1, tailRec } from './ChainRec' import { Comonad1 } from './Comonad' import { Eq } from './Eq' import { Extend1 } from './Extend' import { Foldable1 } from './Foldable' import { dual, identity as id, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { HKT } from './HKT' import * as _ from './internal' import { Monad1 } from './Monad' import { Monoid } from './Monoid' import { Pointed1 } from './Pointed' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export type Identity = A const _map: Monad1['map'] = (fa, f) => pipe(fa, map(f)) const _ap: Monad1['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _reduce: Foldable1['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable1['foldMap'] = (M) => (fa, f) => pipe(fa, foldMap(M)(f)) /* istanbul ignore next */ const _reduceRight: Foldable1['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) /* istanbul ignore next */ const _extend: Extend1['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _traverse = ( F: ApplicativeHKT ): ((ta: Identity, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } const _chainRec: ChainRec1['chainRec'] = tailRec /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Identity) => Identity = (f) => (fa) => f(fa) /** * @since 2.0.0 */ export const ap: (fa: Identity) => (fab: Identity<(a: A) => B>) => Identity = (fa) => (fab) => fab(fa) /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => Identity = id /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => Identity): (ma: Identity) => Identity (ma: Identity, f: (a: A) => Identity): Identity } = /*#__PURE__*/ dual(2, (ma: Identity, f: (a: A) => Identity): Identity => f(ma)) /** * @since 2.0.0 */ export const extend: (f: (wa: Identity) => B) => (wa: Identity) => Identity = (f) => (wa) => f(wa) /** * @category Extract * @since 2.6.2 */ export const extract: (wa: Identity) => A = id /** * @since 2.0.0 */ export const duplicate: (ma: Identity) => Identity> = /*#__PURE__*/ extend(id) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: Identity>) => Identity = /*#__PURE__*/ flatMap(id) /** * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Identity) => B = (b, f) => (fa) => f(b, fa) /** * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Identity) => M = () => (f) => (fa) => f(fa) /** * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Identity) => B = (b, f) => (fa) => f(fa, b) /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = (F: ApplicativeHKT): ((f: (a: A) => HKT) => (ta: Identity) => HKT>) => (f) => (ta) => F.map(f(ta), id) /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = (F: ApplicativeHKT) => (ta: Identity>): HKT> => { return F.map(ta, id) } /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW: (that: () => Identity) => (fa: Identity) => Identity = () => id /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * @category error handling * @since 2.0.0 */ export const alt: (that: () => Identity) => (fa: Identity) => Identity = altW /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Identity' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Identity } } /** * @category instances * @since 2.0.0 */ export const getShow: (S: Show) => Show> = id /** * @category instances * @since 2.0.0 */ export const getEq: (E: Eq) => Eq> = id /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.7 */ export const tap: { (self: Identity, f: (a: A) => Identity<_>): Identity (f: (a: A) => Identity<_>): (self: Identity) => Identity } = /*#__PURE__*/ dual(2, tap_(Chain)) /** * Alias of `tap` * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => B) => (first: A) => A = tap /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.7.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad1 = { URI, map: _map, extend: _extend, extract } /** * @category instances * @since 2.7.0 */ export const ChainRec: ChainRec1 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRec } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: Identity<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ bind_(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Identity) => (ma: Identity) => Identity = flatMap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `I.Functor` instead of `I.identity` * (where `I` is from `import I from 'fp-ts/Identity'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const identity: Monad1 & Foldable1 & Traversable1 & Alt1 & Comonad1 & ChainRec1 = { URI, map: _map, ap: _ap, of, chain: flatMap, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, alt: _alt, extract, extend: _extend, chainRec: _chainRec } ================================================ FILE: src/Invariant.ts ================================================ /** * @since 2.0.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Invariant { readonly URI: F readonly imap: (fa: HKT, f: (a: A) => B, g: (b: B) => A) => HKT } /** * @category model * @since 2.0.0 */ export interface Invariant1 { readonly URI: F readonly imap: (fa: Kind, f: (a: A) => B, g: (b: B) => A) => Kind } /** * @category model * @since 2.0.0 */ export interface Invariant2 { readonly URI: F readonly imap: (fa: Kind2, f: (a: A) => B, g: (b: B) => A) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Invariant2C { readonly URI: F readonly _E: E readonly imap: (fa: Kind2, f: (a: A) => B, g: (b: B) => A) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Invariant3 { readonly URI: F readonly imap: (fa: Kind3, f: (a: A) => B, g: (b: B) => A) => Kind3 } /** * @category model * @since 2.4.2 */ export interface Invariant3C { readonly URI: F readonly _E: E readonly imap: (fa: Kind3, f: (a: A) => B, g: (b: B) => A) => Kind3 } /** * @category model * @since 2.4.2 */ export interface Invariant4 { readonly URI: F readonly imap: (fa: Kind4, f: (a: A) => B, g: (b: B) => A) => Kind4 } ================================================ FILE: src/JoinSemilattice.ts ================================================ /** * A join-semilattice (or upper semilattice) is a semilattice whose operation is called `join`, and which can be thought * of as a least upper bound. * * A `JoinSemilattice` must satisfy the following laws: * * - Associativity: `a ∨ (b ∨ c) <-> (a ∨ b) ∨ c` * - Commutativity: `a ∨ b <-> b ∨ a` * - Idempotency: `a ∨ a <-> a` * * @since 2.0.0 */ // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface JoinSemilattice { readonly join: (x: A, y: A) => A } ================================================ FILE: src/Json.ts ================================================ /** * @since 2.10.0 */ import { Either, tryCatch } from './Either' import { identity } from './function' /** * @since 2.10.0 */ export type Json = boolean | number | string | null | JsonArray | JsonRecord /** * @since 2.10.0 */ export interface JsonRecord { readonly [key: string]: Json } /** * @since 2.10.0 */ export interface JsonArray extends ReadonlyArray {} /** * Converts a JavaScript Object Notation (JSON) string into a `Json` type. * * @example * import * as J from 'fp-ts/Json' * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('{"a":1}', J.parse), E.right({ a: 1 })) * assert.deepStrictEqual(pipe('{"a":}', J.parse), E.left(new SyntaxError(`Unexpected token '}', "{"a":}" is not valid JSON`))) * * @since 2.10.0 */ export const parse = (s: string): Either => tryCatch(() => JSON.parse(s), identity) /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * * @example * import * as E from 'fp-ts/Either' * import * as J from 'fp-ts/Json' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(J.stringify({ a: 1 }), E.right('{"a":1}')) * const circular: any = { ref: null } * circular.ref = circular * assert.deepStrictEqual( * pipe( * J.stringify(circular), * E.mapLeft(e => e instanceof Error && e.message.includes('Converting circular structure to JSON')) * ), * E.left(true) * ) * * @since 2.10.0 */ export const stringify = (a: A): Either => tryCatch(() => { const s = JSON.stringify(a) if (typeof s !== 'string') { throw new Error('Converting unsupported structure to JSON') } return s }, identity) ================================================ FILE: src/Lattice.ts ================================================ /** * A `Lattice` must satisfy the following in addition to `JoinSemilattice` and `MeetSemilattice` laws: * * - Absorbtion law for meet: `a ∧ (a ∨ b) <-> a` * - Absorbtion law for join: `a ∨ (a ∧ b) <-> a` * * @since 2.0.0 */ import { JoinSemilattice } from './JoinSemilattice' import { MeetSemilattice } from './MeetSemilattice' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Lattice extends JoinSemilattice, MeetSemilattice {} ================================================ FILE: src/Magma.ts ================================================ /** * A `Magma` is a pair `(A, concat)` in which `A` is a non-empty set and `concat` is a binary operation on `A` * * See [Semigroup](https://gcanti.github.io/fp-ts/modules/Semigroup.ts.html) for some instances. * * @since 2.0.0 */ import { Endomorphism } from './Endomorphism' import { Predicate } from './Predicate' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Magma { readonly concat: (x: A, y: A) => A } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * The dual of a `Magma`, obtained by swapping the arguments of `concat`. * * @example * import { reverse, concatAll } from 'fp-ts/Magma' * import * as N from 'fp-ts/number' * * const subAll = concatAll(reverse(N.MagmaSub))(0) * * assert.deepStrictEqual(subAll([1, 2, 3]), 2) * * @since 2.11.0 */ export const reverse = (M: Magma): Magma => ({ concat: (first, second) => M.concat(second, first) }) /** * @since 2.11.0 */ export const filterFirst = (predicate: Predicate) => (M: Magma): Magma => ({ concat: (first, second) => (predicate(first) ? M.concat(first, second) : second) }) /** * @since 2.11.0 */ export const filterSecond = (predicate: Predicate) => (M: Magma): Magma => ({ concat: (first, second) => (predicate(second) ? M.concat(first, second) : first) }) /** * @since 2.11.0 */ export const endo = (f: Endomorphism) => (M: Magma): Magma => ({ concat: (first, second) => M.concat(f(first), f(second)) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Given a sequence of `as`, concat them and return the total. * * If `as` is empty, return the provided `startWith` value. * * @example * import { concatAll } from 'fp-ts/Magma' * import * as N from 'fp-ts/number' * * const subAll = concatAll(N.MagmaSub)(0) * * assert.deepStrictEqual(subAll([1, 2, 3]), -6) * * @since 2.11.0 */ export const concatAll = (M: Magma) => (startWith: A) => (as: ReadonlyArray): A => as.reduce((a, acc) => M.concat(a, acc), startWith) ================================================ FILE: src/Map.ts ================================================ /** * @since 2.0.0 */ import { Applicative } from './Applicative' import { Compactable2 } from './Compactable' import { Either } from './Either' import { Eq } from './Eq' import { Filterable2 } from './Filterable' import { FilterableWithIndex2C } from './FilterableWithIndex' import { Foldable, Foldable1, Foldable2, Foldable2C, Foldable3 } from './Foldable' import { FoldableWithIndex2C } from './FoldableWithIndex' import { pipe } from './function' import { flap as flap_, Functor2 } from './Functor' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import * as _ from './internal' import { Magma } from './Magma' import { Monoid } from './Monoid' import * as O from './Option' import { Ord } from './Ord' import { Predicate } from './Predicate' import * as RM from './ReadonlyMap' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import { TraversableWithIndex2C } from './TraversableWithIndex' import { Unfoldable, Unfoldable1 } from './Unfoldable' import { wiltDefault, Witherable2C, witherDefault } from './Witherable' import Option = O.Option /** * @category instances * @since 2.0.0 */ export const getShow: (SK: Show, SA: Show) => Show> = RM.getShow /** * Calculate the number of key/value pairs in a map * * @since 2.0.0 */ export const size: (m: Map) => number = RM.size /** * Test whether or not a map is empty * * @since 2.0.0 */ export const isEmpty: (m: Map) => boolean = RM.isEmpty // TODO: remove non-curried overloading in v3 /** * Test whether or not a key exists in a map * * @since 2.0.0 */ export const member: (E: Eq) => { (k: K): (m: Map) => boolean (k: K, m: Map): boolean } = RM.member // TODO: remove non-curried overloading in v3 /** * Test whether or not a value is a member of a map * * @since 2.0.0 */ export const elem: (E: Eq) => { (a: A): (m: Map) => boolean (a: A, m: Map): boolean } = RM.elem /** * Get a sorted `Array` of the keys contained in a `Map`. * * @since 2.0.0 */ export const keys = (O: Ord) => (m: Map): Array => Array.from(m.keys()).sort(O.compare) /** * Get a sorted `Array` of the values contained in a `Map`. * * @since 2.0.0 */ export const values = (O: Ord) => (m: Map): Array => Array.from(m.values()).sort(O.compare) /** * @since 2.0.0 */ export function collect(O: Ord): (f: (k: K, a: A) => B) => (m: Map) => Array { const keysO = keys(O) return (f: (k: K, a: A) => B) => (m: Map): Array => { const out: Array = [] const ks = keysO(m) for (const key of ks) { out.push(f(key, m.get(key)!)) } return out } } /** * Get a sorted `Array` of the key/value pairs contained in a `Map`. * * @since 2.0.0 */ export function toArray(O: Ord): (m: Map) => Array<[K, A]> { return collect(O)((k, a) => [k, a]) } /** * Unfolds a map into a list of key/value pairs * * @since 2.0.0 */ export function toUnfoldable(ord: Ord, U: Unfoldable1): (d: Map) => Kind export function toUnfoldable(ord: Ord, U: Unfoldable): (d: Map) => HKT export function toUnfoldable(ord: Ord, U: Unfoldable): (d: Map) => HKT { const toArrayO = toArray(ord) return (d) => { const kas = toArrayO(d) const len = kas.length return U.unfold(0, (b) => (b < len ? _.some([kas[b], b + 1]) : _.none)) } } /** * Insert or replace a key/value pair in a `Map`. * * @since 2.0.0 */ export const upsertAt = (E: Eq): ((k: K, a: A) => (m: Map) => Map) => { const lookupWithKeyE = lookupWithKey(E) return (k, a) => { const lookupWithKeyEk = lookupWithKeyE(k) return (m) => { const found = lookupWithKeyEk(m) if (_.isNone(found)) { const out = new Map(m) out.set(k, a) return out } else if (found.value[1] !== a) { const out = new Map(m) out.set(found.value[0], a) return out } return m } } } /** * Delete a key and value from a map * * @since 2.0.0 */ export const deleteAt = (E: Eq): ((k: K) => (m: Map) => Map) => { const lookupWithKeyE = lookupWithKey(E) return (k) => (m) => { const found = lookupWithKeyE(k, m) if (_.isSome(found)) { const r = new Map(m) r.delete(found.value[0]) return r } return m } } /** * @since 2.0.0 */ export const updateAt = (E: Eq): ((k: K, a: A) => (m: Map) => Option>) => { const modifyAtE = modifyAt(E) return (k, a) => modifyAtE(k, () => a) } /** * @since 2.0.0 */ export const modifyAt = (E: Eq): ((k: K, f: (a: A) => A) => (m: Map) => Option>) => { const lookupWithKeyE = lookupWithKey(E) return (k, f) => (m) => { const found = lookupWithKeyE(k, m) if (_.isNone(found)) { return _.none } const r = new Map(m) r.set(found.value[0], f(found.value[1])) return _.some(r) } } /** * Delete a key and value from a map, returning the value as well as the subsequent map * * @since 2.0.0 */ export function pop(E: Eq): (k: K) => (m: Map) => Option<[A, Map]> { const lookupE = lookup(E) const deleteAtE = deleteAt(E) return (k) => { const deleteAtEk = deleteAtE(k) return (m) => pipe( lookupE(k, m), O.map((a) => [a, deleteAtEk(m)]) ) } } type Next = IteratorResult // TODO: remove non-curried overloading in v3 /** * Lookup the value for a key in a `Map`. * If the result is a `Some`, the existing key is also returned. * * @since 2.0.0 */ export function lookupWithKey(E: Eq): { (k: K): (m: Map) => Option<[K, A]> (k: K, m: Map): Option<[K, A]> } export function lookupWithKey( E: Eq ): (k: K, m?: Map) => Option<[K, A]> | ((m: Map) => Option<[K, A]>) { return (k: K, m?: Map) => { if (m === undefined) { const lookupWithKeyE = lookupWithKey(E) return (m) => lookupWithKeyE(k, m) } const entries = m.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [ka, a] = e.value if (E.equals(ka, k)) { return _.some([ka, a]) } } return _.none } } // TODO: remove non-curried overloading in v3 /** * Lookup the value for a key in a `Map`. * * @since 2.0.0 */ export const lookup: (E: Eq) => { (k: K): (m: Map) => Option (k: K, m: Map): Option } = RM.lookup // TODO: remove non-curried overloading in v3 /** * Test whether or not one `Map` contains all of the keys and values contained in another `Map` * * @since 2.0.0 */ export const isSubmap: ( SK: Eq, SA: Eq ) => { (that: Map): (me: Map) => boolean (me: Map, that: Map): boolean } = RM.isSubmap /** * @category instances * @since 2.0.0 */ export const getEq: (SK: Eq, SA: Eq) => Eq> = RM.getEq /** * Gets `Monoid` instance for Maps given `Semigroup` instance for their values * * @category instances * @since 2.0.0 */ export function getMonoid(SK: Eq, SA: Semigroup): Monoid> { const lookupWithKeyS = lookupWithKey(SK) return { concat: (mx, my) => { if (isEmpty(mx)) { return my } if (isEmpty(my)) { return mx } const r = new Map(mx) const entries = my.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [k, a] = e.value const mxOptA = lookupWithKeyS(k, mx) if (_.isSome(mxOptA)) { r.set(mxOptA.value[0], SA.concat(mxOptA.value[1], a)) } else { r.set(k, a) } } return r }, empty: new Map() } } /** * Create a map with one key/value pair * * @since 2.0.0 */ export const singleton = (k: K, a: A): Map => new Map([[k, a]]) /** * Create a map from a foldable collection of key/value pairs, using the * specified `Magma` to combine values for duplicate keys. * * @category constructors * @since 2.0.0 */ export function fromFoldable( E: Eq, M: Magma, F: Foldable3 ): (fka: Kind3) => Map export function fromFoldable( E: Eq, M: Magma, F: Foldable2 ): (fka: Kind2) => Map export function fromFoldable( E: Eq, M: Magma, F: Foldable1 ): (fka: Kind) => Map export function fromFoldable(E: Eq, M: Magma, F: Foldable): (fka: HKT) => Map export function fromFoldable(E: Eq, M: Magma, F: Foldable): (fka: HKT) => Map { return (fka: HKT) => { const lookupWithKeyE = lookupWithKey(E) return F.reduce<[K, A], Map>(fka, new Map(), (b, [k, a]) => { const bOpt = lookupWithKeyE(k, b) if (_.isSome(bOpt)) { b.set(bOpt.value[0], M.concat(bOpt.value[1], a)) } else { b.set(k, a) } return b }) } } const _mapWithIndex = (fa: Map, f: (k: K, a: A) => B): Map => { const m = new Map() const entries = fa.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [key, a] = e.value m.set(key, f(key, a)) } return m } /** * @since 2.10.0 */ export const partitionMapWithIndex = (f: (k: K, a: A) => Either) => (fa: Map): Separated, Map> => { const left = new Map() const right = new Map() const entries = fa.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [k, a] = e.value const ei = f(k, a) if (_.isLeft(ei)) { left.set(k, ei.left) } else { right.set(k, ei.right) } } return separated(left, right) } /** * @since 2.10.0 */ export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => a is B ): (fa: Map) => Separated, Map> export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (fb: Map) => Separated, Map> export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (fa: Map) => Separated, Map> export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (fa: Map) => Separated, Map> { return (fa: Map) => { const left = new Map() const right = new Map() const entries = fa.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [k, a] = e.value if (predicateWithIndex(k, a)) { right.set(k, a) } else { left.set(k, a) } } return separated(left, right) } } /** * @since 2.10.0 */ export const filterMapWithIndex = (f: (k: K, a: A) => Option) => (fa: Map): Map => { const m = new Map() const entries = fa.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [k, a] = e.value const o = f(k, a) if (_.isSome(o)) { m.set(k, o.value) } } return m } /** * @since 2.10.0 */ export function filterWithIndex(p: (k: K, a: A) => a is B): (m: Map) => Map export function filterWithIndex(p: (k: K, a: A) => boolean): (m: Map) => Map export function filterWithIndex(p: (k: K, a: A) => boolean): (m: Map) => Map export function filterWithIndex(p: (k: K, a: A) => boolean): (m: Map) => Map { return (m: Map) => { const out = new Map() const entries = m.entries() let e: Next<[K, A]> while (!(e = entries.next()).done) { const [k, a] = e.value if (p(k, a)) { out.set(k, a) } } return out } } const _map: Functor2['map'] = (fa, f) => _mapWithIndex(fa, (_, a) => f(a)) const _filter: Filterable2['filter'] = (fa: Map, p: Predicate) => _filterWithIndex(fa, (_, a) => p(a)) const _filterMap: Filterable2['filterMap'] = (fa, f) => _filterMapWithIndex(fa, (_, a) => f(a)) const _partition: Filterable2['partition'] = (fa: Map, predicate: Predicate) => _partitionWithIndex(fa, (_, a) => predicate(a)) const _partitionMap: Filterable2['partitionMap'] = (fa, f) => _partitionMapWithIndex(fa, (_, a) => f(a)) const _filterWithIndex = (fa: Map, p: (k: K, a: A) => boolean) => pipe(fa, filterWithIndex(p)) const _filterMapWithIndex = (fa: Map, f: (k: K, a: A) => Option) => pipe(fa, filterMapWithIndex(f)) const _partitionWithIndex = (fa: Map, p: (k: K, a: A) => boolean) => pipe(fa, partitionWithIndex(p)) const _partitionMapWithIndex = (fa: Map, f: (k: K, a: A) => Either) => pipe(fa, partitionMapWithIndex(f)) /** * @category filtering * @since 2.0.0 */ export const compact = (fa: Map>): Map => { const m = new Map() const entries = fa.entries() let e: Next<[K, Option]> while (!(e = entries.next()).done) { const [k, oa] = e.value if (_.isSome(oa)) { m.set(k, oa.value) } } return m } /** * @category filtering * @since 2.0.0 */ export const filter: { (refinement: Refinement): (fa: Map) => Map (predicate: Predicate): (fb: Map) => Map (predicate: Predicate): (fa: Map) => Map } = (predicate: Predicate) => (fa: Map) => _filter(fa, predicate) /** * @category filtering * @since 2.0.0 */ export const filterMap: (f: (a: A) => Option) => (fa: Map) => Map = (f) => (fa) => _filterMap(fa, f) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Map) => Map = (f) => (fa) => _map(fa, f) /** * @category mapping * @since 2.7.1 */ export const mapWithIndex: (f: (k: K, a: A) => B) => (fa: Map) => Map = (f) => (fa) => _mapWithIndex(fa, f) /** * @category filtering * @since 2.0.0 */ export const partition: { (refinement: Refinement): (fa: Map) => Separated, Map> (predicate: Predicate): (fb: Map) => Separated, Map> (predicate: Predicate): (fa: Map) => Separated, Map> } = (predicate: Predicate) => (fa: Map) => _partition(fa, predicate) /** * @category filtering * @since 2.0.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: Map) => Separated, Map> = (f) => (fa) => _partitionMap(fa, f) /** * @category filtering * @since 2.0.0 */ export const separate = (fa: Map>): Separated, Map> => { const left = new Map() const right = new Map() const entries = fa.entries() let e: Next<[K, Either]> while (!(e = entries.next()).done) { const [k, ei] = e.value if (_.isLeft(ei)) { left.set(k, ei.left) } else { right.set(k, ei.right) } } return separated(left, right) } /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Map' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Map } } /** * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq, S: Semigroup): Semigroup> => { const unionES = union(E, S) return { concat: (first, second) => unionES(second)(first) } } /** * @category instances * @since 2.11.0 */ export const getUnionMonoid = (E: Eq, S: Semigroup): Monoid> => ({ concat: getUnionSemigroup(E, S).concat, empty: new Map() }) /** * @category instances * @since 2.11.0 */ export const getIntersectionSemigroup = (E: Eq, S: Semigroup): Semigroup> => { const intersectionES = intersection(E, S) return { concat: (first, second) => intersectionES(second)(first) } } /** * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (E: Eq) => (): Magma> => { const differenceE = difference(E) return { concat: (first, second) => differenceE(second)(first) } } /** * @category filtering * @since 2.0.0 */ export function getFilterableWithIndex(): FilterableWithIndex2C { return { URI, _E: undefined as any, map: _map, mapWithIndex: _mapWithIndex, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex } } /** * @category filtering * @since 2.0.0 */ export function getWitherable(O: Ord): Witherable2C & TraversableWithIndex2C { const TWI = getTraversableWithIndex(O) return { URI, _E: undefined as any, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, reduce: TWI.reduce, foldMap: TWI.foldMap, reduceRight: TWI.reduceRight, traverse: TWI.traverse, sequence: TWI.sequence, mapWithIndex: _mapWithIndex, reduceWithIndex: TWI.reduceWithIndex, foldMapWithIndex: TWI.foldMapWithIndex, reduceRightWithIndex: TWI.reduceRightWithIndex, traverseWithIndex: TWI.traverseWithIndex, wilt: wiltDefault(TWI, Compactable), wither: witherDefault(TWI, Compactable) } } /** * @category folding * @since 2.11.0 */ export const reduce: (O: Ord) => (b: B, f: (b: B, a: A) => B) => (m: Map) => B = RM.reduce /** * @category folding * @since 2.11.0 */ export const foldMap: (O: Ord) => (M: Monoid) => (f: (a: A) => M) => (m: Map) => M = RM.foldMap /** * @category folding * @since 2.11.0 */ export const reduceRight: (O: Ord) => (b: B, f: (a: A, b: B) => B) => (m: Map) => B = RM.reduceRight /** * @category folding * @since 2.11.0 */ export const getFoldable = (O: Ord): Foldable2C => { return { ...RM.getFoldable(O), URI } } /** * @category folding * @since 2.11.0 */ export const reduceWithIndex: (O: Ord) => (b: B, f: (k: K, b: B, a: A) => B) => (m: Map) => B = RM.reduceWithIndex /** * @category folding * @since 2.11.0 */ export const foldMapWithIndex: (O: Ord) => (M: Monoid) => (f: (k: K, a: A) => M) => (m: Map) => M = RM.foldMapWithIndex /** * @category folding * @since 2.11.0 */ export const reduceRightWithIndex: (O: Ord) => (b: B, f: (k: K, a: A, b: B) => B) => (m: Map) => B = RM.reduceRightWithIndex /** * @category folding * @since 2.10.0 */ export const getFoldableWithIndex = (O: Ord): FoldableWithIndex2C => { return { ...RM.getFoldableWithIndex(O), URI } } /** * @category traversing * @since 2.10.0 */ export const getTraversableWithIndex = (O: Ord): TraversableWithIndex2C => { const FWI = getFoldableWithIndex(O) const keysO = keys(O) const traverseWithIndex = ( F: Applicative ): ((ta: Map, f: (k: K, a: A) => HKT) => HKT>) => { return (ta: Map, f: (k: K, a: A) => HKT) => { let fm: HKT> = F.of(new Map()) const ks = keysO(ta) const len = ks.length for (let i = 0; i < len; i++) { const key = ks[i] const a = ta.get(key)! fm = F.ap( F.map(fm, (m) => (b: B) => m.set(key, b)), f(key, a) ) } return fm } } const traverse = (F: Applicative): ((ta: Map, f: (a: A) => HKT) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta, f) => traverseWithIndexF(ta, (_, a) => f(a)) } const sequence = (F: Applicative): ((ta: Map>) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta) => traverseWithIndexF(ta, (_, a) => a) } return { URI, _E: undefined as any, map: _map, mapWithIndex: _mapWithIndex, reduce: FWI.reduce, foldMap: FWI.foldMap, reduceRight: FWI.reduceRight, reduceWithIndex: FWI.reduceWithIndex, foldMapWithIndex: FWI.foldMapWithIndex, reduceRightWithIndex: FWI.reduceRightWithIndex, traverse, sequence, traverseWithIndex } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable2 = { URI, compact, separate } /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable2 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- const copy = (m: Map): Map => new Map(m) /** * @since 2.11.0 */ export const union = (E: Eq, M: Magma): ((second: Map) => (first: Map) => Map) => { const unionEM = RM.union(E, M) return (second) => (first) => { if (isEmpty(first)) { return copy(second) } if (isEmpty(second)) { return copy(first) } return unionEM(second)(first) as any } } /** * @since 2.11.0 */ export const intersection = (E: Eq, M: Magma): ((second: Map) => (first: Map) => Map) => { const intersectionEM = RM.intersection(E, M) return (second) => (first) => { if (isEmpty(first) || isEmpty(second)) { return new Map() } return intersectionEM(second)(first) as any } } /** * @since 2.11.0 */ export const difference = (E: Eq): ((_second: Map) => (first: Map) => Map) => { const differenceE = RM.difference(E) return (second: Map) => (first: Map) => { if (isEmpty(first)) { return copy(second) } if (isEmpty(second)) { return copy(first) } return differenceE(second)(first) as any } } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use a `new Map()` instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const empty = new Map() /** * Use [`upsertAt`](#upsertat) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const insertAt: (E: Eq) => (k: K, a: A) => (m: Map) => Map = upsertAt /** * Use [`Filterable`](#filterable) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const map_: Filterable2 = Filterable ================================================ FILE: src/MeetSemilattice.ts ================================================ /** * A meet-semilattice (or lower semilattice) is a semilattice whose operation is called `meet`, and which can be thought * of as a greatest lower bound. * * A `MeetSemilattice` must satisfy the following laws: * * - Associativity: `a ∧ (b ∧ c) <-> (a ∧ b) ∧ c` * - Commutativity: `a ∧ b <-> b ∧ a` * - Idempotency: `a ∧ a <-> a` * * @since 2.0.0 */ // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface MeetSemilattice { readonly meet: (x: A, y: A) => A } ================================================ FILE: src/Monad.ts ================================================ /** * The `Monad` type class combines the operations of the `Chain` and * `Applicative` type classes. Therefore, `Monad` instances represent type * constructors which support sequential composition, and also lifting of * functions of arbitrary arity. * * Instances must satisfy the following laws in addition to the `Applicative` and `Chain` laws: * * 1. Left identity: `M.chain(M.of(a), f) <-> f(a)` * 2. Right identity: `M.chain(fa, M.of) <-> fa` * * Note. `Functor`'s `map` can be derived: `A.map = (fa, f) => A.chain(fa, a => A.of(f(a)))` * * @since 2.0.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C, Applicative4 } from './Applicative' import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4 } from './Chain' import { URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Monad extends Applicative, Chain {} /** * @category model * @since 2.0.0 */ export interface Monad1 extends Applicative1, Chain1 {} /** * @category model * @since 2.0.0 */ export interface Monad2 extends Applicative2, Chain2 {} /** * @category model * @since 2.0.0 */ export interface Monad2C extends Applicative2C, Chain2C {} /** * @category model * @since 2.0.0 */ export interface Monad3 extends Applicative3, Chain3 {} /** * @category model * @since 2.2.0 */ export interface Monad3C extends Applicative3C, Chain3C {} /** * @category model * @since 2.0.0 */ export interface Monad4 extends Applicative4, Chain4 {} ================================================ FILE: src/MonadIO.ts ================================================ /** * Lift a computation from the `IO` monad * * @since 2.0.0 */ import { FromIO, FromIO1, FromIO2, FromIO2C, FromIO3, FromIO3C, FromIO4 } from './FromIO' import { URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C, Monad4 } from './Monad' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface MonadIO extends Monad, FromIO {} /** * @category model * @since 2.0.0 */ export interface MonadIO1 extends Monad1, FromIO1 {} /** * @category model * @since 2.0.0 */ export interface MonadIO2 extends Monad2, FromIO2 {} /** * @category model * @since 2.0.0 */ export interface MonadIO2C extends Monad2C, FromIO2C {} /** * @category model * @since 2.0.0 */ export interface MonadIO3 extends Monad3, FromIO3 {} /** * @category model * @since 2.2.0 */ export interface MonadIO3C extends Monad3C, FromIO3C {} /** * @category model * @since 2.4.4 */ export interface MonadIO4 extends Monad4, FromIO4 {} ================================================ FILE: src/MonadTask.ts ================================================ /** * Lift a computation from the `Task` monad * * @since 2.0.0 */ import { FromTask, FromTask1, FromTask2, FromTask2C, FromTask3, FromTask3C, FromTask4 } from './FromTask' import { URIS, URIS2, URIS3, URIS4 } from './HKT' import { MonadIO, MonadIO1, MonadIO2, MonadIO2C, MonadIO3, MonadIO3C, MonadIO4 } from './MonadIO' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface MonadTask extends MonadIO, FromTask {} /** * @category model * @since 2.0.0 */ export interface MonadTask1 extends MonadIO1, FromTask1 {} /** * @category model * @since 2.0.0 */ export interface MonadTask2 extends MonadIO2, FromTask2 {} /** * @category model * @since 2.0.0 */ export interface MonadTask2C extends MonadIO2C, FromTask2C {} /** * @category model * @since 2.0.0 */ export interface MonadTask3 extends MonadIO3, FromTask3 {} /** * @category model * @since 2.2.0 */ export interface MonadTask3C extends MonadIO3C, FromTask3C {} /** * @category model * @since 2.4.4 */ export interface MonadTask4 extends MonadIO4, FromTask4 {} ================================================ FILE: src/MonadThrow.ts ================================================ /** * The `MonadThrow` type class represents those monads which support errors via * `throwError`, where `throwError(e)` halts, yielding the error `e`. * * Laws: * * - Left zero: `M.chain(M.throwError(e), f) = M.throwError(e)` * * @since 2.0.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C, Monad4 } from './Monad' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface MonadThrow extends Monad { readonly throwError: (e: E) => HKT } /** * @category model * @since 2.0.0 */ export interface MonadThrow1 extends Monad1 { readonly throwError: (e: E) => Kind } /** * @category model * @since 2.0.0 */ export interface MonadThrow2 extends Monad2 { readonly throwError: (e: E) => Kind2 } /** * @category model * @since 2.0.0 */ export interface MonadThrow2C extends Monad2C { readonly throwError: (e: E) => Kind2 } /** * @category model * @since 2.0.0 */ export interface MonadThrow3 extends Monad3 { readonly throwError: (e: E) => Kind3 } /** * @category model * @since 2.2.0 */ export interface MonadThrow3C extends Monad3C { readonly throwError: (e: E) => Kind3 } /** * @category model * @since 2.0.0 */ export interface MonadThrow4 extends Monad4 { readonly throwError: (e: E) => Kind4 } ================================================ FILE: src/Monoid.ts ================================================ /** * `Monoid` extends the power of `Semigroup` by providing an additional `empty` value. * * ```ts * interface Semigroup { * readonly concat: (x: A, y: A) => A * } * * interface Monoid extends Semigroup { * readonly empty: A * } * ``` * * This `empty` value should be an identity for the `concat` operation, which means the following equalities hold for any choice of `x`. * * ```ts * concat(x, empty) = concat(empty, x) = x * ``` * * Many types that form a `Semigroup` also form a `Monoid`, such as `number`s (with `0`) and `string`s (with `''`). * * ```ts * import { Monoid } from 'fp-ts/Monoid' * * const monoidString: Monoid = { * concat: (x, y) => x + y, * empty: '' * } * ``` * * *Adapted from https://typelevel.org/cats* * * @since 2.0.0 */ import { Bounded } from './Bounded' import { Endomorphism, getMonoid as getEM } from './Endomorphism' import { getMonoid as getFM } from './function' import * as _ from './internal' import { ReadonlyRecord } from './ReadonlyRecord' import * as Se from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Monoid extends Se.Semigroup { readonly empty: A } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Get a monoid where `concat` will return the minimum, based on the provided bounded order. * * The `empty` value is the `top` value. * * @example * import * as N from 'fp-ts/number' * import * as M from 'fp-ts/Monoid' * * const M1 = M.min(N.Bounded) * * assert.deepStrictEqual(M1.concat(1, 2), 1) * * @category constructors * @since 2.10.0 */ export const min = (B: Bounded): Monoid => ({ concat: Se.min(B).concat, empty: B.top }) /** * Get a monoid where `concat` will return the maximum, based on the provided bounded order. * * The `empty` value is the `bottom` value. * * @example * import * as N from 'fp-ts/number' * import * as M from 'fp-ts/Monoid' * * const M1 = M.max(N.Bounded) * * assert.deepStrictEqual(M1.concat(1, 2), 2) * * @category constructors * @since 2.10.0 */ export const max = (B: Bounded): Monoid => ({ concat: Se.max(B).concat, empty: B.bottom }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * The dual of a `Monoid`, obtained by swapping the arguments of `concat`. * * @example * import { reverse } from 'fp-ts/Monoid' * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(reverse(S.Monoid).concat('a', 'b'), 'ba') * * @since 2.10.0 */ export const reverse = (M: Monoid): Monoid => ({ concat: Se.reverse(M).concat, empty: M.empty }) /** * Given a struct of monoids returns a monoid for the struct. * * @example * import { struct } from 'fp-ts/Monoid' * import * as N from 'fp-ts/number' * * interface Point { * readonly x: number * readonly y: number * } * * const M = struct({ * x: N.MonoidSum, * y: N.MonoidSum * }) * * assert.deepStrictEqual(M.concat({ x: 1, y: 2 }, { x: 3, y: 4 }), { x: 4, y: 6 }) * * @since 2.10.0 */ export const struct = (monoids: { [K in keyof A]: Monoid }): Monoid<{ readonly [K in keyof A]: A[K] }> => { const empty: A = {} as any for (const k in monoids) { if (_.has.call(monoids, k)) { empty[k] = monoids[k].empty } } return { concat: Se.struct(monoids).concat, empty } } /** * Given a tuple of monoids returns a monoid for the tuple. * * @example * import { tuple } from 'fp-ts/Monoid' * import * as B from 'fp-ts/boolean' * import * as N from 'fp-ts/number' * import * as S from 'fp-ts/string' * * const M1 = tuple(S.Monoid, N.MonoidSum) * assert.deepStrictEqual(M1.concat(['a', 1], ['b', 2]), ['ab', 3]) * * const M2 = tuple(S.Monoid, N.MonoidSum, B.MonoidAll) * assert.deepStrictEqual(M2.concat(['a', 1, true], ['b', 2, false]), ['ab', 3, false]) * * @since 2.10.0 */ export const tuple = >( ...monoids: { [K in keyof A]: Monoid } ): Monoid> => ({ concat: Se.tuple(...(monoids as any)).concat, empty: monoids.map((m) => m.empty) } as any) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Given a sequence of `as`, concat them and return the total. * * If `as` is empty, return the monoid `empty` value. * * @example * import { concatAll } from 'fp-ts/Monoid' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(concatAll(N.MonoidSum)([1, 2, 3]), 6) * assert.deepStrictEqual(concatAll(N.MonoidSum)([]), 0) * * @since 2.10.0 */ export const concatAll = (M: Monoid): ((as: ReadonlyArray) => A) => Se.concatAll(M)(M.empty) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`Monoid`](./void.ts.html#monoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const monoidVoid: Monoid = { concat: Se.semigroupVoid.concat, empty: undefined } /** * Use [`tuple`](#tuple) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getTupleMonoid: >>( ...monoids: T ) => Monoid<{ [K in keyof T]: T[K] extends Se.Semigroup ? A : never }> = tuple as any /** * Use [`struct`](#struct) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getStructMonoid: >(monoids: { [K in keyof O]: Monoid }) => Monoid = struct /** * Use [`reverse`](#reverse) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getDualMonoid = reverse /** * Use [`max`](#max) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getJoinMonoid = max /** * Use [`min`](#min) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getMeetMonoid = min /** * Use [`concatAll`](#concatall) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const fold = concatAll /** * Use [`MonoidAll`](./boolean.ts.html#monoidall) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const monoidAll: Monoid = { concat: Se.semigroupAll.concat, empty: true } /** * Use [`MonoidAny`](./boolean.ts.html#monoidany) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const monoidAny: Monoid = { concat: Se.semigroupAny.concat, empty: false } /** * Use [`getMonoid`](./function.ts.html#getmonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFunctionMonoid: (M: Monoid) => () => Monoid<(a: A) => M> = getFM /** * Use [`getEndomorphismMonoid`](./function.ts.html#getendomorphismmonoid) instead. * * **Note**. The execution order in [`getEndomorphismMonoid`](./function.ts.html#getendomorphismmonoid) is reversed. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getEndomorphismMonoid = (): Monoid> => reverse(getEM()) /** * Use [`Monoid`](./string.ts.html#monoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const monoidString: Monoid = { concat: Se.semigroupString.concat, empty: '' } /** * Use [`MonoidSum`](./number.ts.html#monoidsum) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const monoidSum: Monoid = { concat: Se.semigroupSum.concat, empty: 0 } /** * Use [`MonoidProduct`](./number.ts.html#monoidproduct) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const monoidProduct: Monoid = { concat: Se.semigroupProduct.concat, empty: 1 } ================================================ FILE: src/NaturalTransformation.ts ================================================ /** * A type for natural transformations. * * A natural transformation is a mapping between type constructors of kind `* -> *` where the mapping * operation has no ability to manipulate the inner values. * * The definition of a natural transformation in category theory states that `F` and `G` should be functors, * but the `Functor` constraint is not enforced here; that the types are of kind `* -> *` is enough for our purposes. * * @since 2.11.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' /** * @since 2.11.0 */ export interface NaturalTransformation { (fa: HKT): HKT } /** * @since 2.11.0 */ export interface NaturalTransformation11 { (fa: Kind): Kind } /** * @since 2.11.0 */ export interface NaturalTransformation12 { (fa: Kind): Kind2 } /** * @since 2.11.0 */ export interface NaturalTransformation12C { (fa: Kind): Kind2 } /** * @since 2.11.0 */ export interface NaturalTransformation13 { (fa: Kind): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation13C { (fa: Kind): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation14 { (fa: Kind): Kind4 } /** * @since 2.11.0 */ export interface NaturalTransformation14C { (fa: Kind): Kind4 } /** * @since 2.11.0 */ export interface NaturalTransformation21 { (fa: Kind2): Kind } /** * @since 2.11.0 */ export interface NaturalTransformation22 { (fa: Kind2): Kind2 } /** * @since 2.11.0 */ export interface NaturalTransformation22C { (fa: Kind2): Kind2 } /** * @since 2.11.0 */ export interface NaturalTransformation23 { (fa: Kind2): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation23C { (fa: Kind2): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation24 { (fa: Kind2): Kind4 } /** * @since 2.11.0 */ export interface NaturalTransformation23R { (fa: Kind2): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation23RC { (fa: Kind2): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation24R { (fa: Kind2): Kind4 } /** * @since 2.11.0 */ export interface NaturalTransformation24S { (fa: Kind2): Kind4 } /** * @since 2.11.0 */ export interface NaturalTransformation33 { (fa: Kind3): Kind3 } /** * @since 2.11.0 */ export interface NaturalTransformation34 { (fa: Kind3): Kind4 } ================================================ FILE: src/NonEmptyArray.ts ================================================ /** * Data structure which represents non-empty arrays. * * ```ts * export type NonEmptyArray = Array & { * 0: A * } * ``` * * Note that you don't need any conversion, a `NonEmptyArray` is an `Array`, * so all `Array`'s APIs can be used with a `NonEmptyArray` without further ado. * * @since 2.0.0 */ import { Alt1 } from './Alt' import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain' import { Comonad1 } from './Comonad' import { Endomorphism } from './Endomorphism' import { Eq } from './Eq' import { Extend1 } from './Extend' import { Foldable1 } from './Foldable' import { FoldableWithIndex1 } from './FoldableWithIndex' import { dual, identity, LazyArg, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { FunctorWithIndex1 } from './FunctorWithIndex' import { HKT } from './HKT' import * as _ from './internal' import { Monad1 } from './Monad' import { Option } from './Option' import { getMonoid, Ord } from './Ord' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import * as RNEA from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import * as Se from './Semigroup' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' import { PipeableTraverseWithIndex1, TraversableWithIndex1 } from './TraversableWithIndex' import Semigroup = Se.Semigroup import ReadonlyNonEmptyArray = RNEA.ReadonlyNonEmptyArray // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface NonEmptyArray extends Array { 0: A } // ------------------------------------------------------------------------------------- // internal // ------------------------------------------------------------------------------------- /** * @internal */ export const isNonEmpty = (as: Array): as is NonEmptyArray => as.length > 0 /** * @internal */ export const isOutOfBound = (i: number, as: Array): boolean => i < 0 || i >= as.length /** * @internal */ export const prependW = (head: B) => (tail: Array): NonEmptyArray => [head, ...tail] /** * @internal */ export const prepend: (head: A) => (tail: Array) => NonEmptyArray = prependW /** * @internal */ export const appendW = (end: B) => (init: Array): NonEmptyArray => [...init, end] as any /** * @internal */ export const append: (end: A) => (init: Array) => NonEmptyArray = appendW /** * @internal */ export const unsafeInsertAt = (i: number, a: A, as: Array): NonEmptyArray => { if (isNonEmpty(as)) { const xs = fromReadonlyNonEmptyArray(as) xs.splice(i, 0, a) return xs } return [a] } /** * @internal */ export const unsafeUpdateAt = (i: number, a: A, as: NonEmptyArray): NonEmptyArray => { const xs = fromReadonlyNonEmptyArray(as) xs[i] = a return xs } /** * Remove duplicates from a `NonEmptyArray`, keeping the first occurrence of an element. * * @example * import { uniq } from 'fp-ts/NonEmptyArray' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) * * @since 2.11.0 */ export const uniq = (E: Eq) => (as: NonEmptyArray): NonEmptyArray => { if (as.length === 1) { return copy(as) } const out: NonEmptyArray = [head(as)] const rest = tail(as) for (const a of rest) { if (out.every((o) => !E.equals(o, a))) { out.push(a) } } return out } /** * Sort the elements of a `NonEmptyArray` in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, * etc... * * @example * import * as NEA from 'fp-ts/NonEmptyArray' * import { contramap } from 'fp-ts/Ord' * import * as S from 'fp-ts/string' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * interface Person { * name: string * age: number * } * * const byName = pipe(S.Ord, contramap((p: Person) => p.name)) * * const byAge = pipe(N.Ord, contramap((p: Person) => p.age)) * * const sortByNameByAge = NEA.sortBy([byName, byAge]) * * const persons: NEA.NonEmptyArray = [ * { name: 'a', age: 1 }, * { name: 'b', age: 3 }, * { name: 'c', age: 2 }, * { name: 'b', age: 2 } * ] * * assert.deepStrictEqual(sortByNameByAge(persons), [ * { name: 'a', age: 1 }, * { name: 'b', age: 2 }, * { name: 'b', age: 3 }, * { name: 'c', age: 2 } * ]) * * @since 2.11.0 */ export const sortBy = (ords: Array>): ((as: NonEmptyArray) => NonEmptyArray) => { if (isNonEmpty(ords)) { const M = getMonoid() return sort(ords.reduce(M.concat, M.empty)) } return copy } /** * @since 2.11.0 */ export const union = (E: Eq): ((second: NonEmptyArray) => (first: NonEmptyArray) => NonEmptyArray) => { const uniqE = uniq(E) return (second) => (first) => uniqE(pipe(first, concat(second))) } /** * Rotate a `NonEmptyArray` by `n` steps. * * @example * import { rotate } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) * assert.deepStrictEqual(rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) * * @since 2.11.0 */ export const rotate = (n: number) => (as: NonEmptyArray): NonEmptyArray => { const len = as.length const m = Math.round(n) % len if (isOutOfBound(Math.abs(m), as) || m === 0) { return copy(as) } if (m < 0) { const [f, s] = splitAt(-m)(as) return pipe(s, concat(f)) } else { return rotate(m - len)(as) } } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.10.0 */ export const fromReadonlyNonEmptyArray: (as: ReadonlyNonEmptyArray) => NonEmptyArray = _.fromReadonlyNonEmptyArray /** * Builds a `NonEmptyArray` from an `Array` returning `none` if `as` is an empty array * * @category conversions * @since 2.0.0 */ export const fromArray = (as: Array): Option> => (isNonEmpty(as) ? _.some(as) : _.none) /** * Return a `NonEmptyArray` of length `n` with element `i` initialized with `f(i)`. * * **Note**. `n` is normalized to a natural number. * * @example * import { makeBy } from 'fp-ts/NonEmptyArray' * import { pipe } from 'fp-ts/function' * * const double = (n: number): number => n * 2 * assert.deepStrictEqual(pipe(5, makeBy(double)), [0, 2, 4, 6, 8]) * * @category constructors * @since 2.11.0 */ export const makeBy = (f: (i: number) => A) => (n: number): NonEmptyArray => { const j = Math.max(0, Math.floor(n)) const out: NonEmptyArray = [f(0)] for (let i = 1; i < j; i++) { out.push(f(i)) } return out } /** * Create a `NonEmptyArray` containing a value repeated the specified number of times. * * **Note**. `n` is normalized to a natural number. * * @example * import { replicate } from 'fp-ts/NonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(3, replicate('a')), ['a', 'a', 'a']) * * @category constructors * @since 2.11.0 */ export const replicate = (a: A): ((n: number) => ReadonlyNonEmptyArray) => makeBy(() => a) /** * Create a `NonEmptyArray` containing a range of integers, including both endpoints. * * @example * import { range } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(range(1, 5), [1, 2, 3, 4, 5]) * * @category constructors * @since 2.11.0 */ export const range = (start: number, end: number): NonEmptyArray => start <= end ? makeBy((i) => start + i)(end - start + 1) : [start] /** * Return the tuple of the `head` and the `tail`. * * @example * import { unprepend } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(unprepend([1, 2, 3]), [1, [2, 3]]) * * @since 2.9.0 */ export const unprepend = (as: NonEmptyArray): [A, Array] => [head(as), tail(as)] /** * Return the tuple of the `init` and the `last`. * * @example * import { unappend } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) * * @since 2.9.0 */ export const unappend = (as: NonEmptyArray): [Array, A] => [init(as), last(as)] // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function concatW(second: NonEmptyArray): (first: Array) => NonEmptyArray export function concatW(second: Array): (first: NonEmptyArray) => NonEmptyArray export function concatW(second: Array): (first: NonEmptyArray) => Array { return (first: NonEmptyArray) => first.concat(second) } /** * @since 2.2.0 */ export function concat(second: NonEmptyArray): (first: Array) => NonEmptyArray export function concat(second: Array): (first: NonEmptyArray) => NonEmptyArray /** @deprecated */ export function concat(first: Array, second: NonEmptyArray): NonEmptyArray /** @deprecated */ export function concat(first: NonEmptyArray, second: Array): NonEmptyArray export function concat(x: Array, y?: Array): Array | ((y: NonEmptyArray) => Array) { return y ? x.concat(y) : (y) => y.concat(x) } /** * @since 2.0.0 */ export const reverse = (as: NonEmptyArray): NonEmptyArray => [last(as), ...as.slice(0, -1).reverse()] /** * Group equal, consecutive elements of an array into non empty arrays. * * @example * import { group } from 'fp-ts/NonEmptyArray' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(group(N.Ord)([1, 2, 1, 1]), [ * [1], * [2], * [1, 1] * ]) * * @since 2.0.0 */ export function group(E: Eq): { (as: NonEmptyArray): NonEmptyArray> (as: Array): Array> } export function group(E: Eq): (as: Array) => Array> { return (as) => { const len = as.length if (len === 0) { return [] } const out: Array> = [] let head: A = as[0] let nea: NonEmptyArray = [head] for (let i = 1; i < len; i++) { const a = as[i] if (E.equals(a, head)) { nea.push(a) } else { out.push(nea) head = a nea = [head] } } out.push(nea) return out } } /** * Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning * function on each element, and grouping the results according to values returned * * @example * import { groupBy } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(groupBy((s: string) => String(s.length))(['a', 'b', 'ab']), { * '1': ['a', 'b'], * '2': ['ab'] * }) * * @since 2.0.0 */ export const groupBy = (f: (a: A) => string) => (as: Array): Record> => { const out: Record> = {} for (const a of as) { const k = f(a) if (_.has.call(out, k)) { out[k].push(a) } else { out[k] = [a] } } return out } /** * @since 2.0.0 */ export const sort = (O: Ord) => (as: NonEmptyArray): NonEmptyArray => as.slice().sort(O.compare) as any /** * @since 2.0.0 */ export const insertAt = (i: number, a: A) => (as: Array): Option> => i < 0 || i > as.length ? _.none : _.some(unsafeInsertAt(i, a, as)) /** * @since 2.0.0 */ export const updateAt = (i: number, a: A): ((as: NonEmptyArray) => Option>) => modifyAt(i, () => a) /** * @since 2.0.0 */ export const modifyAt = (i: number, f: (a: A) => A) => (as: NonEmptyArray): Option> => isOutOfBound(i, as) ? _.none : _.some(unsafeUpdateAt(i, f(as[i]), as)) /** * @since 2.0.0 */ export const copy: (as: NonEmptyArray) => NonEmptyArray = fromReadonlyNonEmptyArray /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => NonEmptyArray = (a) => [a] /** * @since 2.5.1 */ export const zipWith = ( as: NonEmptyArray, bs: NonEmptyArray, f: (a: A, b: B) => C ): NonEmptyArray => { const cs: NonEmptyArray = [f(as[0], bs[0])] const len = Math.min(as.length, bs.length) for (let i = 1; i < len; i++) { cs[i] = f(as[i], bs[i]) } return cs } /** * @since 2.5.1 */ export function zip(bs: NonEmptyArray): (as: NonEmptyArray) => NonEmptyArray<[A, B]> export function zip(as: NonEmptyArray, bs: NonEmptyArray): NonEmptyArray<[A, B]> export function zip( as: NonEmptyArray, bs?: NonEmptyArray ): NonEmptyArray<[A, B]> | ((bs: NonEmptyArray) => NonEmptyArray<[B, A]>) { if (bs === undefined) { return (bs) => zip(bs, as) } return zipWith(as, bs, (a, b) => [a, b]) } /** * @since 2.5.1 */ export const unzip = (abs: NonEmptyArray<[A, B]>): [NonEmptyArray, NonEmptyArray] => { const fa: NonEmptyArray = [abs[0][0]] const fb: NonEmptyArray = [abs[0][1]] for (let i = 1; i < abs.length; i++) { fa[i] = abs[i][0] fb[i] = abs[i][1] } return [fa, fb] } /** * Prepend an element to every member of an array * * @example * import { prependAll } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) * * @since 2.10.0 */ export const prependAll = (middle: A) => (as: NonEmptyArray): NonEmptyArray => { const out: NonEmptyArray = [middle, as[0]] for (let i = 1; i < as.length; i++) { out.push(middle, as[i]) } return out } /** * Places an element in between members of an array * * @example * import { intersperse } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) * * @since 2.9.0 */ export const intersperse = (middle: A) => (as: NonEmptyArray): NonEmptyArray => { const rest = tail(as) return isNonEmpty(rest) ? pipe(rest, prependAll(middle), prepend(head(as))) : copy(as) } /** * @category folding * @since 2.0.0 */ export const foldMapWithIndex: (S: Semigroup) => (f: (i: number, a: A) => S) => (fa: NonEmptyArray) => S = RNEA.foldMapWithIndex /** * @category folding * @since 2.0.0 */ export const foldMap: (S: Semigroup) => (f: (a: A) => S) => (fa: NonEmptyArray) => S = RNEA.foldMap /** * @category sequencing * @since 2.10.0 */ export const chainWithIndex = (f: (i: number, a: A) => NonEmptyArray) => (as: NonEmptyArray): NonEmptyArray => { const out: NonEmptyArray = fromReadonlyNonEmptyArray(f(0, head(as))) for (let i = 1; i < as.length; i++) { const bs = f(i, as[i]) for (let j = 0; j < bs.length; j++) { out.push(bs[j]) } } return out } /** * @since 2.10.0 */ export const chop = (f: (as: NonEmptyArray) => [B, Array]) => (as: NonEmptyArray): NonEmptyArray => { const [b, rest] = f(as) const out: NonEmptyArray = [b] let next: Array = rest while (isNonEmpty(next)) { const [b, rest] = f(next) out.push(b) next = rest } return out } /** * Splits a `NonEmptyArray` into two pieces, the first piece has max `n` elements. * * @since 2.10.0 */ export const splitAt = (n: number) => (as: NonEmptyArray): [NonEmptyArray, Array] => { const m = Math.max(1, n) return m >= as.length ? [copy(as), []] : [pipe(as.slice(1, m), prepend(head(as))), as.slice(m)] } /** * @since 2.10.0 */ export const chunksOf = (n: number): ((as: NonEmptyArray) => NonEmptyArray>) => chop(splitAt(n)) /* istanbul ignore next */ const _map: Functor1['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _mapWithIndex: FunctorWithIndex1['mapWithIndex'] = (fa, f) => pipe(fa, mapWithIndex(f)) /* istanbul ignore next */ const _ap: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _extend: Extend1['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _reduce: Foldable1['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable1['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable1['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _traverse: Traversable1['traverse'] = ( F: ApplicativeHKT ): ((ta: NonEmptyArray, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) /* istanbul ignore next */ const _reduceWithIndex: FoldableWithIndex1['reduceWithIndex'] = (fa, b, f) => pipe(fa, reduceWithIndex(b, f)) /* istanbul ignore next */ const _foldMapWithIndex: FoldableWithIndex1['foldMapWithIndex'] = (M) => { const foldMapWithIndexM = foldMapWithIndex(M) return (fa, f) => pipe(fa, foldMapWithIndexM(f)) } /* istanbul ignore next */ const _reduceRightWithIndex: FoldableWithIndex1['reduceRightWithIndex'] = (fa, b, f) => pipe(fa, reduceRightWithIndex(b, f)) /* istanbul ignore next */ const _traverseWithIndex: TraversableWithIndex1['traverseWithIndex'] = ( F: ApplicativeHKT ): ((ta: NonEmptyArray, f: (i: number, a: A) => HKT) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta, f) => pipe(ta, traverseWithIndexF(f)) } /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @example * import * as NEA from 'fp-ts/NonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3] as NEA.NonEmptyArray, * NEA.altW(() => ['a', 'b']) * ), * [1, 2, 3, 'a', 'b'] * ) * * @category error handling * @since 2.9.0 */ export const altW = (that: LazyArg>) => (as: NonEmptyArray): NonEmptyArray => pipe(as, concatW(that())) /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * In case of `NonEmptyArray` concatenates the inputs into a single array. * * @example * import * as NEA from 'fp-ts/NonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * NEA.alt(() => [4, 5]) * ), * [1, 2, 3, 4, 5] * ) * * @category error handling * @since 2.6.2 */ export const alt: (that: LazyArg>) => (fa: NonEmptyArray) => NonEmptyArray = altW /** * Apply a function to an argument under a type constructor. * * @since 2.0.0 */ export const ap = (as: NonEmptyArray): ((fab: NonEmptyArray<(a: A) => B>) => NonEmptyArray) => flatMap((f) => pipe(as, map(f))) /** * @example * import * as NEA from 'fp-ts/NonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * NEA.flatMap((n) => [`a${n}`, `b${n}`]) * ), * ['a1', 'b1', 'a2', 'b2', 'a3', 'b3'] * ) * * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A, i: number) => NonEmptyArray): (ma: NonEmptyArray) => NonEmptyArray (ma: NonEmptyArray, f: (a: A, i: number) => NonEmptyArray): NonEmptyArray } = /*#__PURE__*/ dual( 2, (ma: NonEmptyArray, f: (a: A, i: number) => NonEmptyArray): NonEmptyArray => pipe( ma, chainWithIndex((i, a) => f(a, i)) ) ) /** * @since 2.0.0 */ export const extend = (f: (as: NonEmptyArray) => B) => (as: NonEmptyArray): NonEmptyArray => { let next: Array = tail(as) const out: NonEmptyArray = [f(as)] while (isNonEmpty(next)) { out.push(f(next)) next = tail(next) } return out } /** * @since 2.5.0 */ export const duplicate: (ma: NonEmptyArray) => NonEmptyArray> = /*#__PURE__*/ extend(identity) /** * @category sequencing * @since 2.5.0 */ export const flatten: (mma: NonEmptyArray>) => NonEmptyArray = /*#__PURE__*/ flatMap(identity) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map = (f: (a: A) => B): ((as: NonEmptyArray) => NonEmptyArray) => mapWithIndex((_, a) => f(a)) /** * @category mapping * @since 2.0.0 */ export const mapWithIndex = (f: (i: number, a: A) => B) => (as: NonEmptyArray): NonEmptyArray => { const out: NonEmptyArray = [f(0, head(as))] for (let i = 1; i < as.length; i++) { out.push(f(i, as[i])) } return out } /** * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: NonEmptyArray) => B = RNEA.reduce /** * @category folding * @since 2.0.0 */ export const reduceWithIndex: (b: B, f: (i: number, b: B, a: A) => B) => (fa: NonEmptyArray) => B = RNEA.reduceWithIndex /** * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: NonEmptyArray) => B = RNEA.reduceRight /** * @category folding * @since 2.0.0 */ export const reduceRightWithIndex: (b: B, f: (i: number, a: A, b: B) => B) => (fa: NonEmptyArray) => B = RNEA.reduceRightWithIndex /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT) => (as: NonEmptyArray) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (f) => traverseWithIndexF((_, a) => f(a)) } /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = ( F: ApplicativeHKT ): ((as: NonEmptyArray>) => HKT>) => traverseWithIndex(F)((_, a) => a) /** * @category sequencing * @since 2.6.3 */ export const traverseWithIndex: PipeableTraverseWithIndex1 = (F: ApplicativeHKT) => (f: (i: number, a: A) => HKT) => (as: NonEmptyArray): HKT> => { let out: HKT> = F.map(f(0, head(as)), of) for (let i = 1; i < as.length; i++) { out = F.ap( F.map(out, (bs) => (b: B) => pipe(bs, append(b))), f(i, as[i]) ) } return out } /** * @since 2.7.0 */ export const extract: Comonad1['extract'] = RNEA.head /** * @category type lambdas * @since 2.0.0 */ export const URI = 'NonEmptyArray' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: NonEmptyArray } } /** * @category instances * @since 2.0.0 */ export const getShow: (S: Show) => Show> = RNEA.getShow /** * Builds a `Semigroup` instance for `NonEmptyArray` * * @category instances * @since 2.0.0 */ export const getSemigroup = (): Semigroup> => ({ concat }) /** * @example * import { getEq } from 'fp-ts/NonEmptyArray' * import * as N from 'fp-ts/number' * * const E = getEq(N.Eq) * assert.strictEqual(E.equals([1, 2], [1, 2]), true) * assert.strictEqual(E.equals([1, 2], [1, 3]), false) * * @category instances * @since 2.0.0 */ export const getEq: (E: Eq) => Eq> = RNEA.getEq /** * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq): Semigroup> => { const unionE = union(E) return { concat: (first, second) => unionE(second)(first) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.7.0 */ export const FunctorWithIndex: FunctorWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.5.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.5.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category sequencing * @since 2.5.0 */ export const chainFirst: (f: (a: A) => NonEmptyArray) => (first: NonEmptyArray) => NonEmptyArray = /*#__PURE__*/ chainFirst_(Chain) /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const FoldableWithIndex: FoldableWithIndex1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.7.0 */ export const TraversableWithIndex: TraversableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverseWithIndex: _traverseWithIndex } /** * @category instances * @since 2.7.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad1 = { URI, map: _map, extend: _extend, extract } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: NonEmptyArray<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ bind_(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export const head: (nea: NonEmptyArray) => A = RNEA.head /** * @since 2.0.0 */ export const tail = (as: NonEmptyArray): Array => as.slice(1) /** * @since 2.0.0 */ export const last: (nea: NonEmptyArray) => A = RNEA.last /** * Get all but the last element of a non empty array, creating a new array. * * @example * import { init } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(init([1, 2, 3]), [1, 2]) * assert.deepStrictEqual(init([1]), []) * * @since 2.2.0 */ export const init = (as: NonEmptyArray): Array => as.slice(0, -1) /** * @since 2.0.0 */ export const min: (ord: Ord) => (nea: NonEmptyArray) => A = RNEA.min /** * @since 2.0.0 */ export const max: (ord: Ord) => (nea: NonEmptyArray) => A = RNEA.max /** * @since 2.10.0 */ export const concatAll = (S: Semigroup) => (as: NonEmptyArray): A => as.reduce(S.concat) /** * Break an `Array` into its first element and remaining elements. * * @category pattern matching * @since 2.11.0 */ export const matchLeft = (f: (head: A, tail: Array) => B) => (as: NonEmptyArray): B => f(head(as), tail(as)) /** * Break an `Array` into its initial elements and the last element. * * @category pattern matching * @since 2.11.0 */ export const matchRight = (f: (init: Array, last: A) => B) => (as: NonEmptyArray): B => f(init(as), last(as)) /** * Apply a function to the head, creating a new `NonEmptyArray`. * * @since 2.11.0 */ export const modifyHead = (f: Endomorphism) => (as: NonEmptyArray): NonEmptyArray => [f(head(as)), ...tail(as)] /** * Change the head, creating a new `NonEmptyArray`. * * @since 2.11.0 */ export const updateHead = (a: A): ((as: NonEmptyArray) => NonEmptyArray) => modifyHead(() => a) /** * Apply a function to the last element, creating a new `NonEmptyArray`. * * @since 2.11.0 */ export const modifyLast = (f: Endomorphism) => (as: NonEmptyArray): NonEmptyArray => pipe(init(as), append(f(last(as)))) /** * Change the last element, creating a new `NonEmptyArray`. * * @since 2.11.0 */ export const updateLast = (a: A): ((as: NonEmptyArray) => NonEmptyArray) => modifyLast(() => a) /** * Places an element in between members of a `NonEmptyArray`, then folds the results using the provided `Semigroup`. * * @example * import * as S from 'fp-ts/string' * import { intercalate } from 'fp-ts/NonEmptyArray' * * assert.deepStrictEqual(intercalate(S.Semigroup)('-')(['a', 'b', 'c']), 'a-b-c') * * @since 2.12.0 */ export const intercalate: (S: Semigroup) => (middle: A) => (as: NonEmptyArray) => A = RNEA.intercalate // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => NonEmptyArray) => (ma: NonEmptyArray) => NonEmptyArray = flatMap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This is just `sort` followed by `group`. * * @category zone of death * @since 2.0.0 * @deprecated */ export function groupSort(O: Ord): { (as: NonEmptyArray): NonEmptyArray> (as: Array): Array> } export function groupSort(O: Ord): (as: Array) => Array> { const sortO = sort(O) const groupO = group(O) return (as) => (isNonEmpty(as) ? groupO(sortO(as)) : []) } /** * Use [`filter`](./Array.ts.html#filter) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function filter(refinement: Refinement): (as: NonEmptyArray) => Option> export function filter(predicate: Predicate): (bs: NonEmptyArray) => Option> export function filter(predicate: Predicate): (as: NonEmptyArray) => Option> export function filter(predicate: Predicate): (as: NonEmptyArray) => Option> { return filterWithIndex((_, a) => predicate(a)) } /** * Use [`filterWithIndex`](./Array.ts.html#filterwithindex) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const filterWithIndex = (predicate: (i: number, a: A) => boolean) => (as: NonEmptyArray): Option> => fromArray(as.filter((a, i) => predicate(i, a))) /** * Use [`unprepend`](#unprepend) instead. * * @category zone of death * @since 2.9.0 * @deprecated */ export const uncons: (as: NonEmptyArray) => [A, Array] = unprepend /** * Use [`unappend`](#unappend) instead. * * @category zone of death * @since 2.9.0 * @deprecated */ export const unsnoc: (as: NonEmptyArray) => [Array, A] = unappend /** * Use [`prepend`](./Array.ts.html#prepend) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function cons(head: A): (tail: Array) => NonEmptyArray /** @deprecated */ export function cons(head: A, tail: Array): NonEmptyArray export function cons(head: A, tail?: Array): NonEmptyArray | ((tail: Array) => NonEmptyArray) { return tail === undefined ? prepend(head) : pipe(tail, prepend(head)) } /** * Use [`append`](./Array.ts.html#append) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const snoc = (init: Array, end: A): NonEmptyArray => pipe(init, append(end)) /** * Use [`prependAll`](#prependall) instead. * * @category zone of death * @since 2.9.0 * @deprecated */ export const prependToAll = prependAll /** * Use [`concatAll`](#concatall) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const fold: (S: Semigroup) => (fa: NonEmptyArray) => A = RNEA.concatAll /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `NEA.Functor` instead of `NEA.nonEmptyArray` * (where `NEA` is from `import NEA from 'fp-ts/NonEmptyArray'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const nonEmptyArray: Monad1 & Comonad1 & TraversableWithIndex1 & FunctorWithIndex1 & FoldableWithIndex1 & Alt1 = { URI, of, map: _map, mapWithIndex: _mapWithIndex, ap: _ap, chain: flatMap, extend: _extend, extract: extract, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverseWithIndex: _traverseWithIndex, alt: _alt } ================================================ FILE: src/Option.ts ================================================ /** * ```ts * type Option = None | Some * ``` * * `Option` is a container for an optional value of type `A`. If the value of type `A` is present, the `Option` is * an instance of `Some`, containing the present value of type `A`. If the value is absent, the `Option` is an * instance of `None`. * * An option could be looked at as a collection or foldable structure with either one or zero elements. * Another way to look at `Option` is: it represents the effect of a possibly failing computation. * * * @example * import * as O from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * const double = (n: number): number => n * 2 * * export const imperative = (as: ReadonlyArray): string => { * const head = (as: ReadonlyArray): number => { * if (as.length === 0) { * throw new Error() * } * return as[0] * } * const inverse = (n: number): number => { * if (n === 0) { * throw new Error() * } * return 1 / n * } * try { * return `Result is ${inverse(double(head(as)))}` * } catch (e) { * return 'no result' * } * } * * export const functional = (as: ReadonlyArray): string => { * const head = (as: ReadonlyArray): O.Option => * as.length === 0 ? O.none : O.some(as[0]) * const inverse = (n: number): O.Option => * n === 0 ? O.none : O.some(1 / n) * return pipe( * as, * head, * O.map(double), * O.flatMap(inverse), * O.match( * () => 'no result', // onNone handler * (head) => `Result is ${head}` // onSome handler * ) * ) * } * * assert.deepStrictEqual(imperative([1, 2, 3]), functional([1, 2, 3])) * assert.deepStrictEqual(imperative([]), functional([])) * assert.deepStrictEqual(imperative([0]), functional([0])) * * @since 2.0.0 */ import { Alt1 } from './Alt' import { Alternative1 } from './Alternative' import { Applicative as ApplicativeHKT, Applicative1, getApplicativeMonoid } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import * as chainable from './Chain' import { Compactable1 } from './Compactable' import { Either } from './Either' import { Eq } from './Eq' import { Extend1 } from './Extend' import { Filterable1 } from './Filterable' import { Foldable1 } from './Foldable' import { chainEitherK as chainEitherK_, FromEither1, fromEitherK as fromEitherK_, tapEither as tapEither_ } from './FromEither' import { constNull, constUndefined, dual, flow, identity, LazyArg, pipe } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { HKT } from './HKT' import * as _ from './internal' import { Monad1 } from './Monad' import { MonadThrow1 } from './MonadThrow' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Ord } from './Ord' import { Pointed1 } from './Pointed' import { not, Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { first, last, Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' import { PipeableWilt1, PipeableWither1, wiltDefault, Witherable1, witherDefault } from './Witherable' import { guard as guard_, Zero1 } from './Zero' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface None { readonly _tag: 'None' } /** * @category model * @since 2.0.0 */ export interface Some { readonly _tag: 'Some' readonly value: A } /** * @category model * @since 2.0.0 */ export type Option = None | Some // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value. * * @category constructors * @since 2.0.0 */ export const none: Option = _.none /** * Constructs a `Some`. Represents an optional value that exists. * * @category constructors * @since 2.0.0 */ export const some: (a: A) => Option = _.some /** * Returns a *smart constructor* based on the given predicate. * * @example * import { none, some, fromPredicate } from 'fp-ts/Option' * * const getOption = fromPredicate((n: number) => n >= 0) * * assert.deepStrictEqual(getOption(-1), none) * assert.deepStrictEqual(getOption(1), some(1)) * * @category lifting * @since 2.0.0 */ export function fromPredicate(refinement: Refinement): (a: A) => Option export function fromPredicate(predicate: Predicate): (b: B) => Option export function fromPredicate(predicate: Predicate): (a: A) => Option export function fromPredicate(predicate: Predicate): (a: A) => Option { return (a) => (predicate(a) ? some(a) : none) } /** * Returns the `Left` value of an `Either` if possible. * * @example * import { getLeft, none, some } from 'fp-ts/Option' * import { right, left } from 'fp-ts/Either' * * assert.deepStrictEqual(getLeft(right(1)), none) * assert.deepStrictEqual(getLeft(left('a')), some('a')) * * @category constructors * @since 2.0.0 */ export const getLeft = (ma: Either): Option => (ma._tag === 'Right' ? none : some(ma.left)) /** * Returns the `Right` value of an `Either` if possible. * * @example * import { getRight, none, some } from 'fp-ts/Option' * import { right, left } from 'fp-ts/Either' * * assert.deepStrictEqual(getRight(right(1)), some(1)) * assert.deepStrictEqual(getRight(left('a')), none) * * @category constructors * @since 2.0.0 */ export const getRight = (ma: Either): Option => (ma._tag === 'Left' ? none : some(ma.right)) const _map: Monad1['map'] = (fa, f) => pipe(fa, map(f)) const _ap: Monad1['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _reduce: Foldable1['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) const _foldMap: Foldable1['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } const _reduceRight: Foldable1['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) const _traverse: Traversable1['traverse'] = ( F: ApplicativeHKT ): ((ta: Option, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) const _filter: Filterable1['filter'] = (fa: Option, predicate: Predicate) => pipe(fa, filter(predicate)) /* istanbul ignore next */ const _filterMap: Filterable1['filterMap'] = (fa, f) => pipe(fa, filterMap(f)) /* istanbul ignore next */ const _extend: Extend1['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _partition: Filterable1['partition'] = (fa: Option, predicate: Predicate) => pipe(fa, partition(predicate)) /* istanbul ignore next */ const _partitionMap: Filterable1['partitionMap'] = (fa, f) => pipe(fa, partitionMap(f)) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Option' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Option } } /** * @category instances * @since 2.0.0 */ export const getShow = (S: Show): Show> => ({ show: (ma) => (isNone(ma) ? 'none' : `some(${S.show(ma.value)})`) }) /** * @example * import { none, some, getEq } from 'fp-ts/Option' * import * as N from 'fp-ts/number' * * const E = getEq(N.Eq) * assert.strictEqual(E.equals(none, none), true) * assert.strictEqual(E.equals(none, some(1)), false) * assert.strictEqual(E.equals(some(1), none), false) * assert.strictEqual(E.equals(some(1), some(2)), false) * assert.strictEqual(E.equals(some(1), some(1)), true) * * @category instances * @since 2.0.0 */ export const getEq = (E: Eq): Eq> => ({ equals: (x, y) => x === y || (isNone(x) ? isNone(y) : isNone(y) ? false : E.equals(x.value, y.value)) }) /** * The `Ord` instance allows `Option` values to be compared with * `compare`, whenever there is an `Ord` instance for * the type the `Option` contains. * * `None` is considered to be less than any `Some` value. * * * @example * import { none, some, getOrd } from 'fp-ts/Option' * import * as N from 'fp-ts/number' * * const O = getOrd(N.Ord) * assert.strictEqual(O.compare(none, none), 0) * assert.strictEqual(O.compare(none, some(1)), -1) * assert.strictEqual(O.compare(some(1), none), 1) * assert.strictEqual(O.compare(some(1), some(2)), -1) * assert.strictEqual(O.compare(some(1), some(1)), 0) * * @category instances * @since 2.0.0 */ export const getOrd = (O: Ord): Ord> => ({ equals: getEq(O).equals, compare: (x, y) => (x === y ? 0 : isSome(x) ? (isSome(y) ? O.compare(x.value, y.value) : 1) : isSome(y) ? -1 : 0) }) /** * Monoid returning the left-most non-`None` value. If both operands are `Some`s then the inner values are * concatenated using the provided `Semigroup` * * | x | y | concat(x, y) | * | ------- | ------- | ------------------ | * | none | none | none | * | some(a) | none | some(a) | * | none | some(b) | some(b) | * | some(a) | some(b) | some(concat(a, b)) | * * @example * import { getMonoid, some, none } from 'fp-ts/Option' * import { SemigroupSum } from 'fp-ts/number' * * const M = getMonoid(SemigroupSum) * assert.deepStrictEqual(M.concat(none, none), none) * assert.deepStrictEqual(M.concat(some(1), none), some(1)) * assert.deepStrictEqual(M.concat(none, some(1)), some(1)) * assert.deepStrictEqual(M.concat(some(1), some(2)), some(3)) * * @category instances * @since 2.0.0 */ export const getMonoid = (S: Semigroup): Monoid> => ({ concat: (x, y) => (isNone(x) ? y : isNone(y) ? x : some(S.concat(x.value, y.value))), empty: none }) /** * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Option) => Option = (f) => (fa) => isNone(fa) ? none : some(f(fa.value)) /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Maps the `Some` value of this `Option` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): <_>(self: Option<_>) => Option <_, A>(self: Option<_>, a: A): Option } = dual(2, as_(Functor)) /** * Maps the `Some` value of this `Option` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: <_>(self: Option<_>) => Option = asUnit_(Functor) /** * @category constructors * @since 2.7.0 */ export const of: (a: A) => Option = some /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @since 2.0.0 */ export const ap: (fa: Option) => (fab: Option<(a: A) => B>) => Option = (fa) => (fab) => isNone(fab) ? none : isNone(fa) ? none : some(fab.value(fa.value)) /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => Option): (ma: Option) => Option (ma: Option, f: (a: A) => Option): Option } = /*#__PURE__*/ dual(2, (ma: Option, f: (a: A) => Option): Option => (isNone(ma) ? none : f(ma.value))) /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: Option) => B = (b, f) => (fa) => isNone(fa) ? b : f(b, fa.value) /** * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Option) => M = (M) => (f) => (fa) => isNone(fa) ? M.empty : f(fa.value) /** * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Option) => B = (b, f) => (fa) => isNone(fa) ? b : f(fa.value, b) /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * Returns the provided `Option` `that` if `self` is `None`, otherwise returns `self`. * * @param self - The first `Option` to be checked. * @param that - The `Option` to return if `self` is `None`. * * @example * import * as O from "fp-ts/Option" * * assert.deepStrictEqual(O.orElse(O.none, () => O.none), O.none) * assert.deepStrictEqual(O.orElse(O.some(1), () => O.none), O.some(1)) * assert.deepStrictEqual(O.orElse(O.none, () => O.some('b')), O.some('b')) * assert.deepStrictEqual(O.orElse(O.some(1), () => O.some('b')), O.some(1)) * * @category error handling * @since 2.16.0 */ export const orElse: { (that: LazyArg>): (self: Option) => Option (self: Option, that: LazyArg>): Option } = dual(2, (self: Option, that: LazyArg>): Option => (isNone(self) ? that() : self)) /** * Alias of `orElse`. * * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category legacy * @since 2.9.0 */ export const altW: (that: LazyArg>) => (fa: Option) => Option = orElse /** * Alias of `orElse`. * * @category legacy * @since 2.0.0 */ export const alt: (that: LazyArg>) => (fa: Option) => Option = orElse /** * @category instances * @since 2.7.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @since 2.7.0 */ export const zero: () => Option = () => none /** * @category instances * @since 2.11.0 */ export const Zero: Zero1 = { URI, zero } /** * @category do notation * @since 2.11.0 */ export const guard = /*#__PURE__*/ guard_(Zero, Pointed) /** * @category instances * @since 2.7.0 */ export const Alternative: Alternative1 = { URI, map: _map, ap: _ap, of, alt: _alt, zero } /** * @since 2.0.0 */ export const extend: (f: (wa: Option) => B) => (wa: Option) => Option = (f) => (wa) => isNone(wa) ? none : some(f(wa)) /** * @category instances * @since 2.7.0 */ export const Extend: Extend1 = { URI, map: _map, extend: _extend } /** * @category filtering * @since 2.0.0 */ export const compact: (fa: Option>) => Option = /*#__PURE__*/ flatMap(identity) const defaultSeparated = /*#__PURE__*/ separated(none, none) /** * @category filtering * @since 2.0.0 */ export const separate: (ma: Option>) => Separated, Option> = (ma) => isNone(ma) ? defaultSeparated : separated(getLeft(ma.value), getRight(ma.value)) /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category filtering * @since 2.0.0 */ export const filter: { (refinement: Refinement): (fa: Option) => Option (predicate: Predicate): (fb: Option) => Option (predicate: Predicate): (fa: Option) => Option } = (predicate: Predicate) => (fa: Option) => isNone(fa) ? none : predicate(fa.value) ? fa : none /** * @category filtering * @since 2.0.0 */ export const filterMap: (f: (a: A) => Option) => (fa: Option) => Option = (f) => (fa) => isNone(fa) ? none : f(fa.value) /** * @category filtering * @since 2.0.0 */ export const partition: { (refinement: Refinement): (fa: Option) => Separated, Option> (predicate: Predicate): (fb: Option) => Separated, Option> (predicate: Predicate): (fa: Option) => Separated, Option> } = (predicate: Predicate) => (fa: Option) => separated(_filter(fa, not(predicate)), _filter(fa, predicate)) /** * @category filtering * @since 2.0.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: Option) => Separated, Option> = (f) => flow(map(f), separate) /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = (F: ApplicativeHKT) => (f: (a: A) => HKT) => (ta: Option): HKT> => isNone(ta) ? F.of(none) : F.map(f(ta.value), some) /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = (F: ApplicativeHKT) => (ta: Option>): HKT> => isNone(ta) ? F.of(none) : F.map(ta.value, some) /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } const _wither: Witherable1['wither'] = /*#__PURE__*/ witherDefault(Traversable, Compactable) const _wilt: Witherable1['wilt'] = /*#__PURE__*/ wiltDefault(Traversable, Compactable) /** * @category filtering * @since 2.6.5 */ export const wither: PipeableWither1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT>) => (fa: Option) => HKT>) => { const _witherF = _wither(F) return (f) => (fa) => _witherF(fa, f) } /** * @category filtering * @since 2.6.5 */ export const wilt: PipeableWilt1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT>) => (fa: Option) => HKT, Option>>) => { const _wiltF = _wilt(F) return (f) => (fa) => _wiltF(fa, f) } /** * @category instances * @since 2.7.0 */ export const Witherable: Witherable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, wither: _wither, wilt: _wilt } /** * @since 2.7.0 */ export const throwError: MonadThrow1['throwError'] = () => none /** * @category instances * @since 2.7.0 */ export const MonadThrow: MonadThrow1 = { URI, map: _map, ap: _ap, of, chain: flatMap, throwError } /** * Transforms an `Either` to an `Option` discarding the error. * * Alias of [getRight](#getright) * * @category conversions * @since 2.0.0 */ export const fromEither: (fa: Either) => Option = getRight /** * @category instances * @since 2.11.0 */ export const FromEither: FromEither1 = { URI, fromEither } // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * Returns `true` if the option is an instance of `Some`, `false` otherwise. * * @example * import { some, none, isSome } from 'fp-ts/Option' * * assert.strictEqual(isSome(some(1)), true) * assert.strictEqual(isSome(none), false) * * @category refinements * @since 2.0.0 */ export const isSome: (fa: Option) => fa is Some = _.isSome /** * Returns `true` if the option is `None`, `false` otherwise. * * @example * import { some, none, isNone } from 'fp-ts/Option' * * assert.strictEqual(isNone(some(1)), false) * assert.strictEqual(isNone(none), true) * * @category refinements * @since 2.0.0 */ export const isNone = (fa: Option): fa is None => fa._tag === 'None' /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW = (onNone: LazyArg, onSome: (a: A) => C) => (ma: Option): B | C => isNone(ma) ? onNone() : onSome(ma.value) /** * Alias of [`matchW`](#matchw). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchW /** * Takes a (lazy) default value, a function, and an `Option` value, if the `Option` value is `None` the default value is * returned, otherwise the function is applied to the value inside the `Some` and the result is returned. * * @example * import { some, none, match } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.strictEqual( * pipe( * some(1), * match(() => 'a none', a => `a some containing ${a}`) * ), * 'a some containing 1' * ) * * assert.strictEqual( * pipe( * none, * match(() => 'a none', a => `a some containing ${a}`) * ), * 'a none' * ) * * @category pattern matching * @since 2.10.0 */ export const match: (onNone: LazyArg, onSome: (a: A) => B) => (ma: Option) => B = matchW /** * Alias of [`match`](#match). * * @category pattern matching * @since 2.0.0 */ export const fold = match /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.6.0 */ export const getOrElseW = (onNone: LazyArg) => (ma: Option): A | B => isNone(ma) ? onNone() : ma.value /** * Extracts the value out of the structure, if it exists. Otherwise returns the given default value * * @example * import { some, none, getOrElse } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.strictEqual( * pipe( * some(1), * getOrElse(() => 0) * ), * 1 * ) * assert.strictEqual( * pipe( * none, * getOrElse(() => 0) * ), * 0 * ) * * @category error handling * @since 2.0.0 */ export const getOrElse: (onNone: LazyArg) => (ma: Option) => A = getOrElseW /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: Option>) => Option = compact /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: Option, f: (a: A) => Option<_>): Option (f: (a: A) => Option<_>): (self: Option) => Option } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as O from 'fp-ts/Option' * import * as E from 'fp-ts/Either' * * const compute = (value: number) => pipe( * O.of(value), * O.tapEither((value) => value > 0 ? E.right('ok') : E.left('error')), * ) * * assert.deepStrictEqual(compute(1), O.of(1)) * assert.deepStrictEqual(compute(-42), O.none) * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: Option) => Option (self: Option, f: (a: A) => Either): Option } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * @since 2.0.0 */ export const duplicate: (ma: Option) => Option> = /*#__PURE__*/ extend(identity) /** * @category lifting * @since 2.11.0 */ export const fromEitherK: , B>( f: (...a: A) => Either ) => (...a: A) => Option = /*#__PURE__*/ fromEitherK_(FromEither) /** * @category sequencing * @since 2.11.0 */ export const chainEitherK: (f: (a: A) => Either) => (ma: Option) => Option = /*#__PURE__*/ chainEitherK_(FromEither, Chain) /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: (f: (a: A) => Either) => (ma: Option) => Option = tapEither /** * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise * returns the value wrapped in a `Some`. * * @example * import { none, some, fromNullable } from 'fp-ts/Option' * * assert.deepStrictEqual(fromNullable(undefined), none) * assert.deepStrictEqual(fromNullable(null), none) * assert.deepStrictEqual(fromNullable(1), some(1)) * * @category conversions * @since 2.0.0 */ export const fromNullable = (a: A): Option> => (a == null ? none : some(a as NonNullable)) /** * Transforms an exception into an `Option`. If `f` throws, returns `None`, otherwise returns the output wrapped in a * `Some`. * * See also [`tryCatchK`](#trycatchk). * * @example * import { none, some, tryCatch } from 'fp-ts/Option' * * assert.deepStrictEqual( * tryCatch(() => { * throw new Error() * }), * none * ) * assert.deepStrictEqual(tryCatch(() => 1), some(1)) * * @category interop * @since 2.0.0 */ export const tryCatch = (f: LazyArg): Option => { try { return some(f()) } catch (e) { return none } } /** * Converts a function that may throw to one returning a `Option`. * * @category interop * @since 2.10.0 */ export const tryCatchK = , B>(f: (...a: A) => B): ((...a: A) => Option) => (...a) => tryCatch(() => f(...a)) /** * Returns a *smart constructor* from a function that returns a nullable value. * * @example * import { fromNullableK, none, some } from 'fp-ts/Option' * * const f = (s: string): number | undefined => { * const n = parseFloat(s) * return isNaN(n) ? undefined : n * } * * const g = fromNullableK(f) * * assert.deepStrictEqual(g('1'), some(1)) * assert.deepStrictEqual(g('a'), none) * * @category lifting * @since 2.9.0 */ export const fromNullableK: , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Option> = (f) => flow(f, fromNullable) /** * This is `chain` + `fromNullable`, useful when working with optional values. * * @example * import { some, none, fromNullable, chainNullableK } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * interface Employee { * readonly company?: { * readonly address?: { * readonly street?: { * readonly name?: string * } * } * } * } * * const employee1: Employee = { company: { address: { street: { name: 'high street' } } } } * * assert.deepStrictEqual( * pipe( * fromNullable(employee1.company), * chainNullableK(company => company.address), * chainNullableK(address => address.street), * chainNullableK(street => street.name) * ), * some('high street') * ) * * const employee2: Employee = { company: { address: { street: {} } } } * * assert.deepStrictEqual( * pipe( * fromNullable(employee2.company), * chainNullableK(company => company.address), * chainNullableK(address => address.street), * chainNullableK(street => street.name) * ), * none * ) * * @category sequencing * @since 2.9.0 */ export const chainNullableK = (f: (a: A) => B | null | undefined) => (ma: Option): Option> => isNone(ma) ? none : fromNullable(f(ma.value)) /** * Extracts the value out of the structure, if it exists. Otherwise returns `null`. * * @example * import { some, none, toNullable } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.strictEqual( * pipe( * some(1), * toNullable * ), * 1 * ) * assert.strictEqual( * pipe( * none, * toNullable * ), * null * ) * * @category conversions * @since 2.0.0 */ export const toNullable: (ma: Option) => A | null = /*#__PURE__*/ match(constNull, identity) /** * Extracts the value out of the structure, if it exists. Otherwise returns `undefined`. * * @example * import { some, none, toUndefined } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.strictEqual( * pipe( * some(1), * toUndefined * ), * 1 * ) * assert.strictEqual( * pipe( * none, * toUndefined * ), * undefined * ) * * @category conversions * @since 2.0.0 */ export const toUndefined: (ma: Option) => A | undefined = /*#__PURE__*/ match(constUndefined, identity) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Returns `true` if `ma` contains `a` * * @example * import { some, none, elem } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * import * as N from 'fp-ts/number' * * assert.strictEqual(pipe(some(1), elem(N.Eq)(1)), true) * assert.strictEqual(pipe(some(1), elem(N.Eq)(2)), false) * assert.strictEqual(pipe(none, elem(N.Eq)(1)), false) * * @since 2.0.0 */ export function elem(E: Eq): { (a: A): (ma: Option) => boolean (a: A, ma: Option): boolean } export function elem(E: Eq): (a: A, ma?: Option) => boolean | ((ma: Option) => boolean) { return (a, ma?) => { if (ma === undefined) { const elemE = elem(E) return (ma) => elemE(a, ma) } return isNone(ma) ? false : E.equals(a, ma.value) } } /** * Returns `true` if the predicate is satisfied by the wrapped value * * @example * import { some, none, exists } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.strictEqual( * pipe( * some(1), * exists(n => n > 0) * ), * true * ) * assert.strictEqual( * pipe( * some(1), * exists(n => n > 1) * ), * false * ) * assert.strictEqual( * pipe( * none, * exists(n => n > 0) * ), * false * ) * * @since 2.0.0 */ export const exists = (predicate: Predicate) => (ma: Option): boolean => isNone(ma) ? false : predicate(ma.value) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: Option<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * @since 2.11.0 */ export const ApT: Option = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => Option) => (as: ReadonlyNonEmptyArray): Option> => { const o = f(0, _.head(as)) if (isNone(o)) { return none } const out: NonEmptyArray = [o.value] for (let i = 1; i < as.length; i++) { const o = f(i, as[i]) if (isNone(o)) { return none } out.push(o.value) } return some(out) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => Option ): ((as: ReadonlyArray) => Option>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => Option ) => (as: ReadonlyArray) => Option> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = (f: (a: A) => Option): ((as: ReadonlyArray) => Option>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => Option> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Option) => (ma: Option) => Option = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => Option) => (first: Option) => Option = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `Refinement` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getRefinement(getOption: (a: A) => Option): Refinement { return (a: A): a is B => isSome(getOption(a)) } /** * Use [`chainNullableK`](#chainnullablek) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const mapNullable = chainNullableK /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `O.Functor` instead of `O.option` * (where `O` is from `import O from 'fp-ts/Option'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const option: Monad1 & Foldable1 & Alternative1 & Extend1 & Witherable1 & MonadThrow1 = { URI, map: _map, of, ap: _ap, chain: flatMap, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, zero, alt: _alt, extend: _extend, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, wither: _wither, wilt: _wilt, throwError } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplySemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(Apply) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplyMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(Applicative) /** * Use * * ```ts * import { first } from 'fp-ts/Semigroup' * import { getMonoid } from 'fp-ts/Option' * * getMonoid(first()) * ``` * * instead. * * Monoid returning the left-most non-`None` value * * | x | y | concat(x, y) | * | ------- | ------- | ------------ | * | none | none | none | * | some(a) | none | some(a) | * | none | some(b) | some(b) | * | some(a) | some(b) | some(a) | * * @example * import { getFirstMonoid, some, none } from 'fp-ts/Option' * * const M = getFirstMonoid() * assert.deepStrictEqual(M.concat(none, none), none) * assert.deepStrictEqual(M.concat(some(1), none), some(1)) * assert.deepStrictEqual(M.concat(none, some(2)), some(2)) * assert.deepStrictEqual(M.concat(some(1), some(2)), some(1)) * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFirstMonoid = (): Monoid> => getMonoid(first()) /** * Use * * ```ts * import { last } from 'fp-ts/Semigroup' * import { getMonoid } from 'fp-ts/Option' * * getMonoid(last()) * ``` * * instead. * * Monoid returning the right-most non-`None` value * * | x | y | concat(x, y) | * | ------- | ------- | ------------ | * | none | none | none | * | some(a) | none | some(a) | * | none | some(b) | some(b) | * | some(a) | some(b) | some(b) | * * @example * import { getLastMonoid, some, none } from 'fp-ts/Option' * * const M = getLastMonoid() * assert.deepStrictEqual(M.concat(none, none), none) * assert.deepStrictEqual(M.concat(some(1), none), some(1)) * assert.deepStrictEqual(M.concat(none, some(2)), some(2)) * assert.deepStrictEqual(M.concat(some(1), some(2)), some(2)) * * @category zone of death * @since 2.0.0 * @deprecated */ export const getLastMonoid = (): Monoid> => getMonoid(last()) ================================================ FILE: src/OptionT.ts ================================================ /** * @since 2.0.0 */ import { ApplicativeComposition2C1, ApplicativeComposition11, ApplicativeComposition21, ApplicativeCompositionHKT1 } from './Applicative' import { ap as ap_, Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C, Apply4 } from './Apply' import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4 } from './Chain' import { Either } from './Either' import { constant, flow, LazyArg, pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4, map as map_ } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C, Monad4 } from './Monad' import * as O from './Option' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C, Pointed4 } from './Pointed' import { Predicate } from './Predicate' import { Refinement } from './Refinement' import Option = O.Option // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export function some(F: Pointed4): (a: A) => Kind4> export function some(F: Pointed3): (a: A) => Kind3> export function some(F: Pointed3C): (a: A) => Kind3> export function some(F: Pointed2): (a: A) => Kind2> export function some(F: Pointed2C): (a: A) => Kind2> export function some(F: Pointed1): (a: A) => Kind> export function some(F: Pointed): (a: A) => HKT> export function some(F: Pointed): (a: A) => HKT> { return flow(O.some, F.of) } /** * @since 2.10.0 */ export function zero(F: Pointed4): () => Kind4> export function zero(F: Pointed3): () => Kind3> export function zero(F: Pointed3C): () => Kind3> export function zero(F: Pointed2): () => Kind2> export function zero(F: Pointed2C): () => Kind2> export function zero(F: Pointed1): () => Kind> export function zero(F: Pointed): () => HKT> export function zero(F: Pointed): () => HKT> { return constant(F.of(O.none)) } /** * @since 2.10.0 */ export function fromF( F: Functor4 ): (ma: Kind4) => Kind4> export function fromF(F: Functor3): (ma: Kind3) => Kind3> export function fromF( F: Functor3C ): (ma: Kind3) => Kind3> export function fromF(F: Functor2): (ma: Kind2) => Kind2> export function fromF(F: Functor2C): (ma: Kind2) => Kind2> export function fromF(F: Functor1): (ma: Kind) => Kind> export function fromF(F: Functor): (ma: HKT) => HKT> export function fromF(F: Functor): (ma: HKT) => HKT> { return (ma) => F.map(ma, O.some) } /** * @since 2.10.0 */ export function fromNullable( F: Pointed4 ): (a: A) => Kind4>> export function fromNullable(F: Pointed3): (a: A) => Kind3>> export function fromNullable( F: Pointed3C ): (a: A) => Kind3>> export function fromNullable(F: Pointed2): (a: A) => Kind2>> export function fromNullable(F: Pointed2C): (a: A) => Kind2>> export function fromNullable(F: Pointed1): (a: A) => Kind>> export function fromNullable(F: Pointed): (a: A) => HKT>> export function fromNullable(F: Pointed): (a: A) => HKT>> { return flow(O.fromNullable, F.of) } /** * @since 2.10.0 */ export function fromNullableK( F: Pointed4 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind4>> export function fromNullableK( F: Pointed3 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export function fromNullableK( F: Pointed3C ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind3>> export function fromNullableK( F: Pointed2 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export function fromNullableK( F: Pointed2C ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind2>> export function fromNullableK( F: Pointed1 ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => Kind>> export function fromNullableK( F: Pointed ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => HKT>> export function fromNullableK( F: Pointed ): , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => HKT>> { const fromNullableF = fromNullable(F) return (f) => flow(f, fromNullableF) } /** * @since 2.10.0 */ export function chainNullableK( M: Monad4 ): ( f: (a: A) => B | null | undefined ) => (ma: Kind4>) => Kind4>> export function chainNullableK( M: Monad3 ): ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export function chainNullableK( M: Monad3C ): ( f: (a: A) => B | null | undefined ) => (ma: Kind3>) => Kind3>> export function chainNullableK( M: Monad2 ): (f: (a: A) => B | null | undefined) => (ma: Kind2>) => Kind2>> export function chainNullableK( M: Monad2C ): (f: (a: A) => B | null | undefined) => (ma: Kind2>) => Kind2>> export function chainNullableK( M: Monad1 ): (f: (a: A) => B | null | undefined) => (ma: Kind>) => Kind>> export function chainNullableK( M: Monad ): (f: (a: A) => B | null | undefined) => (ma: HKT>) => HKT>> export function chainNullableK( M: Monad ): (f: (a: A) => B | null | undefined) => (ma: HKT>) => HKT>> { const chainM = chain(M) const fromNullableKM = fromNullableK(M) return (f) => chainM(fromNullableKM(f)) } /** * @since 2.10.0 */ export function fromOptionK( F: Pointed4 ): , B>( f: (...a: A) => Option ) => (...a: A) => Kind4> export function fromOptionK( F: Pointed3 ): , B>(f: (...a: A) => Option) => (...a: A) => Kind3> export function fromOptionK( F: Pointed3C ): , B>(f: (...a: A) => Option) => (...a: A) => Kind3> export function fromOptionK( F: Pointed2 ): , B>(f: (...a: A) => Option) => (...a: A) => Kind2> export function fromOptionK( F: Pointed2C ): , B>(f: (...a: A) => Option) => (...a: A) => Kind2> export function fromOptionK( F: Pointed1 ): , B>(f: (...a: A) => Option) => (...a: A) => Kind> export function fromOptionK( F: Pointed ): , B>(f: (...a: A) => Option) => (...a: A) => HKT> export function fromOptionK( F: Pointed ): , B>(f: (...a: A) => Option) => (...a: A) => HKT> { return (f) => flow(f, F.of) } /** * @since 2.10.0 */ export function chainOptionK( M: Monad4 ): (f: (a: A) => Option) => (ma: Kind4>) => Kind4> export function chainOptionK( M: Monad3 ): (f: (a: A) => Option) => (ma: Kind3>) => Kind3> export function chainOptionK( M: Monad3C ): (f: (a: A) => Option) => (ma: Kind3>) => Kind3> export function chainOptionK( M: Monad2 ): (f: (a: A) => Option) => (ma: Kind2>) => Kind2> export function chainOptionK( M: Monad2C ): (f: (a: A) => Option) => (ma: Kind2>) => Kind2> export function chainOptionK( M: Monad1 ): (f: (a: A) => Option) => (ma: Kind>) => Kind> export function chainOptionK( M: Monad ): (f: (a: A) => Option) => (ma: HKT>) => HKT> export function chainOptionK( M: Monad ): (f: (a: A) => Option) => (ma: HKT>) => HKT> { const chainM = chain(M) const fromOptionKM = fromOptionK(M) return (f) => chainM(fromOptionKM(f)) } /** * @category lifting * @since 2.10.0 */ export function fromPredicate( F: Pointed4 ): { (refinement: Refinement): (a: A) => Kind4> (predicate: Predicate): (b: B) => Kind4> (predicate: Predicate): (a: A) => Kind4> } export function fromPredicate( F: Pointed3 ): { (refinement: Refinement): (a: A) => Kind3> (predicate: Predicate): (b: B) => Kind3> (predicate: Predicate): (a: A) => Kind3> } export function fromPredicate( F: Pointed3C ): { (refinement: Refinement): (a: A) => Kind3> (predicate: Predicate): (b: B) => Kind3> (predicate: Predicate): (a: A) => Kind3> } export function fromPredicate( F: Pointed2 ): { (refinement: Refinement): (a: A) => Kind2> (predicate: Predicate): (b: B) => Kind2> (predicate: Predicate): (a: A) => Kind2> } export function fromPredicate( F: Pointed2C ): { (refinement: Refinement): (a: A) => Kind2> (predicate: Predicate): (b: B) => Kind2> (predicate: Predicate): (a: A) => Kind2> } export function fromPredicate( F: Pointed1 ): { (refinement: Refinement): (a: A) => Kind> (predicate: Predicate): (b: B) => Kind> (predicate: Predicate): (a: A) => Kind> } export function fromPredicate(F: Pointed): { (refinement: Refinement): (a: A) => HKT> (predicate: Predicate): (b: B) => HKT> (predicate: Predicate): (a: A) => HKT> } export function fromPredicate(F: Pointed): { (refinement: Refinement): (a: A) => HKT> (predicate: Predicate): (b: B) => HKT> (predicate: Predicate): (a: A) => HKT> } { return (predicate: Predicate) => (a: A) => F.of(O.fromPredicate(predicate)(a)) } /** * @since 2.10.0 */ export function fromEither( F: Pointed4 ): (e: Either) => Kind4> export function fromEither( F: Pointed3 ): (e: Either) => Kind3> export function fromEither( F: Pointed3C ): (e: Either) => Kind3> export function fromEither(F: Pointed2): (e: Either) => Kind2> export function fromEither(F: Pointed2C): (e: Either) => Kind2> export function fromEither(F: Pointed2C): (e: Either) => Kind2> export function fromEither(F: Pointed1): (e: Either) => Kind> export function fromEither(F: Pointed): (e: Either) => HKT> export function fromEither(F: Pointed): (e: Either) => HKT> { return flow(O.fromEither, F.of) } /** * @category pattern matching * @since 2.10.0 */ export function match( F: Functor4 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind4>) => Kind4 export function match( F: Functor3 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind3>) => Kind3 export function match( F: Functor3C ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind3>) => Kind3 export function match( F: Functor2 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind2>) => Kind2 export function match( F: Functor2C ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind2>) => Kind2 export function match( F: Functor1 ): (onNone: () => B, onSome: (a: A) => B) => (ma: Kind>) => Kind export function match( F: Functor ): (onNone: () => B, onSome: (a: A) => B) => (ma: HKT>) => HKT export function match( F: Functor ): (onNone: () => B, onSome: (a: A) => B) => (ma: HKT>) => HKT { return (onNone, onSome) => (ma) => F.map(ma, O.match(onNone, onSome)) } /** * @since 2.10.0 */ export function matchE( M: Chain4 ): ( onNone: () => Kind4, onSome: (a: A) => Kind4 ) => (ma: Kind4>) => Kind4 export function matchE( M: Chain3 ): ( onNone: () => Kind3, onSome: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export function matchE( M: Chain3C ): ( onNone: () => Kind3, onSome: (a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export function matchE( M: Chain2 ): ( onNone: () => Kind2, onSome: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export function matchE( M: Chain2C ): ( onNone: () => Kind2, onSome: (a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export function matchE( M: Chain1 ): (onNone: () => Kind, onSome: (a: A) => Kind) => (ma: Kind>) => Kind export function matchE( M: Chain ): (onNone: () => HKT, onSome: (a: A) => HKT) => (ma: HKT>) => HKT export function matchE( M: Chain ): (onNone: () => HKT, onSome: (a: A) => HKT) => (ma: HKT>) => HKT { return (onNone, onSome) => (ma) => M.chain(ma, O.match(onNone, onSome)) } /** * @since 2.10.0 */ export function getOrElse( M: Monad4 ): (onNone: LazyArg>) => (fa: Kind4>) => Kind4 export function getOrElse( M: Monad3 ): (onNone: LazyArg>) => (fa: Kind3>) => Kind3 export function getOrElse( M: Monad3C ): (onNone: LazyArg>) => (fa: Kind3>) => Kind3 export function getOrElse( M: Monad2 ): (onNone: LazyArg>) => (fa: Kind2>) => Kind2 export function getOrElse( M: Monad2C ): (onNone: LazyArg>) => (fa: Kind2>) => Kind2 export function getOrElse( M: Monad1 ): (onNone: LazyArg>) => (fa: Kind>) => Kind export function getOrElse(M: Monad): (onNone: LazyArg>) => (fa: HKT>) => HKT export function getOrElse(M: Monad): (onNone: LazyArg>) => (fa: HKT>) => HKT { return (onNone) => (fa) => M.chain(fa, O.match(onNone, M.of)) } /** * @since 2.10.0 */ export function map( F: Functor4 ): (f: (a: A) => B) => (fa: Kind4>) => Kind4> export function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> export function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> { return map_(F, O.Functor) } /** * @since 2.10.0 */ export function ap( F: Apply4 ): ( fa: Kind4> ) => (fab: Kind4 B>>) => Kind4> export function ap( F: Apply3 ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C ): (fa: Kind3>) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply2 ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply1 ): (fa: Kind>) => (fab: Kind B>>) => Kind> export function ap( F: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply ): (fa: HKT>) => (fab: HKT B>>) => HKT> { return ap_(F, O.Apply) } /** * @since 2.10.0 */ export function chain( M: Monad4 ): ( f: (a: A) => Kind4> ) => (ma: Kind4>) => Kind4> export function chain( M: Monad3 ): (f: (a: A) => Kind3>) => (ma: Kind3>) => Kind3> export function chain( M: Monad3C ): (f: (a: A) => Kind3>) => (ma: Kind3>) => Kind3> export function chain( M: Monad2 ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export function chain( M: Monad2C ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export function chain( M: Monad1 ): (f: (a: A) => Kind>) => (ma: Kind>) => Kind> export function chain( M: Monad ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> export function chain( M: Monad ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> { const flatMapM = flatMap(M) return (f) => (ma) => flatMapM(ma, f) } /** @internal */ export function flatMap( M: Monad1 ): (ma: Kind>, f: (a: A) => Kind>) => Kind> /** @internal */ export function flatMap( M: Monad ): (ma: HKT>, f: (a: A) => HKT>) => HKT> /** @internal */ export function flatMap( M: Monad ): (ma: HKT>, f: (a: A) => HKT>) => HKT> { const zeroM = zero(M) return (ma, f) => M.chain( ma, O.match(() => zeroM(), f) ) } /** * @since 2.10.0 */ export function alt( M: Monad4 ): ( second: LazyArg>> ) => (first: Kind4>) => Kind4> export function alt( M: Monad3 ): ( second: LazyArg>> ) => (first: Kind3>) => Kind3> export function alt( M: Monad3C ): (second: LazyArg>>) => (first: Kind3>) => Kind3> export function alt( M: Monad2 ): (second: LazyArg>>) => (first: Kind2>) => Kind2> export function alt( M: Monad2C ): (second: LazyArg>>) => (first: Kind2>) => Kind2> export function alt( M: Monad1 ): (second: LazyArg>>) => (first: Kind>) => Kind> export function alt( M: Monad ): (second: LazyArg>>) => (first: HKT>) => HKT> export function alt( M: Monad ): (second: LazyArg>>) => (first: HKT>) => HKT> { const _some = some(M) return (second) => (first) => M.chain(first, O.match(second, _some)) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface OptionT extends HKT> {} /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface OptionM extends ApplicativeCompositionHKT1 { readonly chain: (ma: OptionT, f: (a: A) => OptionT) => OptionT readonly alt: (fa: OptionT, that: LazyArg>) => OptionT readonly fold: (ma: OptionT, onNone: LazyArg>, onSome: (a: A) => HKT) => HKT readonly getOrElse: (ma: OptionT, onNone: LazyArg>) => HKT readonly fromM: (ma: HKT) => OptionT readonly none: () => OptionT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export type OptionT1 = Kind> /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface OptionM1 extends ApplicativeComposition11 { readonly chain: (ma: OptionT1, f: (a: A) => OptionT1) => OptionT1 readonly alt: (fa: OptionT1, that: LazyArg>) => OptionT1 readonly fold: (ma: OptionT1, onNone: LazyArg>, onSome: (a: A) => Kind) => Kind readonly getOrElse: (ma: OptionT1, onNone: LazyArg>) => Kind readonly fromM: (ma: Kind) => OptionT1 readonly none: () => OptionT1 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export type OptionT2 = Kind2> /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface OptionM2 extends ApplicativeComposition21 { readonly chain: (ma: OptionT2, f: (a: A) => OptionT2) => OptionT2 readonly alt: (fa: OptionT2, that: LazyArg>) => OptionT2 readonly fold: ( ma: OptionT2, onNone: LazyArg>, onSome: (a: A) => Kind2 ) => Kind2 readonly getOrElse: (ma: OptionT2, onNone: LazyArg>) => Kind2 readonly fromM: (ma: Kind2) => OptionT2 readonly none: () => OptionT2 } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface OptionM2C extends ApplicativeComposition2C1 { readonly chain: (ma: OptionT2, f: (a: A) => OptionT2) => OptionT2 readonly alt: (fa: OptionT2, that: LazyArg>) => OptionT2 readonly fold: ( ma: OptionT2, onNone: LazyArg>, onSome: (a: A) => Kind2 ) => Kind2 readonly getOrElse: (ma: OptionT2, onNone: LazyArg>) => Kind2 readonly fromM: (ma: Kind2) => OptionT2 readonly none: () => OptionT2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export function getOptionM(M: Monad2): OptionM2 /** @deprecated */ export function getOptionM(M: Monad2C): OptionM2C /** @deprecated */ export function getOptionM(M: Monad1): OptionM1 /** @deprecated */ export function getOptionM(M: Monad): OptionM /** @deprecated */ export function getOptionM(M: Monad): OptionM { const apM = ap(M) const mapM = map(M) const chainM = chain(M) const altM = alt(M) const foldM = matchE(M) const getOrElseM = getOrElse(M) const zeroM = zero(M) return { map: (fa, f) => pipe(fa, mapM(f)), ap: (fab, fa) => pipe(fab, apM(fa)), of: some(M), chain: (ma, f) => pipe(ma, chainM(f)), alt: (fa, that) => pipe(fa, altM(that)), fold: (fa, onNone, onSome) => pipe(fa, foldM(onNone, onSome)), getOrElse: (fa, onNone) => pipe(fa, getOrElseM(onNone)), fromM: fromF(M), none: () => zeroM() } } ================================================ FILE: src/Ord.ts ================================================ /** * The `Ord` type class represents types which support comparisons with a _total order_. * * Instances should satisfy the laws of total orderings: * * 1. Reflexivity: `S.compare(a, a) <= 0` * 2. Antisymmetry: if `S.compare(a, b) <= 0` and `S.compare(b, a) <= 0` then `a <-> b` * 3. Transitivity: if `S.compare(a, b) <= 0` and `S.compare(b, c) <= 0` then `S.compare(a, c) <= 0` * * @since 2.0.0 */ import { Contravariant1 } from './Contravariant' import { Eq, eqStrict } from './Eq' import { constant, constTrue, pipe } from './function' import { Monoid } from './Monoid' import { Ordering } from './Ordering' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Ord extends Eq { readonly compare: (first: A, second: A) => Ordering } // ------------------------------------------------------------------------------------- // defaults // ------------------------------------------------------------------------------------- /** * @category defaults * @since 2.10.0 */ export const equalsDefault = (compare: Ord['compare']): Eq['equals'] => (first, second) => first === second || compare(first, second) === 0 // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export const fromCompare = (compare: Ord['compare']): Ord => ({ equals: equalsDefault(compare), compare: (first, second) => (first === second ? 0 : compare(first, second)) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Given a tuple of `Ord`s returns an `Ord` for the tuple. * * @example * import { tuple } from 'fp-ts/Ord' * import * as B from 'fp-ts/boolean' * import * as S from 'fp-ts/string' * import * as N from 'fp-ts/number' * * const O = tuple(S.Ord, N.Ord, B.Ord) * assert.strictEqual(O.compare(['a', 1, true], ['b', 2, true]), -1) * assert.strictEqual(O.compare(['a', 1, true], ['a', 2, true]), -1) * assert.strictEqual(O.compare(['a', 1, true], ['a', 1, false]), 1) * * @since 2.10.0 */ export const tuple = >(...ords: { [K in keyof A]: Ord }): Ord> => fromCompare((first, second) => { let i = 0 for (; i < ords.length - 1; i++) { const r = ords[i].compare(first[i], second[i]) if (r !== 0) { return r } } return ords[i].compare(first[i], second[i]) }) /** * @since 2.10.0 */ export const reverse = (O: Ord): Ord => fromCompare((first, second) => O.compare(second, first)) /* istanbul ignore next */ const contramap_: (fa: Ord, f: (b: B) => A) => Ord = (fa, f) => pipe(fa, contramap(f)) /** * A typical use case for `contramap` would be like, given some `User` type, to construct an `Ord`. * * We can do so with a function from `User -> X` where `X` is some value that we know how to compare * for ordering (meaning we have an `Ord`) * * For example, given the following `User` type, there are lots of possible choices for `X`, * but let's say we want to sort a list of users by `lastName`. * * If we have a way of comparing `lastName`s for ordering (`ordLastName: Ord`) and we know how to go from `User -> string`, * using `contramap` we can do this * * @example * import { pipe } from 'fp-ts/function' * import { contramap, Ord } from 'fp-ts/Ord' * import * as RA from 'fp-ts/ReadonlyArray' * import * as S from 'fp-ts/string' * * interface User { * readonly firstName: string * readonly lastName: string * } * * const ordLastName: Ord = S.Ord * * const ordByLastName: Ord = pipe( * ordLastName, * contramap((user) => user.lastName) * ) * * assert.deepStrictEqual( * RA.sort(ordByLastName)([ * { firstName: 'a', lastName: 'd' }, * { firstName: 'c', lastName: 'b' } * ]), * [ * { firstName: 'c', lastName: 'b' }, * { firstName: 'a', lastName: 'd' } * ] * ) * * @since 2.0.0 */ export const contramap: (f: (b: B) => A) => (fa: Ord) => Ord = (f) => (fa) => fromCompare((first, second) => fa.compare(f(first), f(second))) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Ord' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Ord } } /** * A typical use case for the `Semigroup` instance of `Ord` is merging two or more orderings. * * For example the following snippet builds an `Ord` for a type `User` which * sorts by `created` date descending, and **then** `lastName` * * @example * import * as D from 'fp-ts/Date' * import { pipe } from 'fp-ts/function' * import { contramap, getSemigroup, Ord, reverse } from 'fp-ts/Ord' * import * as RA from 'fp-ts/ReadonlyArray' * import * as S from 'fp-ts/string' * * interface User { * readonly id: string * readonly lastName: string * readonly created: Date * } * * const ordByLastName: Ord = pipe( * S.Ord, * contramap((user) => user.lastName) * ) * * const ordByCreated: Ord = pipe( * D.Ord, * contramap((user) => user.created) * ) * * const ordUserByCreatedDescThenLastName = getSemigroup().concat( * reverse(ordByCreated), * ordByLastName * ) * * assert.deepStrictEqual( * RA.sort(ordUserByCreatedDescThenLastName)([ * { id: 'c', lastName: 'd', created: new Date(1973, 10, 30) }, * { id: 'a', lastName: 'b', created: new Date(1973, 10, 30) }, * { id: 'e', lastName: 'f', created: new Date(1980, 10, 30) } * ]), * [ * { id: 'e', lastName: 'f', created: new Date(1980, 10, 30) }, * { id: 'a', lastName: 'b', created: new Date(1973, 10, 30) }, * { id: 'c', lastName: 'd', created: new Date(1973, 10, 30) } * ] * ) * * @category instances * @since 2.0.0 */ export const getSemigroup = (): Semigroup> => ({ concat: (first, second) => fromCompare((a, b) => { const ox = first.compare(a, b) return ox !== 0 ? ox : second.compare(a, b) }) }) /** * Returns a `Monoid` such that: * * - its `concat(ord1, ord2)` operation will order first by `ord1`, and then by `ord2` * - its `empty` value is an `Ord` that always considers compared elements equal * * @example * import { sort } from 'fp-ts/Array' * import { contramap, reverse, getMonoid } from 'fp-ts/Ord' * import * as S from 'fp-ts/string' * import * as B from 'fp-ts/boolean' * import { pipe } from 'fp-ts/function' * import { concatAll } from 'fp-ts/Monoid' * import * as N from 'fp-ts/number' * * interface User { * readonly id: number * readonly name: string * readonly age: number * readonly rememberMe: boolean * } * * const byName = pipe( * S.Ord, * contramap((p: User) => p.name) * ) * * const byAge = pipe( * N.Ord, * contramap((p: User) => p.age) * ) * * const byRememberMe = pipe( * B.Ord, * contramap((p: User) => p.rememberMe) * ) * * const M = getMonoid() * * const users: Array = [ * { id: 1, name: 'Guido', age: 47, rememberMe: false }, * { id: 2, name: 'Guido', age: 46, rememberMe: true }, * { id: 3, name: 'Giulio', age: 44, rememberMe: false }, * { id: 4, name: 'Giulio', age: 44, rememberMe: true } * ] * * // sort by name, then by age, then by `rememberMe` * const O1 = concatAll(M)([byName, byAge, byRememberMe]) * assert.deepStrictEqual(sort(O1)(users), [ * { id: 3, name: 'Giulio', age: 44, rememberMe: false }, * { id: 4, name: 'Giulio', age: 44, rememberMe: true }, * { id: 2, name: 'Guido', age: 46, rememberMe: true }, * { id: 1, name: 'Guido', age: 47, rememberMe: false } * ]) * * // now `rememberMe = true` first, then by name, then by age * const O2 = concatAll(M)([reverse(byRememberMe), byName, byAge]) * assert.deepStrictEqual(sort(O2)(users), [ * { id: 4, name: 'Giulio', age: 44, rememberMe: true }, * { id: 2, name: 'Guido', age: 46, rememberMe: true }, * { id: 3, name: 'Giulio', age: 44, rememberMe: false }, * { id: 1, name: 'Guido', age: 47, rememberMe: false } * ]) * * @category instances * @since 2.4.0 */ export const getMonoid = (): Monoid> => ({ concat: getSemigroup().concat, empty: fromCompare(() => 0) }) /** * @category instances * @since 2.7.0 */ export const Contravariant: Contravariant1 = { URI, contramap: contramap_ } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const trivial: Ord = { equals: constTrue, compare: /*#__PURE__*/ constant(0) } /** * @since 2.11.0 */ export const equals = (O: Ord) => (second: A) => (first: A): boolean => first === second || O.compare(first, second) === 0 // TODO: curry in v3 /** * Test whether one value is _strictly less than_ another * * @since 2.0.0 */ export const lt = (O: Ord) => (first: A, second: A): boolean => O.compare(first, second) === -1 // TODO: curry in v3 /** * Test whether one value is _strictly greater than_ another * * @since 2.0.0 */ export const gt = (O: Ord) => (first: A, second: A): boolean => O.compare(first, second) === 1 // TODO: curry in v3 /** * Test whether one value is _non-strictly less than_ another * * @since 2.0.0 */ export const leq = (O: Ord) => (first: A, second: A): boolean => O.compare(first, second) !== 1 // TODO: curry in v3 /** * Test whether one value is _non-strictly greater than_ another * * @since 2.0.0 */ export const geq = (O: Ord) => (first: A, second: A): boolean => O.compare(first, second) !== -1 // TODO: curry in v3 /** * Take the minimum of two values. If they are considered equal, the first argument is chosen * * @since 2.0.0 */ export const min = (O: Ord) => (first: A, second: A): A => first === second || O.compare(first, second) < 1 ? first : second // TODO: curry in v3 /** * Take the maximum of two values. If they are considered equal, the first argument is chosen * * @since 2.0.0 */ export const max = (O: Ord) => (first: A, second: A): A => first === second || O.compare(first, second) > -1 ? first : second /** * Clamp a value between a minimum and a maximum * * @since 2.0.0 */ export const clamp = (O: Ord): ((low: A, hi: A) => (a: A) => A) => { const minO = min(O) const maxO = max(O) return (low, hi) => (a) => maxO(minO(a, hi), low) } /** * Test whether a value is between a minimum and a maximum (inclusive) * * @since 2.0.0 */ export const between = (O: Ord): ((low: A, hi: A) => (a: A) => boolean) => { const ltO = lt(O) const gtO = gt(O) return (low, hi) => (a) => ltO(a, low) || gtO(a, hi) ? false : true } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`tuple`](#tuple) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getTupleOrd: >>( ...ords: T ) => Ord<{ [K in keyof T]: T[K] extends Ord ? A : never }> = tuple /** * Use [`reverse`](#reverse) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getDualOrd = reverse /** * Use [`Contravariant`](#contravariant) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const ord: Contravariant1 = Contravariant // default compare for primitive types function compare(first: any, second: any): Ordering { return first < second ? -1 : first > second ? 1 : 0 } const strictOrd = { equals: eqStrict.equals, compare } /** * Use [`Ord`](./boolean.ts.html#ord) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const ordBoolean: Ord = strictOrd /** * Use [`Ord`](./string.ts.html#ord) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const ordString: Ord = strictOrd /** * Use [`Ord`](./number.ts.html#ord) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const ordNumber: Ord = strictOrd /** * Use [`Ord`](./Date.ts.html#ord) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const ordDate: Ord = /*#__PURE__*/ pipe( ordNumber, /*#__PURE__*/ contramap((date) => date.valueOf()) ) ================================================ FILE: src/Ordering.ts ================================================ /** * @since 2.0.0 */ import * as E from './Eq' import * as M from './Monoid' import * as S from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export type Ordering = -1 | 0 | 1 /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.12.0 */ export const matchW = (onLessThan: () => A, onEqual: () => B, onGreaterThan: () => C) => (o: Ordering): A | B | C => o === -1 ? onLessThan() : o === 0 ? onEqual() : onGreaterThan() /** * @category pattern matching * @since 2.10.0 */ export const match: (onLessThan: () => A, onEqual: () => A, onGreaterThan: () => A) => (o: Ordering) => A = matchW // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export const reverse = (o: Ordering): Ordering => (o === -1 ? 1 : o === 1 ? -1 : 0) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.10.0 */ export const Eq: E.Eq = { equals: (x, y) => x === y } /** * @category instances * @since 2.10.0 */ export const Semigroup: S.Semigroup = { concat: (x, y) => (x !== 0 ? x : y) } /** * @category instances * @since 2.10.0 */ export const Monoid: M.Monoid = { concat: Semigroup.concat, empty: 0 } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export const sign = (n: number): Ordering => (n <= -1 ? -1 : n >= 1 ? 1 : 0) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`reverse`](#reverse) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const invert = reverse /** * Use [`Semigroup`](#semigroup) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupOrdering: S.Semigroup = Semigroup /** * Use [`Eq`](#eq) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const eqOrdering: E.Eq = Eq /** * Use [`Monoid`](#monoid) instead * * @category zone of death * @since 2.4.0 * @deprecated */ export const monoidOrdering: M.Monoid = Monoid ================================================ FILE: src/Pointed.ts ================================================ /** * @since 2.10.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.10.0 */ export interface Pointed { readonly URI: F readonly of: (a: A) => HKT } /** * @category model * @since 2.10.0 */ export interface Pointed1 { readonly URI: F readonly of: (a: A) => Kind } /** * @category model * @since 2.10.0 */ export interface Pointed2 { readonly URI: F readonly of: (a: A) => Kind2 } /** * @category model * @since 2.10.0 */ export interface Pointed2C { readonly URI: F readonly _E: E readonly of: (a: A) => Kind2 } /** * @category model * @since 2.10.0 */ export interface Pointed3 { readonly URI: F readonly of: (a: A) => Kind3 } /** * @category model * @since 2.10.0 */ export interface Pointed3C { readonly URI: F readonly _E: E readonly of: (a: A) => Kind3 } /** * @category model * @since 2.10.0 */ export interface Pointed4 { readonly URI: F readonly of: (a: A) => Kind4 } ================================================ FILE: src/Predicate.ts ================================================ /** * @since 2.11.0 */ import { Contravariant1 } from './Contravariant' import { constFalse, constTrue, flow, pipe } from './function' import { Monoid } from './Monoid' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export interface Predicate { (a: A): boolean } const contramap_: Contravariant1['contramap'] = (predicate, f) => pipe(predicate, contramap(f)) /** * @since 2.11.0 */ export const contramap = (f: (b: B) => A) => (predicate: Predicate): Predicate => flow(f, predicate) /** * @category type lambdas * @since 2.11.0 */ export const URI = 'Predicate' /** * @category type lambdas * @since 2.11.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Predicate } } /** * @category instances * @since 2.11.0 */ export const getSemigroupAny = (): Semigroup> => ({ concat: (first, second) => pipe(first, or(second)) }) /** * @category instances * @since 2.11.0 */ export const getMonoidAny = (): Monoid> => ({ concat: getSemigroupAny().concat, empty: constFalse }) /** * @category instances * @since 2.11.0 */ export const getSemigroupAll = (): Semigroup> => ({ concat: (first, second) => pipe(first, and(second)) }) /** * @category instances * @since 2.11.0 */ export const getMonoidAll = (): Monoid> => ({ concat: getSemigroupAll().concat, empty: constTrue }) /** * @category instances * @since 2.11.0 */ export const Contravariant: Contravariant1 = { URI, contramap: contramap_ } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const not = (predicate: Predicate): Predicate => (a) => !predicate(a) /** * @since 2.11.0 */ export const or = (second: Predicate) => (first: Predicate): Predicate => (a) => first(a) || second(a) /** * @since 2.11.0 */ export const and = (second: Predicate) => (first: Predicate): Predicate => (a) => first(a) && second(a) ================================================ FILE: src/Profunctor.ts ================================================ /** * @since 2.0.0 */ import { Functor2, Functor2C, Functor3, Functor3C, Functor4 } from './Functor' import { HKT, HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Profunctor { readonly URI: F readonly map: (fa: HKT2, f: (a: A) => B) => HKT readonly promap: (fea: HKT2, f: (d: D) => E, g: (a: A) => B) => HKT2 } /** * @category model * @since 2.0.0 */ export interface Profunctor2 extends Functor2 { readonly promap: (fea: Kind2, f: (d: D) => E, g: (a: A) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Profunctor2C extends Functor2C { readonly promap: (fea: Kind2, f: (d: D) => E, g: (a: A) => B) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Profunctor3 extends Functor3 { readonly promap: (fea: Kind3, f: (d: D) => E, g: (a: A) => B) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Profunctor3C extends Functor3C { readonly promap: (fea: Kind3, f: (d: D) => E, g: (a: A) => B) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Profunctor4 extends Functor4 { readonly promap: (fea: Kind4, f: (d: D) => E, g: (a: A) => B) => Kind4 } ================================================ FILE: src/Random.ts ================================================ /** * @since 2.0.0 */ import { pipe } from './function' import { IO, map } from './IO' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' /** * Returns a random number between 0 (inclusive) and 1 (exclusive). This is a direct wrapper around JavaScript's * `Math.random()`. * * @since 2.0.0 */ export const random: IO = () => Math.random() /** * Takes a range specified by `low` (the first argument) and `high` (the second), and returns a random integer uniformly * distributed in the closed interval `[low, high]`. It is unspecified what happens if `low > high`, or if either of * `low` or `high` is not an integer. * * @since 2.0.0 */ export function randomInt(low: number, high: number): IO { return pipe( random, map((n) => Math.floor((high - low + 1) * n + low)) ) } /** * Returns a random number between a minimum value (inclusive) and a maximum value (exclusive). It is unspecified what * happens if `maximum < minimum`. * * @since 2.0.0 */ export function randomRange(min: number, max: number): IO { return pipe( random, map((n) => (max - min) * n + min) ) } /** * Returns a random boolean value with an equal chance of being `true` or `false` * * @since 2.0.0 */ export const randomBool: IO = /*#__PURE__*/ pipe( random, map((n) => n < 0.5) ) /** * Returns a random element of a `ReadonlyNonEmptyArray`. * * @since 2.10.0 */ export const randomElem = (as: ReadonlyNonEmptyArray): IO => pipe( randomInt(0, as.length - 1), map((i) => as[i]) ) ================================================ FILE: src/Reader.ts ================================================ /** * The `Reader` monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, * pass values from function to function, and execute sub-computations in a modified environment. * Using `Reader` monad for such computations is often clearer and easier than using the `State` monad. * * In this example the `Reader` monad provides access to variable bindings. `Bindings` are a map of `number` variables. * The variable count contains number of variables in the bindings. You can see how to run a `Reader` monad and retrieve * data from it, how to access the `Reader` data with `ask` and `asks`. * * @example * import { pipe } from 'fp-ts/function' * import * as O from 'fp-ts/Option' * import * as R from 'fp-ts/Reader' * import * as RR from 'fp-ts/ReadonlyRecord' * * interface Bindings extends RR.ReadonlyRecord {} * * // The Reader monad, which implements this complicated check. * const isCountCorrect: R.Reader = pipe( * R.Do, * R.bind('count', () => R.asks(lookupVar('count'))), * R.bind('bindings', () => R.ask()), * R.map(({ count, bindings }) => count === RR.size(bindings)) * ) * * // The selector function to use with 'asks'. * // Returns value of the variable with specified name. * const lookupVar = (name: string) => (bindings: Bindings): number => * pipe( * bindings, * RR.lookup(name), * O.getOrElse(() => 0) * ) * * const sampleBindings: Bindings = { count: 3, a: 1, b: 2 } * * assert.deepStrictEqual(isCountCorrect(sampleBindings), true) * * @since 2.0.0 */ import { Applicative2, getApplicativeMonoid } from './Applicative' import { apFirst as apFirst_, Apply2, apS as apS_, apSecond as apSecond_, getApplySemigroup } from './Apply' import { Category2 } from './Category' import * as chainable from './Chain' import { Choice2 } from './Choice' import * as E from './Either' import { constant, dual, flow, identity, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor2, let as let__ } from './Functor' import * as _ from './internal' import { Monad2 } from './Monad' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Pointed2 } from './Pointed' import { Profunctor2 } from './Profunctor' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Semigroup } from './Semigroup' import { Strong2 } from './Strong' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Reader { (r: R): A } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Reads the current context * * @category constructors * @since 2.0.0 */ export const ask: () => Reader = () => identity /** * Projects a value from the global context in a Reader * * @category constructors * @since 2.0.0 */ export const asks: (f: (r: R) => A) => Reader = identity // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s * `contramap`). * * @example * import { pipe } from 'fp-ts/function' * import * as R from 'fp-ts/Reader' * import * as string from 'fp-ts/string' * * const calculateContentLen: R.Reader = pipe( * R.Do, * R.bind('content', () => R.ask()), * R.map(({ content }) => string.size(content)) * ) * * // Calls calculateContentLen after adding a prefix to the Reader content. * const calculateModifiedContentLen: R.Reader = pipe( * calculateContentLen, * R.local((s) => 'Prefix ' + s) * ) * * const s = '12345' * * assert.deepStrictEqual( * "Modified 's' length: " + calculateModifiedContentLen(s) + '\n' + "Original 's' length: " + calculateContentLen(s), * "Modified 's' length: 12\nOriginal 's' length: 5" * ) * * @since 2.0.0 */ export const local: (f: (r2: R2) => R1) => (ma: Reader) => Reader = (f) => (ma) => (r2) => ma(f(r2)) /** * Less strict version of [`asksReader`](#asksreader). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category constructors * @since 2.11.0 */ export const asksReaderW = (f: (r1: R1) => Reader): Reader => (r) => f(r)(r) /** * Effectfully accesses the environment. * * @category constructors * @since 2.11.0 */ export const asksReader: (f: (r: R) => Reader) => Reader = asksReaderW /* istanbul ignore next */ const _map: Monad2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _ap: Monad2['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _compose: Category2['compose'] = (bc, ab) => pipe(bc, compose(ab)) const _promap: Profunctor2['promap'] = (fea, f, g) => pipe(fea, promap(f, g)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Reader) => Reader = (f) => (fa) => (r) => f(fa(r)) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.8.0 */ export const apW: (fa: Reader) => (fab: Reader B>) => Reader = (fa) => (fab) => (r) => fab(r)(fa(r)) /** * @since 2.0.0 */ export const ap: (fa: Reader) => (fab: Reader B>) => Reader = apW /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => Reader = constant /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => Reader): (ma: Reader) => Reader (ma: Reader, f: (a: A) => Reader): Reader } = /*#__PURE__*/ dual( 2, (ma: Reader, f: (a: A) => Reader): Reader => (r) => f(ma(r))(r) ) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: (mma: Reader>) => Reader = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: Reader>) => Reader = flattenW /** * @since 2.0.0 */ export const compose: (ab: Reader) => (bc: Reader) => Reader = (ab) => (bc) => flow(ab, bc) /** * @since 2.0.0 */ export const promap: (f: (d: D) => E, g: (a: A) => B) => (fea: Reader) => Reader = (f, g) => (fea) => (a) => g(fea(f(a))) /** * @category constructors * @since 2.0.0 */ export const id: Category2['id'] = () => identity /** * @since 2.10.0 */ export const first: Strong2['first'] = (pab) => ([a, c]) => [pab(a), c] /** * @since 2.10.0 */ export const second: Strong2['second'] = (pbc) => ([a, b]) => [a, pbc(b)] /** * @since 2.10.0 */ export const left: Choice2['left'] = (pab) => E.fold((a) => _.left(pab(a)), E.right) /** * @since 2.10.0 */ export const right: Choice2['right'] = (pbc) => E.fold(E.left, (b) => _.right(pbc(b))) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Reader' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Reader } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply2 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Less strict version of [`apFirst`](#apfirst). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.12.0 */ export const apFirstW: (second: Reader) => (first: Reader) => Reader = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * Less strict version of [`apSecond`](#apsecond). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.12.0 */ export const apSecondW: (second: Reader) => (first: Reader) => Reader = apSecond as any /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative2 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad2 = { URI, map: _map, of, ap: _ap, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: Reader, f: (a: A) => Reader): Reader (f: (a: A) => Reader): (self: Reader) => Reader } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * @category instances * @since 2.7.0 */ export const Profunctor: Profunctor2 = { URI, map: _map, promap: _promap } /** * @category instances * @since 2.7.0 */ export const Category: Category2 = { URI, compose: _compose, id } /** * @category instances * @since 2.8.3 */ export const Strong: Strong2 = { URI, map: _map, promap: _promap, first, second } /** * @category instances * @since 2.8.3 */ export const Choice: Choice2 = { URI, map: _map, promap: _promap, left, right } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => Reader ) => (fa: Reader) => Reader = bind as any /** * @category do notation * @since 2.9.0 */ export const Do: Reader = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: Reader ) => (fa: Reader) => Reader = apS as any /** * @since 2.11.0 */ export const ApT: Reader = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => Reader) => (as: ReadonlyNonEmptyArray): Reader> => (r) => { const out: NonEmptyArray = [f(0, _.head(as))(r)] for (let i = 1; i < as.length; i++) { out.push(f(i, as[i])(r)) } return out } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => Reader ): ((as: ReadonlyArray) => Reader>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => Reader ) => (as: ReadonlyArray) => Reader> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => Reader ): ((as: ReadonlyArray) => Reader>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => Reader> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: (f: (a: A) => Reader) => (ma: Reader) => Reader = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Reader) => (ma: Reader) => Reader = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => Reader) => (first: Reader) => Reader = tap /** * Alias of `tap`. * * @category legacy * @since 2.11.0 */ export const chainFirstW: (f: (a: A) => Reader) => (ma: Reader) => Reader = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `R.Functor` instead of `R.reader` * (where `R` is from `import R from 'fp-ts/Reader'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const reader: Monad2 & Profunctor2 & Category2 & Strong2 & Choice2 = { URI, map: _map, of, ap: _ap, chain: flatMap, promap: _promap, compose: _compose, id, first, second, left, right } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup(Apply) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(Applicative) ================================================ FILE: src/ReaderEither.ts ================================================ /** * @since 2.0.0 */ import { Alt3, Alt3C } from './Alt' import { Applicative3, Applicative3C, getApplicativeMonoid } from './Applicative' import { ap as ap_, apFirst as apFirst_, Apply3, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import { Bifunctor3 } from './Bifunctor' import * as chainable from './Chain' import { compact as compact_, Compactable3C, separate as separate_ } from './Compactable' import * as E from './Either' import * as ET from './EitherT' import { filter as filter_, Filterable3C, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable' import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, FromEither3, fromEitherK as fromEitherK_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_, tapEither as tapEither_ } from './FromEither' import { ask as ask_, asks as asks_, FromReader3, fromReaderK as fromReaderK_, tapReader as tapReader_ } from './FromReader' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor3, let as let__ } from './Functor' import * as _ from './internal' import { Monad3, Monad3C } from './Monad' import { MonadThrow3, MonadThrow3C } from './MonadThrow' import { Monoid } from './Monoid' import { Option } from './Option' import { Pointed3 } from './Pointed' import { Predicate } from './Predicate' import * as R from './Reader' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import Reader = R.Reader import Either = E.Either // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface ReaderEither extends Reader> {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export const left: (e: E) => ReaderEither = /*#__PURE__*/ ET.left(R.Pointed) /** * @category constructors * @since 2.0.0 */ export const right: (a: A) => ReaderEither = /*#__PURE__*/ ET.right(R.Pointed) /** * @category constructors * @since 2.0.0 */ export const rightReader: (ma: Reader) => ReaderEither = /*#__PURE__*/ ET.rightF(R.Functor) /** * @category constructors * @since 2.0.0 */ export const leftReader: (me: Reader) => ReaderEither = /*#__PURE__*/ ET.leftF( R.Functor ) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.0.0 */ export const fromEither: (fa: Either) => ReaderEither = R.of /** * @category conversions * @since 2.11.0 */ export const fromReader: (fa: Reader) => ReaderEither = rightReader /** * @category pattern matching * @since 2.10.0 */ export const match: ( onLeft: (e: E) => B, onRight: (a: A) => B ) => (ma: ReaderEither) => Reader = /*#__PURE__*/ ET.match(R.Functor) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C ) => (ma: Reader>) => Reader = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Reader`). * * @category pattern matching * @since 2.10.0 */ export const matchE: ( onLeft: (e: E) => Reader, onRight: (a: A) => Reader ) => (ma: ReaderEither) => Reader = /*#__PURE__*/ ET.matchE(R.Monad) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.0.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchEW: ( onLeft: (e: E) => Reader, onRight: (a: A) => Reader ) => (ma: ReaderEither) => Reader = matchE as any /** * Alias of [`matchEW`](#matchew). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchEW /** * @category error handling * @since 2.0.0 */ export const getOrElse: (onLeft: (e: E) => Reader) => (ma: ReaderEither) => Reader = /*#__PURE__*/ ET.getOrElse(R.Monad) /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.6.0 */ export const getOrElseW: ( onLeft: (e: E) => Reader ) => (ma: ReaderEither) => Reader = getOrElse as any /** * @category conversions * @since 2.10.0 */ export const toUnion: (fa: ReaderEither) => Reader = /*#__PURE__*/ ET.toUnion(R.Functor) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s * `contramap`). * * @since 2.0.0 */ export const local: (f: (r2: R2) => R1) => (ma: ReaderEither) => ReaderEither = R.local /** * Less strict version of [`asksReaderEither`](#asksreadereither). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category constructors * @since 2.11.0 */ export const asksReaderEitherW: (f: (r1: R1) => ReaderEither) => ReaderEither = R.asksReaderW /** * Effectfully accesses the environment. * * @category constructors * @since 2.11.0 */ export const asksReaderEither: (f: (r: R) => ReaderEither) => ReaderEither = asksReaderEitherW /** * @category error handling * @since 2.0.0 */ export const orElse: ( onLeft: (e: E1) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = /*#__PURE__*/ ET.orElse(R.Monad) /** * Less strict version of [`orElse`](#orelse). * * The `W` suffix (short for **W**idening) means that the environment types and the return types will be merged. * * @category error handling * @since 2.10.0 */ export const orElseW: ( onLeft: (e: E1) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = orElse as any /** * Returns an effect that effectfully "peeks" at the failure of this effect. * * @category error handling * @since 2.15.0 */ export const tapError: { (onLeft: (e: E1) => ReaderEither): ( self: ReaderEither ) => ReaderEither (self: ReaderEither, onLeft: (e: E1) => ReaderEither): ReaderEither< R1 & R2, E1 | E2, A > } = /*#__PURE__*/ dual(2, ET.tapError(R.Monad)) /** * @category error handling * @since 2.11.0 */ export const orLeft: ( onLeft: (e: E1) => Reader ) => (fa: ReaderEither) => ReaderEither = /*#__PURE__*/ ET.orLeft(R.Monad) /** * @category error handling * @since 2.16.6 */ export const orLeftW: ( onLeft: (e: E1) => Reader ) => (fa: ReaderEither) => ReaderEither = orLeft as any /** * @since 2.0.0 */ export const swap: (ma: ReaderEither) => ReaderEither = /*#__PURE__*/ ET.swap(R.Functor) /* istanbul ignore next */ const _map: Monad3['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _ap: Monad3['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _alt: Alt3['alt'] = (fa, that) => pipe(fa, alt(that)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: ReaderEither) => ReaderEither = /*#__PURE__*/ ET.map(R.Functor) /** * Returns a `ReaderEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. * * @example * import * as ReaderEither from 'fp-ts/ReaderEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * const g = (n: number) => n * 2 * * assert.deepStrictEqual(ReaderEither.mapBoth(ReaderEither.right(1), f, g)({}), Either.right(2)) * assert.deepStrictEqual(ReaderEither.mapBoth(ReaderEither.left('err'), f, g)({}), Either.left(new Error('err'))) * * @category error handling * @since 2.16.0 */ export const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (e: E) => G, g: (a: A) => B): ReaderEither } = /*#__PURE__*/ dual(3, ET.mapBoth(R.Functor)) /** * Alias of `mapBoth`. * * @category legacy * @since 2.0.0 */ export const bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: ReaderEither) => ReaderEither = mapBoth /** * Returns a `ReaderEither` with its error channel mapped using the specified function. * * @example * import * as ReaderEither from 'fp-ts/ReaderEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * * assert.deepStrictEqual(ReaderEither.mapError(ReaderEither.right(1), f)({}), Either.right(1)) * assert.deepStrictEqual(ReaderEither.mapError(ReaderEither.left('err'), f)({}), Either.left(new Error('err'))) * * @category error handling * @since 2.16.0 */ export const mapError: { (f: (e: E) => G): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (e: E) => G): ReaderEither } = /*#__PURE__*/ dual(2, ET.mapError(R.Functor)) /** * Alias of `mapError`. * * @category legacy * @since 2.0.0 */ export const mapLeft: (f: (e: E) => G) => (fa: ReaderEither) => ReaderEither = mapError /** * @since 2.0.0 */ export const ap: ( fa: ReaderEither ) => (fab: ReaderEither B>) => ReaderEither = /*#__PURE__*/ ET.ap(R.Apply) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.8.0 */ export const apW: ( fa: ReaderEither ) => (fab: ReaderEither B>) => ReaderEither = ap as any /** * @category constructors * @since 2.8.5 */ export const of: (a: A) => ReaderEither = right /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => ReaderEither): ( ma: ReaderEither ) => ReaderEither (ma: ReaderEither, f: (a: A) => ReaderEither): ReaderEither< R1 & R2, E1 | E2, B > } = /*#__PURE__*/ dual(2, ET.flatMap(R.Monad)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: ( mma: ReaderEither> ) => ReaderEither = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: ReaderEither>) => ReaderEither = flattenW /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * @category error handling * @since 2.0.0 */ export const alt: (that: () => ReaderEither) => (fa: ReaderEither) => ReaderEither = /*#__PURE__*/ ET.alt(R.Monad) /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the environment, the error and the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW: ( that: () => ReaderEither ) => (fa: ReaderEither) => ReaderEither = alt as any /** * @since 2.7.0 */ export const throwError: MonadThrow3['throwError'] = left /** * @category type lambdas * @since 2.0.0 */ export const URI = 'ReaderEither' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind3 { readonly [URI]: ReaderEither } } /** * @category filtering * @since 2.10.0 */ export const getCompactable = (M: Monoid): Compactable3C => { const C = E.getCompactable(M) return { URI, _E: undefined as any, compact: compact_(R.Functor, C), separate: separate_(R.Functor, C, E.Functor) } } /** * @category filtering * @since 2.10.0 */ export function getFilterable(M: Monoid): Filterable3C { const F = E.getFilterable(M) const C = getCompactable(M) const filter = filter_(R.Functor, F) const filterMap = filterMap_(R.Functor, F) const partition = partition_(R.Functor, F) const partitionMap = partitionMap_(R.Functor, F) return { URI, _E: undefined as any, map: _map, compact: C.compact, separate: C.separate, filter: (fa: ReaderEither, predicate: Predicate) => pipe(fa, filter(predicate)), filterMap: (fa, f) => pipe(fa, filterMap(f)), partition: (fa: ReaderEither, predicate: Predicate) => pipe(fa, partition(predicate)), partitionMap: (fa, f) => pipe(fa, partitionMap(f)) } } /** * The default [`Applicative`](#applicative) instance returns the first error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getApplicativeValidation`](./Either.ts.html#getapplicativevalidation). * * @category error handling * @since 2.7.0 */ export function getApplicativeReaderValidation(S: Semigroup): Applicative3C { const ap = ap_(R.Apply, E.getApplicativeValidation(S)) return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => pipe(fab, ap(fa)), of } } /** * The default [`Alt`](#alt) instance returns the last error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getAltValidation`](./Either.ts.html#getaltvalidation). * * @category error handling * @since 2.7.0 */ export function getAltReaderValidation(S: Semigroup): Alt3C { const alt = ET.altValidation(R.Monad, S) return { URI, _E: undefined as any, map: _map, alt: (fa, that) => pipe(fa, alt(that)) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor3 = { URI, map: _map } /** * Maps the `Right` value of this `ReaderEither` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: ReaderEither) => ReaderEither (self: ReaderEither, a: A): ReaderEither } = dual(2, as_(Functor)) /** * Maps the `Right` value of this `ReaderEither` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: ReaderEither) => ReaderEither = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed3 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply3 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Less strict version of [`apFirst`](#apfirst) * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.12.0 */ export const apFirstW: ( second: ReaderEither ) => (first: ReaderEither) => ReaderEither = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * Less strict version of [`apSecond`](#apsecond) * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.12.0 */ export const apSecondW: ( second: ReaderEither ) => (first: ReaderEither) => ReaderEither = apSecond as any /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative3 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain3 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad3 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither3 = { URI, fromEither } /** * @category instances * @since 2.11.0 */ export const FromReader: FromReader3 = { URI, fromReader } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: ReaderEither, f: (a: A) => ReaderEither): ReaderEither< R1 & R2, E1 | E2, A > (f: (a: A) => ReaderEither): ( self: ReaderEither ) => ReaderEither } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as RE from 'fp-ts/ReaderEither' * * const checkString = (value: string) => pipe( * RE.ask(), * RE.tapEither( * (minLength) => value.length > minLength * ? E.right('ok') * : E.left('error') * ) * ) * * assert.deepStrictEqual(checkString('')(1), E.left('error')) * assert.deepStrictEqual(checkString('fp-ts')(2), E.right(2)) * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => Either): ReaderEither } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReader: { (f: (a: A) => Reader): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => Reader): ReaderEither } = /*#__PURE__*/ dual(2, tapReader_(FromReader, Chain)) /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor3 = { URI, bimap: mapBoth, mapLeft: mapError } /** * @category instances * @since 2.7.0 */ export const Alt: Alt3 = { URI, map: _map, alt: _alt } /** * Reads the current context. * * @category constructors * @since 2.0.0 */ export const ask: () => ReaderEither = /*#__PURE__*/ ask_(FromReader) /** * Projects a value from the global context in a `ReaderEither`. * * @category constructors * @since 2.0.0 */ export const asks: (f: (r: R) => A) => ReaderEither = /*#__PURE__*/ asks_(FromReader) /** * @category lifting * @since 2.11.0 */ export const fromReaderK: , R, B>( f: (...a: A) => Reader ) => (...a: A) => ReaderEither = /*#__PURE__*/ fromReaderK_(FromReader) /** * Alias of `tapReader`. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderK: ( f: (a: A) => Reader ) => (ma: ReaderEither) => ReaderEither = tapReader /** * Alias of `tapReader`. * * Less strict version of [`chainReaderK`](#chainreaderk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderKW: ( f: (a: A) => Reader ) => (ma: ReaderEither) => ReaderEither = tapReader /** * @category instances * @since 2.7.0 */ export const MonadThrow: MonadThrow3 = { URI, map: _map, ap: _ap, of, chain: flatMap, throwError } /** * @category conversions * @since 2.0.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => ReaderEither = /*#__PURE__*/ fromOption_(FromEither) /** * Use `liftOption`. * * @category legacy * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>( f: (...a: A) => Option ) => (...a: A) => ReaderEither = /*#__PURE__*/ fromOptionK_(FromEither) /** * Use `flatMapOption`. * * @category legacy * @since 2.10.0 */ export const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderEither) => ReaderEither = /*#__PURE__*/ chainOptionK_(FromEither, Chain) /** * Use `flatMapOption`. * * @category legacy * @since 2.13.2 */ export const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderEither) => ReaderEither = chainOptionK as any /** @internal */ interface ReaderEitherTypeLambda extends _.TypeLambda { readonly type: ReaderEither } /** @internal */ const _FromEither: _.FromEither = { fromEither: FromEither.fromEither } /** @internal */ const _FromReader: _.FromReader = { fromReader: FromReader.fromReader } /** * @category lifting * @since 2.15.0 */ export const liftNullable: , B, E>( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => ReaderEither> = /*#__PURE__*/ _.liftNullable(_FromEither) /** * @category lifting * @since 2.15.0 */ export const liftOption: , B, E>( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => ReaderEither = /*#__PURE__*/ _.liftOption(_FromEither) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** * @category sequencing * @since 2.15.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: ReaderEither ) => ReaderEither> ( self: ReaderEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2 ): ReaderEither> } = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: ReaderEither ) => ReaderEither (self: ReaderEither, f: (a: A) => Option, onNone: (a: A) => E2): ReaderEither< R, E1 | E2, B > } = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapEither: { (f: (a: A) => E.Either): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => E.Either): ReaderEither } = /*#__PURE__*/ _.flatMapEither(_FromEither, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReader: { (f: (a: A) => Reader): (self: ReaderEither) => ReaderEither (self: ReaderEither, f: (a: A) => Reader): ReaderEither } = /*#__PURE__*/ _.flatMapReader(_FromReader, _FlatMap) /** * Alias of `flatMapEither`. * * @category legacy * @since 2.4.0 */ export const chainEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderEither) => ReaderEither = flatMapEither /** * Alias of `flatMapEither`. * * @category legacy * @since 2.6.1 */ export const chainEitherKW: ( f: (a: A) => Either ) => (ma: ReaderEither) => ReaderEither = flatMapEither /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderEither) => ReaderEither = tapEither /** * Alias of `tapEither`. * * Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherKW: ( f: (a: A) => Either ) => (ma: ReaderEither) => ReaderEither = tapEither /** * Alias of `flatMapReader`. * * @category legacy * @since 2.11.0 */ export const chainReaderK: ( f: (a: A) => Reader ) => (ma: ReaderEither) => ReaderEither = flatMapReader /** * Alias of `flatMapReader`. * * Less strict version of [`chainReaderK`](#chainreaderk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.11.0 */ export const chainReaderKW: ( f: (a: A) => Reader ) => (ma: ReaderEither) => ReaderEither = flatMapReader /** * @category lifting * @since 2.0.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): (b: B) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => ReaderEither } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category filtering * @since 2.0.0 */ export const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): ( mb: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E): (ma: ReaderEither) => ReaderEither } = /*#__PURE__*/ filterOrElse_(FromEither, Chain) /** * Less strict version of [`filterOrElse`](#filterorelse). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category filtering * @since 2.9.0 */ export const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: ReaderEither ) => ReaderEither (predicate: Predicate, onFalse: (a: A) => E2): ( ma: ReaderEither ) => ReaderEither } = filterOrElse /** * @category lifting * @since 2.4.0 */ export const fromEitherK: , B>( f: (...a: A) => E.Either ) => (...a: A) => ReaderEither = /*#__PURE__*/ fromEitherK_(FromEither) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: ReaderEither = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => ReaderEither ) => ( fa: ReaderEither ) => ReaderEither = bind as any /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: ReaderEither ) => ( fa: ReaderEither ) => ReaderEither = apS as any /** * @since 2.11.0 */ export const ApT: ReaderEither = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => ReaderEither ): ((as: ReadonlyNonEmptyArray) => ReaderEither>) => flow(R.traverseReadonlyNonEmptyArrayWithIndex(f), R.map(E.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => ReaderEither ): ((as: ReadonlyArray) => ReaderEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderEither ) => (as: ReadonlyArray) => ReaderEither> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => ReaderEither ): ((as: ReadonlyArray) => ReaderEither>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: ( arr: ReadonlyArray> ) => ReaderEither> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = tap /** * Alias of `tap`. * * @category legacy * @since 2.8.0 */ export const chainFirstW: ( f: (a: A) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = tap /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirst: ( onLeft: (e: E) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = tapError /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirstW: ( onLeft: (e: E1) => ReaderEither ) => (ma: ReaderEither) => ReaderEither = tapError // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RE.Functor` instead of `RE.readerEither` * (where `R` is from `import R from 'fp-ts/ReaderEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const readerEither: Monad3 & Bifunctor3 & Alt3 & MonadThrow3 = { URI, bimap: mapBoth, mapLeft: mapError, map: _map, of, ap: _ap, chain: flatMap, alt: _alt, throwError: left } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplySemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(Apply) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplyMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(Applicative) /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup = (S: Semigroup): Semigroup> => getApplySemigroup_(R.Apply)(E.getSemigroup(S)) /** * Use [`getApplicativeReaderValidation`](#getapplicativereadervalidation) and [`getAltReaderValidation`](#getaltreadervalidation) instead. * * @category zone of death * @since 2.3.0 * @deprecated */ export function getReaderValidation( SE: Semigroup ): Monad3C & Bifunctor3 & Alt3C & MonadThrow3C { const applicativeReaderValidation = getApplicativeReaderValidation(SE) const altReaderValidation = getAltReaderValidation(SE) return { URI, _E: undefined as any, map: _map, ap: applicativeReaderValidation.ap, of, chain: flatMap, bimap: mapBoth, mapLeft: mapError, alt: altReaderValidation.alt, throwError } } ================================================ FILE: src/ReaderIO.ts ================================================ /** * @since 2.13.0 */ import { Applicative2 } from './Applicative' import { apFirst as apFirst_, Apply2, apS as apS_, apSecond as apSecond_ } from './Apply' import * as chainable from './Chain' import { FromIO2, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { ask as ask_, asks as asks_, FromReader2, fromReaderK as fromReaderK_, tapReader as tapReader_ } from './FromReader' import { dual, flow, identity, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor2 } from './Functor' import * as _ from './internal' import * as I from './IO' import { IO } from './IO' import { Monad2 } from './Monad' import { MonadIO2 } from './MonadIO' import { Pointed2 } from './Pointed' import * as R from './Reader' import { Reader } from './Reader' import * as RT from './ReaderT' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' /** * @category model * @since 2.13.0 */ export interface ReaderIO { (r: R): I.IO } // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.13.0 */ export const fromReader: (fa: Reader) => ReaderIO = /*#__PURE__*/ RT.fromReader(I.Pointed) /** * @category conversions * @since 2.13.0 */ export const fromIO: (fa: IO) => ReaderIO = R.of // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s * `contramap`). * * @since 2.13.0 */ export const local: (f: (r2: R2) => R1) => (ma: ReaderIO) => ReaderIO = R.local /** * Less strict version of [`asksReaderIO`](#asksreaderio). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category constructors * @since 2.13.0 */ export const asksReaderIOW: (f: (r1: R1) => ReaderIO) => ReaderIO = R.asksReaderW /** * Effectfully accesses the environment. * * @category constructors * @since 2.13.0 */ export const asksReaderIO: (f: (r: R) => ReaderIO) => ReaderIO = asksReaderIOW const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) const _ap: Apply2['ap'] = (fab, fa) => pipe(fab, ap(fa)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.13.0 */ export const map: (f: (a: A) => B) => (fa: ReaderIO) => ReaderIO = /*#__PURE__*/ RT.map(I.Functor) /** * @since 2.13.0 */ export const ap: (fa: ReaderIO) => (fab: ReaderIO B>) => ReaderIO = /*#__PURE__*/ RT.ap(I.Apply) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.13.0 */ export const apW: (fa: ReaderIO) => (fab: ReaderIO B>) => ReaderIO = ap as any /** * @category constructors * @since 2.13.0 */ export const of: (a: A) => ReaderIO = /*#__PURE__*/ RT.of(I.Pointed) /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => ReaderIO): (ma: ReaderIO) => ReaderIO (ma: ReaderIO, f: (a: A) => ReaderIO): ReaderIO } = /*#__PURE__*/ dual(2, RT.flatMap(I.Monad)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category sequencing * @since 2.13.0 */ export const flattenW: (mma: ReaderIO>) => ReaderIO = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.13.0 */ export const flatten: (mma: ReaderIO>) => ReaderIO = flattenW /** * @category type lambdas * @since 2.13.0 */ export const URI = 'ReaderIO' /** * @category type lambdas * @since 2.13.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: ReaderIO } } /** * @category instances * @since 2.13.0 */ export const Functor: Functor2 = { URI, map: _map } /** * Maps the value to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: ReaderIO) => ReaderIO (self: ReaderIO, a: A): ReaderIO } = dual(2, as_(Functor)) /** * Maps the value to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: ReaderIO) => ReaderIO = asUnit_(Functor) /** * @category mapping * @since 2.13.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.13.0 */ export const Pointed: Pointed2 = { URI, of } /** * @category instances * @since 2.13.0 */ export const Apply: Apply2 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.13.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.13.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.13.0 */ export const Applicative: Applicative2 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.13.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.13.0 */ export const Monad: Monad2 = { URI, map: _map, of, ap: _ap, chain: flatMap } /** * @category instances * @since 2.13.0 */ export const MonadIO: MonadIO2 = { URI, map: _map, of, ap: _ap, chain: flatMap, fromIO } /** * @category instances * @since 2.13.0 */ export const FromIO: FromIO2 = { URI, fromIO } /** * @category instances * @since 2.13.0 */ export const FromReader: FromReader2 = { URI, fromReader } /** @internal */ interface ReaderIOTypeLambda extends _.TypeLambda { readonly type: ReaderIO } /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** @internal */ const _FromIO: _.FromIO = { fromIO: FromIO.fromIO } /** @internal */ const _FromReader: _.FromReader = { fromReader } /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => IO): ReaderIO } = _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReader: { (f: (a: A) => Reader): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => Reader): ReaderIO } = /*#__PURE__*/ _.flatMapReader(_FromReader, _FlatMap) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: ReaderIO, f: (a: A) => ReaderIO): ReaderIO (f: (a: A) => ReaderIO): (self: ReaderIO) => ReaderIO } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as RIO from 'fp-ts/ReaderIO' * import * as Console from 'fp-ts/Console' * * // Will produce `Hello, fp-ts` to the stdout * const effect = pipe( * RIO.ask(), * RIO.tapIO((value) => Console.log(`Hello, ${value}`)), * ) * * async function test() { * assert.deepStrictEqual(effect('fp-ts')(), 'fp-ts') * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => IO<_>): ReaderIO } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReader: { (f: (a: A) => Reader): (self: ReaderIO) => ReaderIO (self: ReaderIO, f: (a: A) => Reader): ReaderIO } = /*#__PURE__*/ dual(2, tapReader_(FromReader, Chain)) /** * @category lifting * @since 2.13.0 */ export const fromIOK: , B>( f: (...a: A) => I.IO ) => (...a: A) => ReaderIO = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.13.0 */ export const chainIOK: (f: (a: A) => I.IO) => (first: ReaderIO) => ReaderIO = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.13.0 */ export const chainFirstIOK: (f: (a: A) => I.IO) => (first: ReaderIO) => ReaderIO = tapIO /** * Reads the current context. * * @category constructors * @since 2.13.0 */ export const ask = /*#__PURE__*/ ask_(FromReader) /** * Projects a value from the global context in a `ReaderIO`. * * @category constructors * @since 2.13.0 */ export const asks = /*#__PURE__*/ asks_(FromReader) /** * @category lifting * @since 2.13.0 */ export const fromReaderK: , R, B>( f: (...a: A) => R.Reader ) => (...a: A) => ReaderIO = /*#__PURE__*/ fromReaderK_(FromReader) /** * Alias of `flatMapReader`. * * @category legacy * @since 2.13.0 */ export const chainReaderK: (f: (a: A) => R.Reader) => (ma: ReaderIO) => ReaderIO = flatMapReader /** * Alias of `flatMapReader`. * * Less strict version of [`chainReaderK`](#chainreaderk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.13.0 */ export const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderIO) => ReaderIO = flatMapReader /** * Alias of `tapReader`. * * @category legacy * @since 2.13.0 */ export const chainFirstReaderK: (f: (a: A) => R.Reader) => (ma: ReaderIO) => ReaderIO = tapReader /** * Alias of `tapReader`. * * Less strict version of [`chainFirstReaderK`](#chainfirstreaderk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.13.0 */ export const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderIO) => ReaderIO = tapReader // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.13.0 */ export const Do: ReaderIO = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.13.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) /** * @category do notation * @since 2.13.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category do notation * @since 2.13.0 */ export const bindW: ( name: Exclude, f: (a: A) => ReaderIO ) => (fa: ReaderIO) => ReaderIO = bind as any /** * @category do notation * @since 2.13.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category do notation * @since 2.13.0 */ export const apSW: ( name: Exclude, fb: ReaderIO ) => (fa: ReaderIO) => ReaderIO = apS as any /** * @since 2.13.0 */ export const ApT: ReaderIO = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.13.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => ReaderIO ): ((as: ReadonlyNonEmptyArray) => ReaderIO>) => flow(R.traverseReadonlyNonEmptyArrayWithIndex(f), R.map(I.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.13.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => ReaderIO ): ((as: ReadonlyArray) => ReaderIO>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.13.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderIO ) => (as: ReadonlyArray) => ReaderIO> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.13.0 */ export const traverseArray = ( f: (a: A) => ReaderIO ): ((as: ReadonlyArray) => ReaderIO>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.13.0 */ export const sequenceArray: (arr: ReadonlyArray>) => ReaderIO> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.13.0 */ export const chain: (f: (a: A) => ReaderIO) => (ma: ReaderIO) => ReaderIO = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.13.0 */ export const chainW: (f: (a: A) => ReaderIO) => (ma: ReaderIO) => ReaderIO = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.13.0 */ export const chainFirst: (f: (a: A) => ReaderIO) => (first: ReaderIO) => ReaderIO = tap /** * Alias of `tap`. * * @category legacy * @since 2.13.0 */ export const chainFirstW: ( f: (a: A) => ReaderIO ) => (ma: ReaderIO) => ReaderIO = tap ================================================ FILE: src/ReaderT.ts ================================================ /** * The reader monad transformer, which adds a read-only environment to the given monad. * * The `of` function ignores the environment, while `chain` passes the inherited environment to both subcomputations. * * @since 2.0.0 */ import { Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C, Apply4 } from './Apply' import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4 } from './Chain' import { flow, pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4 } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3 } from './Monad' import { NaturalTransformation, NaturalTransformation11, NaturalTransformation12, NaturalTransformation22, NaturalTransformation23R, NaturalTransformation24S } from './NaturalTransformation' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C, Pointed4 } from './Pointed' import { Reader } from './Reader' /** * @since 2.10.0 */ export function of(F: Pointed4): (a: A) => Reader> export function of(F: Pointed3): (a: A) => Reader> export function of(F: Pointed3C): (a: A) => Reader> export function of(F: Pointed2): (a: A) => Reader> export function of(F: Pointed2C): (a: A) => Reader> export function of(F: Pointed1): (a: A) => Reader> export function of(F: Pointed): (a: A) => Reader> export function of(F: Pointed): (a: A) => Reader> { return (a) => () => F.of(a) } /** * @since 2.10.0 */ export function map( F: Functor4 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map( F: Functor3 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map( F: Functor3C ): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map( F: Functor2 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map( F: Functor2C ): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map( F: Functor1 ): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map(F: Functor): (f: (a: A) => B) => (fa: Reader>) => Reader> export function map(F: Functor): (f: (a: A) => B) => (fa: Reader>) => Reader> { return (f) => (fa) => (r) => F.map(fa(r), f) } /** * @since 2.10.0 */ export function ap( F: Apply4 ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export function ap( F: Apply3 ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export function ap( F: Apply3C ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export function ap( F: Apply2 ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export function ap( F: Apply2C ): ( fa: Reader> ) => (fab: Reader B>>) => Reader> export function ap( F: Apply1 ): (fa: Reader>) => (fab: Reader B>>) => Reader> export function ap( F: Apply ): (fa: Reader>) => (fab: Reader B>>) => Reader> export function ap( F: Apply ): (fa: Reader>) => (fab: Reader B>>) => Reader> { return (fa) => (fab) => (r) => F.ap(fab(r), fa(r)) } /** * @since 2.10.0 */ export function chain( M: Chain4 ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export function chain( M: Chain3 ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export function chain( M: Chain3C ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export function chain( M: Chain2 ): ( f: (a: A) => Reader> ) => (ma: Reader>) => Reader> export function chain( M: Chain2C ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> export function chain( M: Chain1 ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> export function chain( M: Chain ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> export function chain( M: Chain ): (f: (a: A) => Reader>) => (ma: Reader>) => Reader> { const flatMapM = flatMap(M) return (f) => (ma) => flatMapM(ma, f) } /** @internal */ export function flatMap( M: Chain1 ): (ma: Reader>, f: (a: A) => Reader>) => Reader> /** @internal */ export function flatMap( M: Chain ): (ma: Reader>, f: (a: A) => Reader>) => Reader> /** @internal */ export function flatMap( M: Chain ): (ma: Reader>, f: (a: A) => Reader>) => Reader> { return (ma, f) => (r) => M.chain(ma(r), (a) => f(a)(r)) } /** * @since 2.10.0 */ export function fromReader( F: Pointed4 ): (ma: Reader) => Reader> export function fromReader( F: Pointed3 ): (ma: Reader) => Reader> export function fromReader( F: Pointed3C ): (ma: Reader) => Reader> export function fromReader(F: Pointed2): (ma: Reader) => Reader> export function fromReader( F: Pointed2C ): (ma: Reader) => Reader> export function fromReader(F: Pointed1): (ma: Reader) => Reader> export function fromReader(F: Pointed): (ma: Reader) => Reader> export function fromReader(F: Pointed): (ma: Reader) => Reader> { return (ma) => flow(ma, F.of) } /** * @category constructors * @since 2.11.0 */ export function fromNaturalTransformation( nt: NaturalTransformation24S ): (f: (r: R) => Kind2) => Reader> export function fromNaturalTransformation( nt: NaturalTransformation23R ): (f: (r: R) => Kind2) => Reader> export function fromNaturalTransformation( nt: NaturalTransformation22 ): (f: (r: R) => Kind2) => Reader> export function fromNaturalTransformation( nt: NaturalTransformation12 ): (f: (r: R) => Kind) => Reader> export function fromNaturalTransformation( nt: NaturalTransformation11 ): (f: (r: R) => Kind) => Reader> export function fromNaturalTransformation( nt: NaturalTransformation ): (f: (r: R) => HKT) => Reader> export function fromNaturalTransformation( nt: NaturalTransformation ): (f: (r: R) => HKT) => Reader> { return (f) => flow(f, nt) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderT { (r: R): HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderM { readonly map: (ma: ReaderT, f: (a: A) => B) => ReaderT readonly of: (a: A) => ReaderT readonly ap: (mab: ReaderT B>, ma: ReaderT) => ReaderT readonly chain: (ma: ReaderT, f: (a: A) => ReaderT) => ReaderT readonly ask: () => ReaderT readonly asks: (f: (r: R) => A) => ReaderT readonly local: (ma: ReaderT, f: (d: R2) => R1) => ReaderT readonly fromReader: (ma: Reader) => ReaderT readonly fromM: (ma: HKT) => ReaderT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderT1 { (r: R): Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderM1 { readonly map: (ma: ReaderT1, f: (a: A) => B) => ReaderT1 readonly of: (a: A) => ReaderT1 readonly ap: (mab: ReaderT1 B>, ma: ReaderT1) => ReaderT1 readonly chain: (ma: ReaderT1, f: (a: A) => ReaderT1) => ReaderT1 readonly ask: () => ReaderT1 readonly asks: (f: (r: R) => A) => ReaderT1 readonly local: (ma: ReaderT1, f: (d: R2) => R1) => ReaderT1 readonly fromReader: (ma: Reader) => ReaderT1 readonly fromM: (ma: Kind) => ReaderT1 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderT2 { (r: R): Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderM2 { readonly map: (ma: ReaderT2, f: (a: A) => B) => ReaderT2 readonly of: (a: A) => ReaderT2 readonly ap: (mab: ReaderT2 B>, ma: ReaderT2) => ReaderT2 readonly chain: (ma: ReaderT2, f: (a: A) => ReaderT2) => ReaderT2 readonly ask: () => ReaderT2 readonly asks: (f: (r: R) => A) => ReaderT2 readonly local: (ma: ReaderT2, f: (d: R2) => R1) => ReaderT2 readonly fromReader: (ma: Reader) => ReaderT2 readonly fromM: (ma: Kind2) => ReaderT2 } /** * @category zone of death * @since 2.2.0 * @deprecated */ export interface ReaderM2C { readonly map: (ma: ReaderT2, f: (a: A) => B) => ReaderT2 readonly of: (a: A) => ReaderT2 readonly ap: (mab: ReaderT2 B>, ma: ReaderT2) => ReaderT2 readonly chain: (ma: ReaderT2, f: (a: A) => ReaderT2) => ReaderT2 readonly ask: () => ReaderT2 readonly asks: (f: (r: R) => A) => ReaderT2 readonly local: (ma: ReaderT2, f: (d: R2) => R1) => ReaderT2 readonly fromReader: (ma: Reader) => ReaderT2 readonly fromM: (ma: Kind2) => ReaderT2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderT3 { (r: R): Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ReaderM3 { readonly map: (ma: ReaderT3, f: (a: A) => B) => ReaderT3 readonly of: (a: A) => ReaderT3 readonly ap: ( mab: ReaderT3 B>, ma: ReaderT3 ) => ReaderT3 readonly chain: ( ma: ReaderT3, f: (a: A) => ReaderT3 ) => ReaderT3 readonly ask: () => ReaderT3 readonly asks: (f: (r: R) => A) => ReaderT3 readonly local: (ma: ReaderT3, f: (d: R2) => R1) => ReaderT3 readonly fromReader: (ma: Reader) => ReaderT3 readonly fromM: (ma: Kind3) => ReaderT3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export function getReaderM(M: Monad3): ReaderM3 /** @deprecated */ export function getReaderM(M: Monad2): ReaderM2 /** @deprecated */ export function getReaderM(M: Monad2C): ReaderM2C /** @deprecated */ export function getReaderM(M: Monad1): ReaderM1 /** @deprecated */ export function getReaderM(M: Monad): ReaderM /** @deprecated */ /* istanbul ignore next */ export function getReaderM(M: Monad): ReaderM { const _ap = ap(M) const _map = map(M) const _chain = chain(M) return { map: (fa, f) => pipe(fa, _map(f)), ap: (fab, fa) => pipe(fab, _ap(fa)), of: of(M), chain: (ma, f) => pipe(ma, _chain(f)), ask: () => M.of, asks: (f) => flow(f, M.of), local: (ma, f) => (q) => ma(f(q)), fromReader: fromReader(M), fromM: (ma) => () => ma } } ================================================ FILE: src/ReaderTask.ts ================================================ /** * @since 2.3.0 */ import { Applicative2, getApplicativeMonoid } from './Applicative' import { apFirst as apFirst_, Apply2, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import * as chainable from './Chain' import { FromIO2, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { ask as ask_, asks as asks_, FromReader2, fromReaderK as fromReaderK_, tapReader as tapReader_ } from './FromReader' import { FromTask2, fromTaskK as fromTaskK_, tapTask as tapTask_ } from './FromTask' import { dual, flow, identity, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor2, let as let__ } from './Functor' import * as _ from './internal' import { IO } from './IO' import { Monad2 } from './Monad' import { MonadIO2 } from './MonadIO' import { MonadTask2 } from './MonadTask' import { Monoid } from './Monoid' import { Pointed2 } from './Pointed' import * as R from './Reader' import * as RIO from './ReaderIO' import * as RT from './ReaderT' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Semigroup } from './Semigroup' import * as T from './Task' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- import ReaderIO = RIO.ReaderIO import Task = T.Task /** * @category model * @since 2.3.0 */ export interface ReaderTask { (r: R): Task } // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.3.0 */ export const fromReader: (fa: R.Reader) => ReaderTask = /*#__PURE__*/ RT.fromReader(T.Pointed) /** * @category conversions * @since 2.3.0 */ export const fromTask: (fa: Task) => ReaderTask = R.of /** * @category conversions * @since 2.3.0 */ export const fromIO: (fa: IO) => ReaderTask = /*#__PURE__*/ flow(T.fromIO, fromTask) /** * @category conversions * @since 2.13.0 */ export const fromReaderIO: (fa: ReaderIO) => ReaderTask = R.map(T.fromIO) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s * `contramap`). * * @since 2.3.0 */ export const local: (f: (r2: R2) => R1) => (ma: ReaderTask) => ReaderTask = R.local /** * Less strict version of [`asksReaderTask`](#asksreadertask). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category constructors * @since 2.11.0 */ export const asksReaderTaskW: (f: (r1: R1) => ReaderTask) => ReaderTask = R.asksReaderW /** * Effectfully accesses the environment. * * @category constructors * @since 2.11.0 */ export const asksReaderTask: (f: (r: R) => ReaderTask) => ReaderTask = asksReaderTaskW const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) const _apPar: Apply2['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _apSeq: Apply2['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.3.0 */ export const map: (f: (a: A) => B) => (fa: ReaderTask) => ReaderTask = /*#__PURE__*/ RT.map( T.Functor ) /** * @since 2.3.0 */ export const ap: (fa: ReaderTask) => (fab: ReaderTask B>) => ReaderTask = /*#__PURE__*/ RT.ap(T.ApplyPar) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.8.0 */ export const apW: ( fa: ReaderTask ) => (fab: ReaderTask B>) => ReaderTask = ap as any /** * @category constructors * @since 2.3.0 */ export const of: (a: A) => ReaderTask = /*#__PURE__*/ RT.of(T.Pointed) /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => ReaderTask): (ma: ReaderTask) => ReaderTask (ma: ReaderTask, f: (a: A) => ReaderTask): ReaderTask } = /*#__PURE__*/ dual(2, RT.flatMap(T.Monad)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: (mma: ReaderTask>) => ReaderTask = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.3.0 */ export const flatten: (mma: ReaderTask>) => ReaderTask = flattenW /** * @category type lambdas * @since 2.3.0 */ export const URI = 'ReaderTask' /** * @category type lambdas * @since 2.3.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: ReaderTask } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * Maps the value to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: ReaderTask) => ReaderTask (self: ReaderTask, a: A): ReaderTask } = dual(2, as_(Functor)) /** * Maps the value to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: ReaderTask) => ReaderTask = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplyPar: Apply2 = { URI, map: _map, ap: _apPar } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.3.0 */ export const apFirst = /*#__PURE__*/ apFirst_(ApplyPar) /** * Less strict version of [`apFirst`](#apfirst). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.16.10 */ export const apFirstW: ( second: ReaderTask ) => (first: ReaderTask) => ReaderTask = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.3.0 */ export const apSecond = /*#__PURE__*/ apSecond_(ApplyPar) /** * Less strict version of [`apSecond`](#apsecond). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @since 2.16.10 */ export const apSecondW: ( second: ReaderTask ) => (first: ReaderTask) => ReaderTask = apSecond as any /** * Runs computations in parallel. * * @category instances * @since 2.7.0 */ export const ApplicativePar: Applicative2 = { URI, map: _map, ap: _apPar, of } /** * Runs computations sequentially. * * @category instances * @since 2.10.0 */ export const ApplySeq: Apply2 = { URI, map: _map, ap: _apSeq } /** * Runs computations sequentially. * * @category instances * @since 2.7.0 */ export const ApplicativeSeq: Applicative2 = { URI, map: _map, ap: _apSeq, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _apPar, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const Monad: Monad2 = { URI, map: _map, of, ap: _apPar, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const MonadIO: MonadIO2 = { URI, map: _map, of, ap: _apPar, chain: flatMap, fromIO } /** * @category instances * @since 2.10.0 */ export const MonadTask: MonadTask2 = { URI, map: _map, of, ap: _apPar, chain: flatMap, fromIO, fromTask } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO2 = { URI, fromIO } /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask2 = { URI, fromIO, fromTask } /** * @category instances * @since 2.11.0 */ export const FromReader: FromReader2 = { URI, fromReader } /** @internal */ interface ReaderTaskTypeLambda extends _.TypeLambda { readonly type: ReaderTask } /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** @internal */ const _FromIO: _.FromIO = { fromIO: FromIO.fromIO } /** @internal */ const _FromTask: _.FromTask = { fromTask } /** @internal */ const _FromReader: _.FromReader = { fromReader } /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => IO): ReaderTask } = _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapTask: { (f: (a: A) => Task): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => Task): ReaderTask } = _.flatMapTask(_FromTask, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReader: { (f: (a: A) => R.Reader): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => R.Reader): ReaderTask } = _.flatMapReader(_FromReader, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReaderIO: { (f: (a: A) => ReaderIO): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => ReaderIO): ReaderTask } = /*#__PURE__*/ dual( 2, (self: ReaderTask, f: (a: A) => ReaderIO): ReaderTask => flatMap(self, fromReaderIOK(f)) ) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: ReaderTask, f: (a: A) => ReaderTask): ReaderTask (f: (a: A) => ReaderTask): (self: ReaderTask) => ReaderTask } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as RT from 'fp-ts/ReaderTask' * import * as Console from 'fp-ts/Console' * * // Will produce `Hello, fp-ts` to the stdout * const effect = pipe( * RT.ask(), * RT.tapIO((value) => Console.log(`Hello, ${value}`)), * ) * * async function test() { * assert.deepStrictEqual(await effect('fp-ts')(), 'fp-ts') * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => IO<_>): ReaderTask } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReader: { (f: (a: A) => R.Reader): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => R.Reader): ReaderTask } = /*#__PURE__*/ dual(2, tapReader_(FromReader, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as RT from 'fp-ts/ReaderTask' * import * as T from 'fp-ts/Task' * * const effect = pipe( * RT.ask(), * RT.tapTask((value) => T.of(value + 1)), * ) * * async function test() { * assert.deepStrictEqual(await effect(1)(), 1) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapTask: { (f: (a: A) => Task<_>): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => Task<_>): ReaderTask } = /*#__PURE__*/ dual(2, tapTask_(FromTask, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReaderIO: { (f: (a: A) => ReaderIO): (self: ReaderTask) => ReaderTask (self: ReaderTask, f: (a: A) => ReaderIO): ReaderTask } = /*#__PURE__*/ dual( 2, (self: ReaderTask, f: (a: A) => ReaderIO): ReaderTask => tap(self, fromReaderIOK(f)) ) /** * @category lifting * @since 2.4.0 */ export const fromIOK: , B>( f: (...a: A) => IO ) => (...a: A) => ReaderTask = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.4.0 */ export const chainIOK: (f: (a: A) => IO) => (first: ReaderTask) => ReaderTask = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: (f: (a: A) => IO) => (first: ReaderTask) => ReaderTask = tapIO /** * Reads the current context. * * @category constructors * @since 2.3.0 */ export const ask = /*#__PURE__*/ ask_(FromReader) /** * Projects a value from the global context in a `ReaderTask`. * * @category constructors * @since 2.3.0 */ export const asks = /*#__PURE__*/ asks_(FromReader) /** * @category lifting * @since 2.11.0 */ export const fromReaderK: , R, B>( f: (...a: A) => R.Reader ) => (...a: A) => ReaderTask = /*#__PURE__*/ fromReaderK_(FromReader) /** * Alias of `flatMapReader`. * * @category legacy * @since 2.11.0 */ export const chainReaderK: (f: (a: A) => R.Reader) => (ma: ReaderTask) => ReaderTask = flatMapReader /** * Alias of `flatMapReader`. * * Less strict version of [`chainReaderK`](#chainreaderk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.11.0 */ export const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTask) => ReaderTask = flatMapReader /** * Alias of `tapReader`. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderK: (f: (a: A) => R.Reader) => (ma: ReaderTask) => ReaderTask = tapReader /** * Alias of `tapReader`. * * Less strict version of [`chainFirstReaderK`](#chainfirstreaderk). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTask) => ReaderTask = tapReader /** * @category lifting * @since 2.13.0 */ export const fromReaderIOK = , R, B>(f: (...a: A) => ReaderIO): ((...a: A) => ReaderTask) => (...a) => fromReaderIO(f(...a)) /** * Alias of `flatMapReaderIO`. * * Less strict version of [`chainReaderIOK`](#chainreaderiok). * * @category legacy * @since 2.13.0 */ export const chainReaderIOKW: ( f: (a: A) => ReaderIO ) => (ma: ReaderTask) => ReaderTask = flatMapReaderIO /** * Alias of `flatMapReaderIO`. * * @category legacy * @since 2.13.0 */ export const chainReaderIOK: (f: (a: A) => ReaderIO) => (ma: ReaderTask) => ReaderTask = flatMapReaderIO /** * Alias of `tapReaderIO`. * * Less strict version of [`chainFirstReaderIOK`](#chainfirstreaderiok). * * @category legacy * @since 2.13.0 */ export const chainFirstReaderIOKW: ( f: (a: A) => ReaderIO ) => (ma: ReaderTask) => ReaderTask = tapReaderIO /** * Alias of `tapReaderIO`. * * @category legacy * @since 2.13.0 */ export const chainFirstReaderIOK: (f: (a: A) => ReaderIO) => (ma: ReaderTask) => ReaderTask = tapReaderIO /** * @category lifting * @since 2.4.0 */ export const fromTaskK: , B>( f: (...a: A) => T.Task ) => (...a: A) => ReaderTask = /*#__PURE__*/ fromTaskK_(FromTask) /** * Alias of `flatMapTask`. * * @category legacy * @since 2.4.0 */ export const chainTaskK: (f: (a: A) => T.Task) => (first: ReaderTask) => ReaderTask = flatMapTask /** * Alias of `tapTask`. * @category legacy * @since 2.10.0 */ export const chainFirstTaskK: (f: (a: A) => T.Task) => (first: ReaderTask) => ReaderTask = tapTask // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: ReaderTask = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => ReaderTask ) => (fa: ReaderTask) => ReaderTask = bind as any /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(ApplyPar) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: ReaderTask ) => (fa: ReaderTask) => ReaderTask = apS as any /** * @since 2.11.0 */ export const ApT: ReaderTask = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => ReaderTask ): ((as: ReadonlyNonEmptyArray) => ReaderTask>) => flow(R.traverseReadonlyNonEmptyArrayWithIndex(f), R.map(T.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => ReaderTask ): ((as: ReadonlyArray) => ReaderTask>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = ( f: (index: number, a: A) => ReaderTask ): ((as: ReadonlyNonEmptyArray) => ReaderTask>) => flow(R.traverseReadonlyNonEmptyArrayWithIndex(f), R.map(T.traverseReadonlyNonEmptyArrayWithIndexSeq(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = ( f: (index: number, a: A) => ReaderTask ): ((as: ReadonlyArray) => ReaderTask>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderTask ) => (as: ReadonlyArray) => ReaderTask> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => ReaderTask ): ((as: ReadonlyArray) => ReaderTask>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => ReaderTask> = /*#__PURE__*/ traverseArray(identity) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.10.0 */ export const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => ReaderTask ) => (as: ReadonlyArray) => ReaderTask> = traverseReadonlyArrayWithIndexSeq /** * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. * * @category traversing * @since 2.10.0 */ export const traverseSeqArray = ( f: (a: A) => ReaderTask ): ((as: ReadonlyArray) => ReaderTask>) => traverseReadonlyArrayWithIndexSeq((_, a) => f(a)) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.3.0 */ export const chain: (f: (a: A) => ReaderTask) => (ma: ReaderTask) => ReaderTask = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.6.7 */ export const chainW: ( f: (a: A) => ReaderTask ) => (ma: ReaderTask) => ReaderTask = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.3.0 */ export const chainFirst: (f: (a: A) => ReaderTask) => (first: ReaderTask) => ReaderTask = tap /** * Alias of `tap`. * * @category legacy * @since 2.11.0 */ export const chainFirstW: ( f: (a: A) => ReaderTask ) => (ma: ReaderTask) => ReaderTask = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `traverseReadonlyArrayWithIndexSeq` instead. * * @category zone of death * @since 2.10.0 * @deprecated */ export const sequenceSeqArray: (arr: ReadonlyArray>) => ReaderTask> = /*#__PURE__*/ traverseSeqArray(identity) /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RT.Functor` instead of `RT.readerTask` * (where `RT` is from `import RT from 'fp-ts/ReaderTask'`) * * @category zone of death * @since 2.3.0 * @deprecated */ export const readerTask: MonadTask2 = { URI, map: _map, of, ap: _apPar, chain: flatMap, fromIO, fromTask } /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RT.Functor` instead of `RT.readerTaskSeq` * (where `RT` is from `import RT from 'fp-ts/ReaderTask'`) * * @category zone of death * @since 2.3.0 * @deprecated */ export const readerTaskSeq: typeof readerTask = { URI, map: _map, of, ap: _apSeq, chain: flatMap, fromIO, fromTask } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.3.0 * @deprecated */ export const getSemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(ApplySeq) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.3.0 * @deprecated */ export const getMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(ApplicativeSeq) /** * @category zone of death * @since 2.4.0 * @deprecated */ /* istanbul ignore next */ export function run(ma: ReaderTask, r: R): Promise { return ma(r)() } ================================================ FILE: src/ReaderTaskEither.ts ================================================ /** * @since 2.0.0 */ import { Alt3, Alt3C } from './Alt' import { Applicative3, Applicative3C, getApplicativeMonoid } from './Applicative' import { ap as ap_, apFirst as apFirst_, Apply1, Apply3, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import { Bifunctor3 } from './Bifunctor' import * as chainable from './Chain' import { compact as compact_, Compactable3C, separate as separate_ } from './Compactable' import * as E from './Either' import * as ET from './EitherT' import { filter as filter_, Filterable3C, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable' import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, FromEither3, fromEitherK as fromEitherK_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_, tapEither as tapEither_ } from './FromEither' import { FromIO3, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { ask as ask_, asks as asks_, FromReader3, fromReaderK as fromReaderK_, tapReader as tapReader_ } from './FromReader' import { FromTask3, fromTaskK as fromTaskK_, tapTask as tapTask_ } from './FromTask' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor3, let as let__ } from './Functor' import * as _ from './internal' import { IO } from './IO' import { IOEither } from './IOEither' import { Monad3, Monad3C } from './Monad' import { MonadIO3 } from './MonadIO' import { MonadTask3, MonadTask3C } from './MonadTask' import { MonadThrow3, MonadThrow3C } from './MonadThrow' import { Monoid } from './Monoid' import { Option } from './Option' import { Pointed3 } from './Pointed' import { Predicate } from './Predicate' import * as R from './Reader' import { ReaderEither } from './ReaderEither' import * as RIO from './ReaderIO' import * as RT from './ReaderTask' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import * as T from './Task' import * as TE from './TaskEither' import Either = E.Either import Task = T.Task import TaskEither = TE.TaskEither import Reader = R.Reader import ReaderIO = RIO.ReaderIO import ReaderTask = RT.ReaderTask // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface ReaderTaskEither { (r: R): TaskEither } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.0.0 */ export const fromTaskEither: (fa: TaskEither) => ReaderTaskEither = R.of /** * @category constructors * @since 2.0.0 */ export const left: (e: E) => ReaderTaskEither = /*#__PURE__*/ ET.left(RT.Pointed) /** * @category constructors * @since 2.0.0 */ export const right: (a: A) => ReaderTaskEither = /*#__PURE__*/ ET.right(RT.Pointed) /** * @category constructors * @since 2.0.0 */ export const rightTask: (ma: Task) => ReaderTaskEither = /*#__PURE__*/ flow( TE.rightTask, fromTaskEither ) /** * @category constructors * @since 2.0.0 */ export const leftTask: (me: Task) => ReaderTaskEither = /*#__PURE__*/ flow( TE.leftTask, fromTaskEither ) /** * @category constructors * @since 2.0.0 */ export const rightReader: (ma: Reader) => ReaderTaskEither = (ma) => flow(ma, TE.right) /** * @category constructors * @since 2.0.0 */ export const leftReader: (me: Reader) => ReaderTaskEither = (me) => flow(me, TE.left) /** * @category constructors * @since 2.5.0 */ export const rightReaderTask: (ma: ReaderTask) => ReaderTaskEither = /*#__PURE__*/ ET.rightF(RT.Functor) /** * @category constructors * @since 2.5.0 */ export const leftReaderTask: (me: ReaderTask) => ReaderTaskEither = /*#__PURE__*/ ET.leftF(RT.Functor) /** * @category constructors * @since 2.0.0 */ export const rightIO: (ma: IO) => ReaderTaskEither = /*#__PURE__*/ flow( TE.rightIO, fromTaskEither ) /** * @category constructors * @since 2.0.0 */ export const leftIO: (me: IO) => ReaderTaskEither = /*#__PURE__*/ flow( TE.leftIO, fromTaskEither ) /** * @category constructors * @since 2.13.0 */ export const rightReaderIO: (ma: ReaderIO) => ReaderTaskEither = (ma) => flow(ma, TE.rightIO) /** * @category constructors * @since 2.13.0 */ export const leftReaderIO: (me: ReaderIO) => ReaderTaskEither = (me) => flow(me, TE.leftIO) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.0.0 */ export const fromEither: (fa: Either) => ReaderTaskEither = RT.of /** * @category conversions * @since 2.11.0 */ export const fromReader: (fa: Reader) => ReaderTaskEither = rightReader /** * @category conversions * @since 2.0.0 */ export const fromIO: (fa: IO) => ReaderTaskEither = rightIO /** * @category conversions * @since 2.0.0 */ export const fromTask: (fa: Task) => ReaderTaskEither = rightTask /** * @category conversions * @since 2.0.0 */ export const fromIOEither: (fa: IOEither) => ReaderTaskEither = /*#__PURE__*/ flow( TE.fromIOEither, fromTaskEither ) /** * @category conversions * @since 2.0.0 */ export const fromReaderEither: (fa: ReaderEither) => ReaderTaskEither = (ma) => flow(ma, TE.fromEither) /** * @category pattern matching * @since 2.10.0 */ export const match: ( onLeft: (e: E) => B, onRight: (a: A) => B ) => (ma: ReaderTaskEither) => ReaderTask = /*#__PURE__*/ ET.match(RT.Functor) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C ) => (ma: ReaderTaskEither) => ReaderTask = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`ReaderTask`). * * @category pattern matching * @since 2.10.0 */ export const matchE: ( onLeft: (e: E) => ReaderTask, onRight: (a: A) => ReaderTask ) => (ma: ReaderTaskEither) => ReaderTask = /*#__PURE__*/ ET.matchE(RT.Chain) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.0.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchEW: ( onLeft: (e: E) => ReaderTask, onRight: (a: A) => ReaderTask ) => (ma: ReaderTaskEither) => ReaderTask = matchE as any /** * Alias of [`matchEW`](#matchew). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchEW /** * @category error handling * @since 2.0.0 */ export const getOrElse: ( onLeft: (e: E) => ReaderTask ) => (ma: ReaderTaskEither) => ReaderTask = /*#__PURE__*/ ET.getOrElse(RT.Monad) /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.6.0 */ export const getOrElseW: ( onLeft: (e: E) => ReaderTask ) => (ma: ReaderTaskEither) => ReaderTask = getOrElse as any /** * @category conversions * @since 2.10.0 */ export const toUnion: (fa: ReaderTaskEither) => ReaderTask = /*#__PURE__*/ ET.toUnion( RT.Functor ) /** * @category conversions * @since 2.12.0 */ export const fromNullable: (e: E) => (a: A) => ReaderTaskEither> = /*#__PURE__*/ ET.fromNullable(RT.Pointed) /** * Use `liftNullable`. * * @category legacy * @since 2.12.0 */ export const fromNullableK: ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => ReaderTaskEither> = /*#__PURE__*/ ET.fromNullableK(RT.Pointed) /** * Use `flatMapNullable`. * * @category legacy * @since 2.12.0 */ export const chainNullableK: ( e: E ) => ( f: (a: A) => B | null | undefined ) => (ma: ReaderTaskEither) => ReaderTaskEither> = /*#__PURE__*/ ET.chainNullableK( RT.Monad ) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s * `contramap`). * * @since 2.0.0 */ export const local: ( f: (r2: R2) => R1 ) => (ma: ReaderTaskEither) => ReaderTaskEither = R.local /** * Less strict version of [`asksReaderTaskEither`](#asksreadertaskeither). * * The `W` suffix (short for **W**idening) means that the environment types will be merged. * * @category constructors * @since 2.11.0 */ export const asksReaderTaskEitherW: ( f: (r1: R1) => ReaderTaskEither ) => ReaderTaskEither = R.asksReaderW /** * Effectfully accesses the environment. * * @category constructors * @since 2.11.0 */ export const asksReaderTaskEither: (f: (r: R) => ReaderTaskEither) => ReaderTaskEither = asksReaderTaskEitherW /** * @category error handling * @since 2.0.0 */ export const orElse: ( onLeft: (e: E1) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ET.orElse(RT.Monad) /** * Less strict version of [`orElse`](#orelse). * * The `W` suffix (short for **W**idening) means that the environment types and the return types will be merged. * * @category error handling * @since 2.10.0 */ export const orElseW: ( onLeft: (e: E1) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = orElse as any /** * Returns an effect that effectfully "peeks" at the failure of this effect. * * @category error handling * @since 2.15.0 */ export const tapError: { (onLeft: (e: E1) => ReaderTaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither ( self: ReaderTaskEither, onLeft: (e: E1) => ReaderTaskEither ): ReaderTaskEither } = /*#__PURE__*/ dual(2, ET.tapError(RT.Monad)) /** * @category error handling * @since 2.11.0 */ export const orLeft: ( onLeft: (e: E1) => ReaderTask ) => (fa: ReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ET.orLeft(RT.Monad) /** * @category error handling * @since 2.16.6 */ export const orLeftW: ( onLeft: (e: E1) => ReaderTask ) => (fa: ReaderTaskEither) => ReaderTaskEither = orLeft as any /** * @since 2.0.0 */ export const swap: (ma: ReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ET.swap( RT.Functor ) /** * @category lifting * @since 2.4.0 */ export const fromIOEitherK = , B>( f: (...a: A) => IOEither ): ((...a: A) => ReaderTaskEither) => flow(f, fromIOEither) /** * @category lifting * @since 2.4.0 */ export const fromTaskEitherK = , B>( f: (...a: A) => TaskEither ): ((...a: A) => ReaderTaskEither) => flow(f, fromTaskEither) /** * @category lifting * @since 2.11.0 */ export const fromReaderEitherK = , B>( f: (...a: A) => ReaderEither ): ((...a: A) => ReaderTaskEither) => flow(f, fromReaderEither) const _map: Functor3['map'] = (fa, f) => pipe(fa, map(f)) const _apPar: Apply3['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _apSeq: Apply3['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /* istanbul ignore next */ const _alt: Alt3['alt'] = (fa, that) => pipe(fa, alt(that)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: ReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ET.map(RT.Functor) /** * Returns a `ReaderTaskEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. * * @example * import * as ReaderTaskEither from 'fp-ts/ReaderTaskEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * const g = (n: number) => n * 2 * * async function test() { * assert.deepStrictEqual(await ReaderTaskEither.mapBoth(ReaderTaskEither.right(1), f, g)({})(), Either.right(2)) * assert.deepStrictEqual(await ReaderTaskEither.mapBoth(ReaderTaskEither.left('err'), f, g)({})(), Either.left(new Error('err'))) * } * * test() * * @category error handling * @since 2.16.0 */ export const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (e: E) => G, g: (a: A) => B): ReaderTaskEither } = /*#__PURE__*/ dual(3, ET.mapBoth(RT.Functor)) /** * Alias of `mapBoth`. * * @category legacy * @since 2.0.0 */ export const bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: ReaderTaskEither) => ReaderTaskEither = mapBoth /** * Returns a `ReaderTaskEither` with its error channel mapped using the specified function. * * @example * import * as ReaderTaskEither from 'fp-ts/ReaderTaskEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * * async function test() { * assert.deepStrictEqual(await ReaderTaskEither.mapError(ReaderTaskEither.right(1), f)({})(), Either.right(1)) * assert.deepStrictEqual(await ReaderTaskEither.mapError(ReaderTaskEither.left('err'), f)({})(), Either.left(new Error('err'))) * } * * test() * * @category error handling * @since 2.16.0 */ export const mapError: { (f: (e: E) => G): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (e: E) => G): ReaderTaskEither } = /*#__PURE__*/ dual(2, ET.mapError(RT.Functor)) /** * Alias of `mapError`. * * @category legacy * @since 2.0.0 */ export const mapLeft: (f: (e: E) => G) => (fa: ReaderTaskEither) => ReaderTaskEither = mapError /** * @since 2.0.0 */ export const ap: ( fa: ReaderTaskEither ) => (fab: ReaderTaskEither B>) => ReaderTaskEither = /*#__PURE__*/ ET.ap(RT.ApplyPar) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.8.0 */ export const apW: ( fa: ReaderTaskEither ) => (fab: ReaderTaskEither B>) => ReaderTaskEither = ap as any /** * @category constructors * @since 2.7.0 */ export const of: (a: A) => ReaderTaskEither = right /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => ReaderTaskEither): ( ma: ReaderTaskEither ) => ReaderTaskEither (ma: ReaderTaskEither, f: (a: A) => ReaderTaskEither): ReaderTaskEither< R1 & R2, E1 | E2, B > } = /*#__PURE__*/ dual(2, ET.flatMap(RT.Monad)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: ( mma: ReaderTaskEither> ) => ReaderTaskEither = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: ReaderTaskEither>) => ReaderTaskEither = flattenW /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * @category error handling * @since 2.0.0 */ export const alt: ( that: () => ReaderTaskEither ) => (fa: ReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ET.alt(RT.Monad) /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the environment, the error and the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW: ( that: () => ReaderTaskEither ) => (fa: ReaderTaskEither) => ReaderTaskEither = alt as any /** * @since 2.0.0 */ export const throwError: MonadThrow3['throwError'] = left /** * @category type lambdas * @since 2.0.0 */ export const URI = 'ReaderTaskEither' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind3 { readonly [URI]: ReaderTaskEither } } /** * @category filtering * @since 2.10.0 */ export const getCompactable = (M: Monoid): Compactable3C => { const C = E.getCompactable(M) return { URI, _E: undefined as any, compact: compact_(RT.Functor, C), separate: separate_(RT.Functor, C, E.Functor) } } /** * @category filtering * @since 2.10.0 */ export function getFilterable(M: Monoid): Filterable3C { const F = E.getFilterable(M) const C = getCompactable(M) const filter = filter_(RT.Functor, F) const filterMap = filterMap_(RT.Functor, F) const partition = partition_(RT.Functor, F) const partitionMap = partitionMap_(RT.Functor, F) return { URI, _E: undefined as any, map: _map, compact: C.compact, separate: C.separate, filter: (fa: ReaderTaskEither, predicate: Predicate) => pipe(fa, filter(predicate)), filterMap: (fa, f) => pipe(fa, filterMap(f)), partition: (fa: ReaderTaskEither, predicate: Predicate) => pipe(fa, partition(predicate)), partitionMap: (fa, f) => pipe(fa, partitionMap(f)) } } /** * The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getApplicativeValidation`](./Either.ts.html#getapplicativevalidation). * * @category error handling * @since 2.7.0 */ export function getApplicativeReaderTaskValidation(A: Apply1, S: Semigroup): Applicative3C { const ap = ap_(R.Apply, TE.getApplicativeTaskValidation(A, S)) return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => pipe(fab, ap(fa)), of } } /** * The default [`Alt`](#alt) instance returns the last error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getAltValidation`](./Either.ts.html#getaltvalidation). * * @category error handling * @since 2.7.0 */ export function getAltReaderTaskValidation(S: Semigroup): Alt3C { const alt = ET.altValidation(RT.Monad, S) return { URI, _E: undefined as any, map: _map, alt: (fa, that) => pipe(fa, alt(that)) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor3 = { URI, map: _map } /** * Maps the `Right` value of this `ReaderTaskEither` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, a: A): ReaderTaskEither } = dual(2, as_(Functor)) /** * Maps the `Right` value of this `ReaderTaskEither` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: ReaderTaskEither) => ReaderTaskEither = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed3 = { URI, of } /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplyPar: Apply3 = { URI, map: _map, ap: _apPar } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(ApplyPar) /** * Less strict version of [`apFirst`](#apfirst). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.12.0 */ export const apFirstW: ( second: ReaderTaskEither ) => (first: ReaderTaskEither) => ReaderTaskEither = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(ApplyPar) /** * Less strict version of [`apSecond`](#apsecond). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.12.0 */ export const apSecondW: ( second: ReaderTaskEither ) => (first: ReaderTaskEither) => ReaderTaskEither = apSecond as any /** * Runs computations in parallel. * * @category instances * @since 2.7.0 */ export const ApplicativePar: Applicative3 = { URI, map: _map, ap: _apPar, of } /** * Runs computations sequentially. * * @category instances * @since 2.10.0 */ export const ApplySeq: Apply3 = { URI, map: _map, ap: _apSeq } /** * Runs computations sequentially. * * @category instances * @since 2.7.0 */ export const ApplicativeSeq: Applicative3 = { URI, map: _map, ap: _apSeq, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain3 = { URI, map: _map, ap: _apPar, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const Monad: Monad3 = { URI, map: _map, ap: _apPar, chain: flatMap, of } /** * @category instances * @since 2.10.0 */ export const MonadIO: MonadIO3 = { URI, map: _map, ap: _apPar, chain: flatMap, of, fromIO } /** * @category instances * @since 2.10.0 */ export const MonadTask: MonadTask3 = { URI, map: _map, ap: _apPar, chain: flatMap, of, fromIO, fromTask } /** * @category instances * @since 2.10.0 */ export const MonadThrow: MonadThrow3 = { URI, map: _map, ap: _apPar, chain: flatMap, of, throwError } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither3 = { URI, fromEither } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO3 = { URI, fromIO } /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask3 = { URI, fromIO, fromTask } /** * @category instances * @since 2.11.0 */ export const FromReader: FromReader3 = { URI, fromReader } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: ReaderTaskEither, f: (a: A) => ReaderTaskEither): ReaderTaskEither< R1 & R2, E1 | E2, A > (f: (a: A) => ReaderTaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as RTE from 'fp-ts/ReaderTaskEither' * * const checkString = (value: string) => pipe( * RTE.ask(), * RTE.tapEither((minLength) => value.length > minLength ? E.right('ok') : E.left('error')) * ) * * async function test() { * assert.deepStrictEqual(await checkString('')(2)(), E.left('error')) * assert.deepStrictEqual(await checkString('fp-ts')(2)(), E.right(2)) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Either): ReaderTaskEither } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as RTE from 'fp-ts/ReaderTaskEither' * import * as E from 'fp-ts/Either' * import * as Console from 'fp-ts/Console' * * * // Will produce `Hello, fp-ts` to the stdout * const effect = RTE.tapIO( * RTE.ask(), * (value) => Console.log(`Hello, ${value}`) * ) * * async function test() { * assert.deepStrictEqual(await effect('fp-ts')(), E.of('fp-ts')) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => IO<_>): ReaderTaskEither } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as RTE from 'fp-ts/ReaderTaskEither' * import * as E from 'fp-ts/Either' * import * as T from 'fp-ts/Task' * * * const effect = RTE.tapTask( * RTE.ask(), * (value) => T.of(value + 1) * ) * * async function test() { * assert.deepStrictEqual(await effect(1)(), E.of(1)) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapTask: { (f: (a: A) => Task<_>): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Task<_>): ReaderTaskEither } = /*#__PURE__*/ dual(2, tapTask_(FromTask, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReader: { (f: (a: A) => Reader): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Reader): ReaderTaskEither } = /*#__PURE__*/ dual(2, tapReader_(FromReader, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReaderEither: { (f: (a: A) => ReaderEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderEither): ReaderTaskEither< R1 & R2, E1 | E2, A > } = /*#__PURE__*/ dual( 2, ( self: ReaderTaskEither, f: (a: A) => ReaderEither ): ReaderTaskEither => tap(self, fromReaderEitherK(f)) ) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapTaskEither: { (f: (a: A) => TaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => TaskEither): ReaderTaskEither } = /*#__PURE__*/ dual( 2, ( self: ReaderTaskEither, f: (a: A) => TaskEither ): ReaderTaskEither => tap(self, fromTaskEitherK(f)) ) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReaderTask: { (f: (a: A) => ReaderTask): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderTask): ReaderTaskEither } = /*#__PURE__*/ dual( 2, ( self: ReaderTaskEither, f: (a: A) => ReaderTask ): ReaderTaskEither => tap(self, fromReaderTaskK(f)) ) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReaderIO: { (f: (a: A) => ReaderIO): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderIO): ReaderTaskEither } = /*#__PURE__*/ dual( 2, (self: ReaderTaskEither, f: (a: A) => ReaderIO): ReaderTaskEither => tap(self, fromReaderIOK(f)) ) /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor3 = { URI, bimap: mapBoth, mapLeft: mapError } /** * @category instances * @since 2.7.0 */ export const Alt: Alt3 = { URI, map: _map, alt: _alt } /** * Reads the current context. * * @category constructors * @since 2.0.0 */ export const ask: () => ReaderTaskEither = /*#__PURE__*/ ask_(FromReader) /** * Projects a value from the global context in a `ReaderEither`. * * @category constructors * @since 2.0.0 */ export const asks: (f: (r: R) => A) => ReaderTaskEither = /*#__PURE__*/ asks_(FromReader) /** * @category lifting * @since 2.11.0 */ export const fromReaderK: , R, B>( f: (...a: A) => Reader ) => (...a: A) => ReaderTaskEither = /*#__PURE__*/ fromReaderK_(FromReader) /** * Alias of `tapReader`. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderK: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReader /** * Alias of `tapReader`. * * Less strict version of [`chainFirstReaderK`](#chainfirstreaderk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReader /** * Alias of `tapReaderEither`. * * Less strict version of [`chainFirstReaderEitherK`](#chainfirstreadereitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderEitherKW: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReaderEither /** * Alias of `tapReaderEither`. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderEitherK: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReaderEither /** * Alias of `tapTaskEither`. * * Less strict version of [`chainFirstTaskEitherK`](#chainfirsttaskeitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstTaskEitherKW: ( f: (a: A) => TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapTaskEither /** * Alias of `tapTaskEither`. * * @category legacy * @since 2.11.0 */ export const chainFirstTaskEitherK: ( f: (a: A) => TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapTaskEither /** * @category lifting * @since 2.11.0 */ export const fromReaderTaskK = , R, B>( f: (...a: A) => ReaderTask ): ((...a: A) => ReaderTaskEither) => (...a) => rightReaderTask(f(...a)) /** * Alias of `tapReaderTask`. * * Less strict version of [`chainFirstReaderTaskK`](#chainfirstreadertaskk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderTaskKW: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReaderTask /** * Alias of `tapReaderTask`. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderTaskK: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReaderTask /** * @category lifting * @since 2.13.0 */ export const fromReaderIOK = , R, B>( f: (...a: A) => ReaderIO ): ((...a: A) => ReaderTaskEither) => (...a) => rightReaderIO(f(...a)) /** * Alias of `tapReaderIO`. * * Less strict version of [`chainFirstReaderIOK`](#chainfirstreaderiok). * * @category legacy * @since 2.13.0 */ export const chainFirstReaderIOKW: ( f: (a: A) => ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReaderIO /** * Alias of `tapReaderIO`. * * @category legacy * @since 2.13.0 */ export const chainFirstReaderIOK: ( f: (a: A) => ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapReaderIO /** * @category conversions * @since 2.0.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => ReaderTaskEither = /*#__PURE__*/ fromOption_(FromEither) /** * Use `liftOption`. * * @category legacy * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>( f: (...a: A) => Option ) => (...a: A) => ReaderTaskEither = /*#__PURE__*/ fromOptionK_(FromEither) /** * Use `flatMapOption`. * * @category legacy * @since 2.10.0 */ export const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ chainOptionK_(FromEither, Chain) /** * Use `flatMapOption`. * * @category legacy * @since 2.13.2 */ export const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: ReaderTaskEither) => ReaderTaskEither = chainOptionK as any /** @internal */ interface ReaderTaskEitherTypeLambda extends _.TypeLambda { readonly type: ReaderTaskEither } /** @internal */ const _FromEither: _.FromEither = { fromEither: FromEither.fromEither } /** * @category lifting * @since 2.15.0 */ export const liftNullable: , B, E>( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => ReaderTaskEither> = /*#__PURE__*/ _.liftNullable(_FromEither) /** * @category lifting * @since 2.15.0 */ export const liftOption: , B, E>( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => ReaderTaskEither = /*#__PURE__*/ _.liftOption(_FromEither) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** @internal */ const _FromIO: _.FromIO = { fromIO } /** @internal */ const _FromTask: _.FromTask = { fromTask } /** @internal */ const _FromReader: _.FromReader = { fromReader } /** * @category sequencing * @since 2.15.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: ReaderTaskEither ) => ReaderTaskEither> ( self: ReaderTaskEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2 ): ReaderTaskEither> } = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Option, onNone: (a: A) => E2): ReaderTaskEither< R, E1 | E2, B > } = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapEither: { (f: (a: A) => E.Either): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => E.Either): ReaderTaskEither } = /*#__PURE__*/ _.flatMapEither(_FromEither, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapTaskEither: { (f: (a: A) => TaskEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => TaskEither): ReaderTaskEither } = /*#__PURE__*/ dual( 2, ( self: ReaderTaskEither, f: (a: A) => TaskEither ): ReaderTaskEither => flatMap(self, fromTaskEitherK(f)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapReaderTask: { (f: (a: A) => ReaderTask): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderTask): ReaderTaskEither } = /*#__PURE__*/ dual( 2, ( self: ReaderTaskEither, f: (a: A) => ReaderTask ): ReaderTaskEither => flatMap(self, fromReaderTaskK(f)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => IO): ReaderTaskEither } = /*#__PURE__*/ _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapTask: { (f: (a: A) => Task): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Task): ReaderTaskEither } = /*#__PURE__*/ _.flatMapTask(_FromTask, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReader: { (f: (a: A) => Reader): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => Reader): ReaderTaskEither } = /*#__PURE__*/ _.flatMapReader(_FromReader, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReaderIO: { (f: (a: A) => ReaderIO): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderIO): ReaderTaskEither } = /*#__PURE__*/ dual( 2, (self: ReaderTaskEither, f: (a: A) => ReaderIO): ReaderTaskEither => flatMap(self, fromReaderIOK(f)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapIOEither: { (f: (a: A) => IOEither): (self: ReaderTaskEither) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => IOEither): ReaderTaskEither } = /*#__PURE__*/ dual( 2, (self: ReaderTaskEither, f: (a: A) => IOEither): ReaderTaskEither => flatMap(self, fromIOEitherK(f)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapReaderEither: { (f: (a: A) => ReaderEither): ( self: ReaderTaskEither ) => ReaderTaskEither (self: ReaderTaskEither, f: (a: A) => ReaderEither): ReaderTaskEither< R1 & R2, E1 | E2, B > } = /*#__PURE__*/ dual( 2, ( self: ReaderTaskEither, f: (a: A) => ReaderEither ): ReaderTaskEither => flatMap(self, fromReaderEitherK(f)) ) /** * Alias of `flatMapEither`. * * @category legacy * @since 2.4.0 */ export const chainEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapEither /** * Alias of `flatMapEither`. * * @category legacy * @since 2.6.1 */ export const chainEitherKW: ( f: (a: A) => Either ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapEither /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapEither /** * Alias of `tapEither`. * * Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherKW: ( f: (a: A) => Either ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapEither /** * Alias of `flatMapTaskEither`. * * Less strict version of [`chainTaskEitherK`](#chaintaskeitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.6.1 */ export const chainTaskEitherKW: ( f: (a: A) => TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapTaskEither /** * Alias of `flatMapTaskEither`. * * @category legacy * @since 2.4.0 */ export const chainTaskEitherK: ( f: (a: A) => TaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapTaskEither /** * Alias of `flatMapReaderTask`. * * Less strict version of [`chainReaderTaskK`](#chainreadertaskk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainReaderTaskKW: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReaderTask /** * Alias of `flatMapReaderTask`. * * @category legacy * @since 2.11.0 */ export const chainReaderTaskK: ( f: (a: A) => RT.ReaderTask ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReaderTask /** * @category lifting * @since 2.0.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): ( a: A ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( b: B ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => ReaderTaskEither } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category filtering * @since 2.0.0 */ export const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( mb: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): (ma: ReaderTaskEither) => ReaderTaskEither } = /*#__PURE__*/ filterOrElse_(FromEither, Chain) /** * Less strict version of [`filterOrElse`](#filterorelse). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category filtering * @since 2.9.0 */ export const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: ReaderTaskEither ) => ReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( ma: ReaderTaskEither ) => ReaderTaskEither } = filterOrElse /** * @category lifting * @since 2.4.0 */ export const fromEitherK: , B>( f: (...a: A) => E.Either ) => (...a: A) => ReaderTaskEither = /*#__PURE__*/ fromEitherK_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromIOK: , B>( f: (...a: A) => IO ) => (...a: A) => ReaderTaskEither = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.10.0 */ export const chainIOK: ( f: (a: A) => IO ) => (first: ReaderTaskEither) => ReaderTaskEither = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: ( f: (a: A) => IO ) => (first: ReaderTaskEither) => ReaderTaskEither = tapIO /** * @category lifting * @since 2.10.0 */ export const fromTaskK: , B>( f: (...a: A) => T.Task ) => (...a: A) => ReaderTaskEither = /*#__PURE__*/ fromTaskK_(FromTask) /** * Alias of `flatMapTask`. * * @category legacy * @since 2.10.0 */ export const chainTaskK: ( f: (a: A) => T.Task ) => (first: ReaderTaskEither) => ReaderTaskEither = flatMapTask /** * Alias of `tapTask`. * @category legacy * @since 2.10.0 */ export const chainFirstTaskK: ( f: (a: A) => T.Task ) => (first: ReaderTaskEither) => ReaderTaskEither = tapTask /** * Alias of `flatMapReader`. * * @category legacy * @since 2.11.0 */ export const chainReaderK: ( f: (a: A) => Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReader /** * Alias of `flatMapReader`. * * Less strict version of [`chainReaderK`](#chainreaderk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainReaderKW: ( f: (a: A) => R.Reader ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReader /** * Alias of `flatMapReaderIO`. * * Less strict version of [`chainReaderIOK`](#chainreaderiok). * * @category legacy * @since 2.13.0 */ export const chainReaderIOKW: ( f: (a: A) => ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReaderIO /** * Alias of `flatMapReaderIO`. * * @category legacy * @since 2.13.0 */ export const chainReaderIOK: ( f: (a: A) => ReaderIO ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReaderIO /** * Alias of `flatMapIOEither`. * * Less strict version of [`chainIOEitherK`](#chainioeitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.6.1 */ export const chainIOEitherKW: ( f: (a: A) => IOEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapIOEither /** * Alias of `flatMapIOEither`. * * @category legacy * @since 2.4.0 */ export const chainIOEitherK: ( f: (a: A) => IOEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapIOEither /** * Alias of `flatMapReaderEither`. * * Less strict version of [`chainReaderEitherK`](#chainreadereitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainReaderEitherKW: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReaderEither /** * Alias of `flatMapReaderEither`. * * @category legacy * @since 2.11.0 */ export const chainReaderEitherK: ( f: (a: A) => ReaderEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMapReaderEither // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of * whether the body action throws (\*) or returns. * * (\*) i.e. returns a `Left` * * @since 2.0.4 */ export function bracket( acquire: ReaderTaskEither, use: (a: A) => ReaderTaskEither, release: (a: A, e: Either) => ReaderTaskEither ): ReaderTaskEither { return bracketW(acquire, use, release) } /** * Less strict version of [`bracket`](#bracket). * * @since 2.12.0 */ export function bracketW( acquire: ReaderTaskEither, use: (a: A) => ReaderTaskEither, release: (a: A, e: Either) => ReaderTaskEither ): ReaderTaskEither { return (r) => TE.bracketW( acquire(r), (a) => use(a)(r), (a, e) => release(a, e)(r) ) } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: ReaderTaskEither = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => ReaderTaskEither ) => ( fa: ReaderTaskEither ) => ReaderTaskEither = bind as any /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(ApplyPar) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: ReaderTaskEither ) => ( fa: ReaderTaskEither ) => ReaderTaskEither = apS as any /** * @since 2.11.0 */ export const ApT: ReaderTaskEither = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => ReaderTaskEither ): ((as: ReadonlyNonEmptyArray) => ReaderTaskEither>) => flow(R.traverseReadonlyNonEmptyArrayWithIndex(f), R.map(TE.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => ReaderTaskEither ): ((as: ReadonlyArray) => ReaderTaskEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = ( f: (index: number, a: A) => ReaderTaskEither ): ((as: ReadonlyNonEmptyArray) => ReaderTaskEither>) => flow(R.traverseReadonlyNonEmptyArrayWithIndex(f), R.map(TE.traverseReadonlyNonEmptyArrayWithIndexSeq(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = ( f: (index: number, a: A) => ReaderTaskEither ): ((as: ReadonlyArray) => ReaderTaskEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: ReadonlyArray) => ReaderTaskEither> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => ReaderTaskEither ): ((as: ReadonlyArray) => ReaderTaskEither>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: ( arr: ReadonlyArray> ) => ReaderTaskEither> = /*#__PURE__*/ traverseArray(identity) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => ReaderTaskEither ) => (as: ReadonlyArray) => ReaderTaskEither> = traverseReadonlyArrayWithIndexSeq /** * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArray = ( f: (a: A) => ReaderTaskEither ): ((as: ReadonlyArray) => ReaderTaskEither>) => traverseReadonlyArrayWithIndexSeq((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const sequenceSeqArray: ( arr: ReadonlyArray> ) => ReaderTaskEither> = /*#__PURE__*/ traverseSeqArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tap /** * Alias of `tap`. * * @category legacy * @since 2.8.0 */ export const chainFirstW: ( f: (a: A) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tap /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirst: ( onLeft: (e: E) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapError /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirstW: ( onLeft: (e: E1) => ReaderTaskEither ) => (ma: ReaderTaskEither) => ReaderTaskEither = tapError // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RTE.Functor` instead of `RTE.readerTaskEither` * (where `RTE` is from `import RTE from 'fp-ts/ReaderTaskEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const readerTaskEither: Monad3 & Bifunctor3 & Alt3 & MonadTask3 & MonadThrow3 = { URI, map: _map, of, ap: _apPar, chain: flatMap, alt: _alt, bimap: mapBoth, mapLeft: mapError, fromIO, fromTask, throwError } /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RTE.Functor` instead of `RTE.readerTaskEitherSeq` * (where `RTE` is from `import RTE from 'fp-ts/ReaderTaskEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const readerTaskEitherSeq: typeof readerTaskEither = { URI, map: _map, of, ap: _apSeq, chain: flatMap, alt: _alt, bimap: mapBoth, mapLeft: mapError, fromIO, fromTask, throwError } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values * are concatenated using the provided `Semigroup` * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplySemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(ApplySeq) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplyMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(ApplicativeSeq) /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup = (S: Semigroup): Semigroup> => getApplySemigroup_(RT.ApplySeq)(E.getSemigroup(S)) /** * Use [`getApplicativeReaderTaskValidation`](#getapplicativereadertaskvalidation) and [`getAltReaderTaskValidation`](#getaltreadertaskvalidation) instead. * * @category instances * @since 2.3.0 * @deprecated */ export function getReaderTaskValidation( SE: Semigroup ): Monad3C & Bifunctor3 & Alt3C & MonadTask3C & MonadThrow3C { const applicativeReaderTaskValidation = getApplicativeReaderTaskValidation(T.ApplicativePar, SE) const altReaderTaskValidation = getAltReaderTaskValidation(SE) return { URI, _E: undefined as any, map: _map, of, chain: flatMap, bimap: mapBoth, mapLeft: mapError, ap: applicativeReaderTaskValidation.ap, alt: altReaderTaskValidation.alt, fromIO, fromTask, throwError } } /** * @category zone of death * @since 2.0.0 * @deprecated */ /* istanbul ignore next */ export function run(ma: ReaderTaskEither, r: R): Promise> { return ma(r)() } ================================================ FILE: src/ReadonlyArray.ts ================================================ /** * @since 2.5.0 */ import { Alt1 } from './Alt' import { Alternative1 } from './Alternative' import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain' import { ChainRec1 } from './ChainRec' import { Compactable1 } from './Compactable' import { Either } from './Either' import { Eq, fromEquals } from './Eq' import { Extend1 } from './Extend' import { Filterable1 } from './Filterable' import { FilterableWithIndex1, PredicateWithIndex, RefinementWithIndex } from './FilterableWithIndex' import { Foldable1 } from './Foldable' import { FoldableWithIndex1 } from './FoldableWithIndex' import { FromEither1, fromEitherK as fromEitherK_ } from './FromEither' import { dual, identity, LazyArg, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { FunctorWithIndex1 } from './FunctorWithIndex' import { HKT } from './HKT' import * as _ from './internal' import { Magma } from './Magma' import { Monad1 } from './Monad' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import * as N from './number' import { Option } from './Option' import { fromCompare, Ord } from './Ord' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import * as RNEA from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' import { PipeableTraverseWithIndex1, TraversableWithIndex1 } from './TraversableWithIndex' import { Unfoldable1 } from './Unfoldable' import { filterE as filterE_, PipeableWilt1, PipeableWither1, wiltDefault, Witherable1, witherDefault } from './Witherable' import { guard as guard_, Zero1 } from './Zero' import ReadonlyNonEmptyArray = RNEA.ReadonlyNonEmptyArray // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * Test whether a `ReadonlyArray` is empty. * * @example * import { isEmpty } from 'fp-ts/ReadonlyArray' * * assert.strictEqual(isEmpty([]), true) * * @category refinements * @since 2.5.0 */ export const isEmpty = (as: ReadonlyArray): as is readonly [] => as.length === 0 /** * Test whether a `ReadonlyArray` is non empty. * * @category refinements * @since 2.5.0 */ export const isNonEmpty: (as: ReadonlyArray) => as is ReadonlyNonEmptyArray = RNEA.isNonEmpty // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Prepend an element to the front of a `ReadonlyArray`, creating a new `ReadonlyNonEmptyArray`. * * @example * import { prepend } from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([2, 3, 4], prepend(1)), [1, 2, 3, 4]) * * @since 2.10.0 */ export const prepend = RNEA.prepend /** * Less strict version of [`prepend`](#prepend). * * @since 2.11.0 */ export const prependW = RNEA.prependW /** * Append an element to the end of a `ReadonlyArray`, creating a new `ReadonlyNonEmptyArray`. * * @example * import { append } from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], append(4)), [1, 2, 3, 4]) * * @since 2.10.0 */ export const append = RNEA.append /** * Less strict version of [`append`](#append). * * @since 2.11.0 */ export const appendW = RNEA.appendW /** * Return a `ReadonlyArray` of length `n` with element `i` initialized with `f(i)`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { makeBy } from 'fp-ts/ReadonlyArray' * * const double = (n: number): number => n * 2 * assert.deepStrictEqual(makeBy(5, double), [0, 2, 4, 6, 8]) * * @category constructors * @since 2.5.0 */ export const makeBy = (n: number, f: (i: number) => A): ReadonlyArray => (n <= 0 ? empty : RNEA.makeBy(f)(n)) /** * Create a `ReadonlyArray` containing a value repeated the specified number of times. * * **Note**. `n` is normalized to a non negative integer. * * @example * import { replicate } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(replicate(3, 'a'), ['a', 'a', 'a']) * * @category constructors * @since 2.5.0 */ export const replicate = (n: number, a: A): ReadonlyArray => makeBy(n, () => a) /** * @category lifting * @since 2.11.0 */ export function fromPredicate(refinement: Refinement): (a: A) => ReadonlyArray export function fromPredicate(predicate: Predicate): (b: B) => ReadonlyArray export function fromPredicate(predicate: Predicate): (a: A) => ReadonlyArray export function fromPredicate(predicate: Predicate): (a: A) => ReadonlyArray { return (a) => (predicate(a) ? [a] : empty) } // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.11.0 */ export const fromOption: (fa: Option) => ReadonlyArray = (ma) => (_.isNone(ma) ? empty : [ma.value]) /** * Transforms an `Either` to a `ReadonlyArray`. * * @category conversions * @since 2.11.0 */ export const fromEither: (fa: Either) => ReadonlyArray = (e) => (_.isLeft(e) ? empty : [e.right]) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.11.0 */ export const matchW = (onEmpty: LazyArg, onNonEmpty: (as: ReadonlyNonEmptyArray) => C) => (as: ReadonlyArray): B | C => isNonEmpty(as) ? onNonEmpty(as) : onEmpty() /** * @category pattern matching * @since 2.11.0 */ export const match: ( onEmpty: LazyArg, onNonEmpty: (as: ReadonlyNonEmptyArray) => B ) => (as: ReadonlyArray) => B = matchW /** * Less strict version of [`matchLeft`](#matchleft). * * @category pattern matching * @since 2.11.0 */ export const matchLeftW = (onEmpty: LazyArg, onNonEmpty: (head: A, tail: ReadonlyArray) => C) => (as: ReadonlyArray): B | C => isNonEmpty(as) ? onNonEmpty(RNEA.head(as), RNEA.tail(as)) : onEmpty() /** * Break a `ReadonlyArray` into its first element and remaining elements. * * @example * import { matchLeft } from 'fp-ts/ReadonlyArray' * * const len: (as: ReadonlyArray) => number = matchLeft(() => 0, (_, tail) => 1 + len(tail)) * assert.strictEqual(len([1, 2, 3]), 3) * * @category pattern matching * @since 2.10.0 */ export const matchLeft: ( onEmpty: LazyArg, onNonEmpty: (head: A, tail: ReadonlyArray) => B ) => (as: ReadonlyArray) => B = matchLeftW /** * Alias of [`matchLeft`](#matchleft). * * @category pattern matching * @since 2.5.0 */ export const foldLeft: ( onEmpty: LazyArg, onNonEmpty: (head: A, tail: ReadonlyArray) => B ) => (as: ReadonlyArray) => B = matchLeft /** * Less strict version of [`matchRight`](#matchright). * * @category pattern matching * @since 2.11.0 */ export const matchRightW = (onEmpty: LazyArg, onNonEmpty: (init: ReadonlyArray, last: A) => C) => (as: ReadonlyArray): B | C => isNonEmpty(as) ? onNonEmpty(RNEA.init(as), RNEA.last(as)) : onEmpty() /** * Break a `ReadonlyArray` into its initial elements and the last element. * * @category pattern matching * @since 2.10.0 */ export const matchRight: ( onEmpty: LazyArg, onNonEmpty: (init: ReadonlyArray, last: A) => B ) => (as: ReadonlyArray) => B = matchRightW /** * Alias of [`matchRight`](#matchright). * * @category pattern matching * @since 2.5.0 */ export const foldRight: ( onEmpty: LazyArg, onNonEmpty: (init: ReadonlyArray, last: A) => B ) => (as: ReadonlyArray) => B = matchRight // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category sequencing * @since 2.7.0 */ export const chainWithIndex = (f: (i: number, a: A) => ReadonlyArray) => (as: ReadonlyArray): ReadonlyArray => { if (isEmpty(as)) { return empty } const out: Array = [] for (let i = 0; i < as.length; i++) { const bs = f(i, as[i]) for (let j = 0; j < bs.length; j++) { out.push(bs[j]) } } return out } /** * Same as `reduce` but it carries over the intermediate steps. * * @example * import { scanLeft } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(scanLeft(10, (b, a: number) => b - a)([1, 2, 3]), [10, 9, 7, 4]) * * @since 2.5.0 */ export const scanLeft = (b: B, f: (b: B, a: A) => B) => (as: ReadonlyArray): ReadonlyNonEmptyArray => { const len = as.length const out = new Array(len + 1) as NonEmptyArray out[0] = b for (let i = 0; i < len; i++) { out[i + 1] = f(out[i], as[i]) } return out } /** * Fold an array from the right, keeping all intermediate results instead of only the final result * * @example * import { scanRight } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(scanRight(10, (a: number, b) => b - a)([1, 2, 3]), [4, 5, 7, 10]) * * @since 2.5.0 */ export const scanRight = (b: B, f: (a: A, b: B) => B) => (as: ReadonlyArray): ReadonlyNonEmptyArray => { const len = as.length const out = new Array(len + 1) as NonEmptyArray out[len] = b for (let i = len - 1; i >= 0; i--) { out[i] = f(as[i], out[i + 1]) } return out } /** * Calculate the number of elements in a `ReadonlyArray`. * * @since 2.10.0 */ export const size = (as: ReadonlyArray): number => as.length /** * Test whether an array contains a particular index * * @since 2.5.0 */ export const isOutOfBound: (i: number, as: ReadonlyArray) => boolean = RNEA.isOutOfBound // TODO: remove non-curried overloading in v3 /** * This function provides a safe way to read a value at a particular index from an array * * @example * import { lookup } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], lookup(1)), some(2)) * assert.deepStrictEqual(pipe([1, 2, 3], lookup(3)), none) * * @since 2.5.0 */ export function lookup(i: number): (as: ReadonlyArray) => Option export function lookup(i: number, as: ReadonlyArray): Option export function lookup(i: number, as?: ReadonlyArray): Option | ((as: ReadonlyArray) => Option) { return as === undefined ? (as) => lookup(i, as) : isOutOfBound(i, as) ? _.none : _.some(as[i]) } /** * Get the first element in an array, or `None` if the array is empty * * @example * import { head } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(head([1, 2, 3]), some(1)) * assert.deepStrictEqual(head([]), none) * * @since 2.5.0 */ export const head = (as: ReadonlyArray): Option => (isNonEmpty(as) ? _.some(RNEA.head(as)) : _.none) /** * Get the last element in an array, or `None` if the array is empty * * @example * import { last } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(last([1, 2, 3]), some(3)) * assert.deepStrictEqual(last([]), none) * * @since 2.5.0 */ export const last = (as: ReadonlyArray): Option => (isNonEmpty(as) ? _.some(RNEA.last(as)) : _.none) /** * Get all but the first element of an array, creating a new array, or `None` if the array is empty * * @example * import { tail } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(tail([1, 2, 3]), some([2, 3])) * assert.deepStrictEqual(tail([]), none) * * @since 2.5.0 */ export const tail = (as: ReadonlyArray): Option> => isNonEmpty(as) ? _.some(RNEA.tail(as)) : _.none /** * Get all but the last element of an array, creating a new array, or `None` if the array is empty * * @example * import { init } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(init([1, 2, 3]), some([1, 2])) * assert.deepStrictEqual(init([]), none) * * @since 2.5.0 */ export const init = (as: ReadonlyArray): Option> => isNonEmpty(as) ? _.some(RNEA.init(as)) : _.none /** * Keep only a max number of elements from the start of an `ReadonlyArray`, creating a new `ReadonlyArray`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * const input: ReadonlyArray = [1, 2, 3] * assert.deepStrictEqual(pipe(input, RA.takeLeft(2)), [1, 2]) * * // out of bounds * assert.strictEqual(pipe(input, RA.takeLeft(4)), input) * assert.strictEqual(pipe(input, RA.takeLeft(-1)), input) * * @since 2.5.0 */ export const takeLeft = (n: number) => (as: ReadonlyArray): ReadonlyArray => isOutOfBound(n, as) ? as : n === 0 ? empty : as.slice(0, n) /** * Keep only a max number of elements from the end of an `ReadonlyArray`, creating a new `ReadonlyArray`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * const input: ReadonlyArray = [1, 2, 3] * assert.deepStrictEqual(pipe(input, RA.takeRight(2)), [2, 3]) * * // out of bounds * assert.strictEqual(pipe(input, RA.takeRight(4)), input) * assert.strictEqual(pipe(input, RA.takeRight(-1)), input) * * @since 2.5.0 */ export const takeRight = (n: number) => (as: ReadonlyArray): ReadonlyArray => isOutOfBound(n, as) ? as : n === 0 ? empty : as.slice(-n) /** * Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new array * * @example * import { takeLeftWhile } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(takeLeftWhile((n: number) => n % 2 === 0)([2, 4, 3, 6]), [2, 4]) * * @since 2.5.0 */ export function takeLeftWhile(refinement: Refinement): (as: ReadonlyArray) => ReadonlyArray export function takeLeftWhile(predicate: Predicate): (bs: ReadonlyArray) => ReadonlyArray export function takeLeftWhile(predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray export function takeLeftWhile(predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray { return (as: ReadonlyArray) => { const out: Array = [] for (const a of as) { if (!predicate(a)) { break } out.push(a) } const len = out.length return len === as.length ? as : len === 0 ? empty : out } } /** * @since 2.5.0 */ export interface Spanned { readonly init: ReadonlyArray readonly rest: ReadonlyArray } const spanLeftIndex = (as: ReadonlyArray, predicate: Predicate): number => { const l = as.length let i = 0 for (; i < l; i++) { if (!predicate(as[i])) { break } } return i } /** * Split an array into two parts: * 1. the longest initial subarray for which all elements satisfy the specified predicate * 2. the remaining elements * * @example * import { spanLeft } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(spanLeft((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] }) * * @since 2.5.0 */ export function spanLeft(refinement: Refinement): (as: ReadonlyArray) => Spanned export function spanLeft(predicate: Predicate): (bs: ReadonlyArray) => Spanned export function spanLeft(predicate: Predicate): (as: ReadonlyArray) => Spanned export function spanLeft(predicate: Predicate): (as: ReadonlyArray) => Spanned { return (as) => { const [init, rest] = splitAt(spanLeftIndex(as, predicate))(as) return { init, rest } } } /** * Drop a max number of elements from the start of an `ReadonlyArray`, creating a new `ReadonlyArray`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * const input: ReadonlyArray = [1, 2, 3] * assert.deepStrictEqual(pipe(input, RA.dropLeft(2)), [3]) * assert.strictEqual(pipe(input, RA.dropLeft(0)), input) * assert.strictEqual(pipe(input, RA.dropLeft(-1)), input) * * @since 2.5.0 */ export const dropLeft = (n: number) => (as: ReadonlyArray): ReadonlyArray => n <= 0 || isEmpty(as) ? as : n >= as.length ? empty : as.slice(n, as.length) /** * Drop a max number of elements from the end of an `ReadonlyArray`, creating a new `ReadonlyArray`. * * **Note**. `n` is normalized to a non negative integer. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * const input: ReadonlyArray = [1, 2, 3] * assert.deepStrictEqual(pipe(input, RA.dropRight(2)), [1]) * assert.strictEqual(pipe(input, RA.dropRight(0)), input) * assert.strictEqual(pipe(input, RA.dropRight(-1)), input) * * @since 2.5.0 */ export const dropRight = (n: number) => (as: ReadonlyArray): ReadonlyArray => n <= 0 || isEmpty(as) ? as : n >= as.length ? empty : as.slice(0, as.length - n) /** * Remove the longest initial subarray for which all element satisfy the specified predicate, creating a new array * * @example * import { dropLeftWhile } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(dropLeftWhile((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), [2, 4, 5]) * * @since 2.5.0 */ export function dropLeftWhile(refinement: Refinement): (as: ReadonlyArray) => ReadonlyArray export function dropLeftWhile(predicate: Predicate): (bs: ReadonlyArray) => ReadonlyArray export function dropLeftWhile(predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray export function dropLeftWhile(predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray { return (as) => { const i = spanLeftIndex(as, predicate) return i === 0 ? as : i === as.length ? empty : as.slice(i) } } /** * Find the first index for which a predicate holds * * @example * import { findIndex } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(findIndex((n: number) => n === 2)([1, 2, 3]), some(1)) * assert.deepStrictEqual(findIndex((n: number) => n === 2)([]), none) * * @since 2.5.0 */ export const findIndex = (predicate: Predicate) => (as: ReadonlyArray): Option => { for (let i = 0; i < as.length; i++) { if (predicate(as[i])) { return _.some(i) } } return _.none } /** * Find the first element which satisfies a predicate (or a refinement) function * * @example * import { findFirst } from 'fp-ts/ReadonlyArray' * import { some } from 'fp-ts/Option' * * type X = { * readonly a: number * readonly b: number * } * * assert.deepStrictEqual(findFirst((x: X) => x.a === 1)([{ a: 1, b: 1 }, { a: 1, b: 2 }]), some({ a: 1, b: 1 })) * * @since 2.5.0 */ export function findFirst(refinement: Refinement): (as: ReadonlyArray) => Option export function findFirst(predicate: Predicate): (bs: ReadonlyArray) => Option export function findFirst(predicate: Predicate): (as: ReadonlyArray) => Option export function findFirst(predicate: Predicate): (as: ReadonlyArray) => Option { return (as) => { for (let i = 0; i < as.length; i++) { if (predicate(as[i])) { return _.some(as[i]) } } return _.none } } /** * Find the first element returned by an option based selector function * * @example * import { findFirstMap } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * interface Person { * readonly name: string * readonly age?: number * } * * const persons: ReadonlyArray = [{ name: 'John' }, { name: 'Mary', age: 45 }, { name: 'Joey', age: 28 }] * * // returns the name of the first person that has an age * assert.deepStrictEqual(findFirstMap((p: Person) => (p.age === undefined ? none : some(p.name)))(persons), some('Mary')) * * @since 2.5.0 */ export const findFirstMap = (f: (a: A) => Option) => (as: ReadonlyArray): Option => { for (let i = 0; i < as.length; i++) { const out = f(as[i]) if (_.isSome(out)) { return out } } return _.none } /** * Find the last element which satisfies a predicate function * * @example * import { findLast } from 'fp-ts/ReadonlyArray' * import { some } from 'fp-ts/Option' * * type X = { * readonly a: number * readonly b: number * } * * assert.deepStrictEqual(findLast((x: X) => x.a === 1)([{ a: 1, b: 1 }, { a: 1, b: 2 }]), some({ a: 1, b: 2 })) * * @since 2.5.0 */ export function findLast(refinement: Refinement): (as: ReadonlyArray) => Option export function findLast(predicate: Predicate): (bs: ReadonlyArray) => Option export function findLast(predicate: Predicate): (as: ReadonlyArray) => Option export function findLast(predicate: Predicate): (as: ReadonlyArray) => Option { return (as) => { for (let i = as.length - 1; i >= 0; i--) { if (predicate(as[i])) { return _.some(as[i]) } } return _.none } } /** * Find the last element returned by an option based selector function * * @example * import { findLastMap } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * interface Person { * readonly name: string * readonly age?: number * } * * const persons: ReadonlyArray = [{ name: 'John' }, { name: 'Mary', age: 45 }, { name: 'Joey', age: 28 }] * * // returns the name of the last person that has an age * assert.deepStrictEqual(findLastMap((p: Person) => (p.age === undefined ? none : some(p.name)))(persons), some('Joey')) * * @since 2.5.0 */ export const findLastMap = (f: (a: A) => Option) => (as: ReadonlyArray): Option => { for (let i = as.length - 1; i >= 0; i--) { const out = f(as[i]) if (_.isSome(out)) { return out } } return _.none } /** * Returns the index of the last element of the list which matches the predicate * * @example * import { findLastIndex } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * interface X { * readonly a: number * readonly b: number * } * const xs: ReadonlyArray = [{ a: 1, b: 0 }, { a: 1, b: 1 }] * assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 1)(xs), some(1)) * assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 4)(xs), none) * * * @since 2.5.0 */ export const findLastIndex = (predicate: Predicate) => (as: ReadonlyArray): Option => { for (let i = as.length - 1; i >= 0; i--) { if (predicate(as[i])) { return _.some(i) } } return _.none } /** * Insert an element at the specified index, creating a new array, or returning `None` if the index is out of bounds * * @example * import { insertAt } from 'fp-ts/ReadonlyArray' * import { some } from 'fp-ts/Option' * * assert.deepStrictEqual(insertAt(2, 5)([1, 2, 3, 4]), some([1, 2, 5, 3, 4])) * * @since 2.5.0 */ export const insertAt = (i: number, a: A) => (as: ReadonlyArray): Option> => i < 0 || i > as.length ? _.none : _.some(RNEA.unsafeInsertAt(i, a, as)) /** * Change the element at the specified index, creating a new array, or returning `None` if the index is out of bounds * * @example * import { updateAt } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(updateAt(1, 1)([1, 2, 3]), some([1, 1, 3])) * assert.deepStrictEqual(updateAt(1, 1)([]), none) * * @since 2.5.0 */ export const updateAt = (i: number, a: A): ((as: ReadonlyArray) => Option>) => modifyAt(i, () => a) /** * Delete the element at the specified index, creating a new array, or returning `None` if the index is out of bounds * * @example * import { deleteAt } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * assert.deepStrictEqual(deleteAt(0)([1, 2, 3]), some([2, 3])) * assert.deepStrictEqual(deleteAt(1)([]), none) * * @since 2.5.0 */ export const deleteAt = (i: number) => (as: ReadonlyArray): Option> => isOutOfBound(i, as) ? _.none : _.some(unsafeDeleteAt(i, as)) /** * Apply a function to the element at the specified index, creating a new array, or returning `None` if the index is out * of bounds * * @example * import { modifyAt } from 'fp-ts/ReadonlyArray' * import { some, none } from 'fp-ts/Option' * * const double = (x: number): number => x * 2 * assert.deepStrictEqual(modifyAt(1, double)([1, 2, 3]), some([1, 4, 3])) * assert.deepStrictEqual(modifyAt(1, double)([]), none) * * @since 2.5.0 */ export const modifyAt = (i: number, f: (a: A) => A) => (as: ReadonlyArray): Option> => isOutOfBound(i, as) ? _.none : _.some(unsafeUpdateAt(i, f(as[i]), as)) /** * Reverse an array, creating a new array * * @example * import { reverse } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(reverse([1, 2, 3]), [3, 2, 1]) * * @since 2.5.0 */ export const reverse = (as: ReadonlyArray): ReadonlyArray => (as.length <= 1 ? as : as.slice().reverse()) /** * Extracts from an array of `Either` all the `Right` elements. All the `Right` elements are extracted in order * * @example * import { rights } from 'fp-ts/ReadonlyArray' * import { right, left } from 'fp-ts/Either' * * assert.deepStrictEqual(rights([right(1), left('foo'), right(2)]), [1, 2]) * * @since 2.5.0 */ export const rights = (as: ReadonlyArray>): ReadonlyArray => { const r: Array = [] for (let i = 0; i < as.length; i++) { const a = as[i] if (a._tag === 'Right') { r.push(a.right) } } return r } /** * Extracts from an array of `Either` all the `Left` elements. All the `Left` elements are extracted in order * * @example * import { lefts } from 'fp-ts/ReadonlyArray' * import { left, right } from 'fp-ts/Either' * * assert.deepStrictEqual(lefts([right(1), left('foo'), right(2)]), ['foo']) * * @since 2.5.0 */ export const lefts = (as: ReadonlyArray>): ReadonlyArray => { const r: Array = [] for (let i = 0; i < as.length; i++) { const a = as[i] if (a._tag === 'Left') { r.push(a.left) } } return r } /** * Sort the elements of an array in increasing order, creating a new array * * @example * import { sort } from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(sort(N.Ord)([3, 2, 1]), [1, 2, 3]) * * @since 2.5.0 */ export const sort = (O: Ord) => (as: ReadonlyArray): ReadonlyArray => as.length <= 1 ? as : as.slice().sort(O.compare) // TODO: curry and make data-last in v3 /** * Apply a function to pairs of elements at the same index in two arrays, collecting the results in a new array. If one * input array is short, excess elements of the longer array are discarded. * * @example * import { zipWith } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3']) * * @since 2.5.0 */ export const zipWith = ( fa: ReadonlyArray, fb: ReadonlyArray, f: (a: A, b: B) => C ): ReadonlyArray => { const fc: Array = [] const len = Math.min(fa.length, fb.length) for (let i = 0; i < len; i++) { fc[i] = f(fa[i], fb[i]) } return fc } // TODO: remove non-curried overloading in v3 /** * Takes two arrays and returns an array of corresponding pairs. If one input array is short, excess elements of the * longer array are discarded * * @example * import { zip } from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2, 3], zip(['a', 'b', 'c', 'd'])), [[1, 'a'], [2, 'b'], [3, 'c']]) * * @since 2.5.0 */ export function zip(bs: ReadonlyArray): (as: ReadonlyArray) => ReadonlyArray export function zip(as: ReadonlyArray, bs: ReadonlyArray): ReadonlyArray export function zip( as: ReadonlyArray, bs?: ReadonlyArray ): ReadonlyArray | ((bs: ReadonlyArray) => ReadonlyArray) { if (bs === undefined) { return (bs) => zip(bs, as) } return zipWith(as, bs, (a, b) => [a, b]) } /** * The function is reverse of `zip`. Takes an array of pairs and return two corresponding arrays * * @example * import { unzip } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(unzip([[1, 'a'], [2, 'b'], [3, 'c']]), [[1, 2, 3], ['a', 'b', 'c']]) * * @since 2.5.0 */ export const unzip = (as: ReadonlyArray): readonly [ReadonlyArray, ReadonlyArray] => { const fa: Array = [] const fb: Array = [] for (let i = 0; i < as.length; i++) { fa[i] = as[i][0] fb[i] = as[i][1] } return [fa, fb] } /** * Prepend an element to every member of an array * * @example * import { prependAll } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) * * @since 2.10.0 */ export const prependAll = (middle: A): ((as: ReadonlyArray) => ReadonlyArray) => { const f = RNEA.prependAll(middle) return (as) => (isNonEmpty(as) ? f(as) : as) } /** * Places an element in between members of an array * * @example * import { intersperse } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) * * @since 2.9.0 */ export const intersperse = (middle: A): ((as: ReadonlyArray) => ReadonlyArray) => { const f = RNEA.intersperse(middle) return (as) => (isNonEmpty(as) ? f(as) : as) } /** * Rotate a `ReadonlyArray` by `n` steps. * * @example * import { rotate } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) * * @since 2.5.0 */ export const rotate = (n: number): ((as: ReadonlyArray) => ReadonlyArray) => { const f = RNEA.rotate(n) return (as) => (isNonEmpty(as) ? f(as) : as) } // TODO: remove non-curried overloading in v3 /** * Test if a value is a member of an array. Takes a `Eq` as a single * argument which returns the function to use to search for a value of type `A` in * an array of type `ReadonlyArray`. * * @example * import { elem } from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(2)), true) * assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(0)), false) * * @since 2.5.0 */ export function elem(E: Eq): { (a: A): (as: ReadonlyArray) => boolean (a: A, as: ReadonlyArray): boolean } export function elem(E: Eq): (a: A, as?: ReadonlyArray) => boolean | ((as: ReadonlyArray) => boolean) { return (a, as?) => { if (as === undefined) { const elemE = elem(E) return (as) => elemE(a, as) } const predicate = (element: A) => E.equals(element, a) let i = 0 for (; i < as.length; i++) { if (predicate(as[i])) { return true } } return false } } /** * Remove duplicates from an array, keeping the first occurrence of an element. * * @example * import { uniq } from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) * * @since 2.5.0 */ export const uniq = (E: Eq): ((as: ReadonlyArray) => ReadonlyArray) => { const f = RNEA.uniq(E) return (as) => (isNonEmpty(as) ? f(as) : as) } /** * Sort the elements of an array in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, * etc... * * @example * import { sortBy } from 'fp-ts/ReadonlyArray' * import { contramap } from 'fp-ts/Ord' * import * as S from 'fp-ts/string' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * interface Person { * readonly name: string * readonly age: number * } * const byName = pipe(S.Ord, contramap((p: Person) => p.name)) * const byAge = pipe(N.Ord, contramap((p: Person) => p.age)) * * const sortByNameByAge = sortBy([byName, byAge]) * * const persons = [{ name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 }] * assert.deepStrictEqual(sortByNameByAge(persons), [ * { name: 'a', age: 1 }, * { name: 'b', age: 2 }, * { name: 'b', age: 3 }, * { name: 'c', age: 2 } * ]) * * @since 2.5.0 */ export const sortBy = (ords: ReadonlyArray>): ((as: ReadonlyArray) => ReadonlyArray) => { const f = RNEA.sortBy(ords) return (as) => (isNonEmpty(as) ? f(as) : as) } /** * A useful recursion pattern for processing a `ReadonlyArray` to produce a new `ReadonlyArray`, often used for "chopping" up the input * `ReadonlyArray`. Typically `chop` is called with some function that will consume an initial prefix of the `ReadonlyArray` and produce a * value and the tail of the `ReadonlyArray`. * * @example * import { Eq } from 'fp-ts/Eq' * import * as RA from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * const group = (S: Eq): ((as: ReadonlyArray) => ReadonlyArray>) => { * return RA.chop(as => { * const { init, rest } = pipe(as, RA.spanLeft((a: A) => S.equals(a, as[0]))) * return [init, rest] * }) * } * assert.deepStrictEqual(group(N.Eq)([1, 1, 2, 3, 3, 4]), [[1, 1], [2], [3, 3], [4]]) * * @since 2.5.0 */ export const chop = ( f: (as: ReadonlyNonEmptyArray) => readonly [B, ReadonlyArray] ): ((as: ReadonlyArray) => ReadonlyArray) => { const g = RNEA.chop(f) return (as) => (isNonEmpty(as) ? g(as) : empty) } /** * Splits a `ReadonlyArray` into two pieces, the first piece has max `n` elements. * * @example * import { splitAt } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(splitAt(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4, 5]]) * * @since 2.5.0 */ export const splitAt = (n: number) => (as: ReadonlyArray): readonly [ReadonlyArray, ReadonlyArray] => n >= 1 && isNonEmpty(as) ? RNEA.splitAt(n)(as) : isEmpty(as) ? [as, empty] : [empty, as] /** * Splits a `ReadonlyArray` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the `ReadonlyArray`. Note that `chunksOf(n)([])` is `[]`, not `[[]]`. This is intentional, and is consistent with a recursive * definition of `chunksOf`; it satisfies the property that: * * ```ts * chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys))) * ``` * * whenever `n` evenly divides the length of `as`. * * @example * import { chunksOf } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) * * @since 2.5.0 */ export const chunksOf = (n: number): ((as: ReadonlyArray) => ReadonlyArray>) => { const f = RNEA.chunksOf(n) return (as) => (isNonEmpty(as) ? f(as) : empty) } /** * @category lifting * @since 2.11.0 */ export const fromOptionK = , B>(f: (...a: A) => Option) => (...a: A): ReadonlyArray => fromOption(f(...a)) /** * `ReadonlyArray` comprehension. * * ``` * [ f(x, y, ...) | x ← xs, y ← ys, ..., g(x, y, ...) ] * ``` * * @example * import { comprehension } from 'fp-ts/ReadonlyArray' * import { tuple } from 'fp-ts/function' * * assert.deepStrictEqual(comprehension([[1, 2, 3], ['a', 'b']], tuple, (a, b) => (a + b.length) % 2 === 0), [ * [1, 'a'], * [1, 'b'], * [3, 'a'], * [3, 'b'] * ]) * * @since 2.5.0 */ export function comprehension( input: readonly [ReadonlyArray, ReadonlyArray, ReadonlyArray, ReadonlyArray], f: (a: A, b: B, c: C, d: D) => R, g?: (a: A, b: B, c: C, d: D) => boolean ): ReadonlyArray export function comprehension( input: readonly [ReadonlyArray, ReadonlyArray, ReadonlyArray], f: (a: A, b: B, c: C) => R, g?: (a: A, b: B, c: C) => boolean ): ReadonlyArray export function comprehension( input: readonly [ReadonlyArray, ReadonlyArray], f: (a: A, b: B) => R, g?: (a: A, b: B) => boolean ): ReadonlyArray export function comprehension( input: readonly [ReadonlyArray], f: (a: A) => R, g?: (a: A) => boolean ): ReadonlyArray export function comprehension( input: ReadonlyArray>, f: (...xs: ReadonlyArray) => R, g: (...xs: ReadonlyArray) => boolean = () => true ): ReadonlyArray { const go = (scope: ReadonlyArray, input: ReadonlyArray>): ReadonlyArray => isNonEmpty(input) ? flatMap(RNEA.head(input), (a) => go(pipe(scope, append(a)), RNEA.tail(input))) : g(...scope) ? [f(...scope)] : empty return go(empty, input) } /** * @since 2.11.0 */ export const concatW = (second: ReadonlyArray) => (first: ReadonlyArray): ReadonlyArray => isEmpty(first) ? second : isEmpty(second) ? first : (first as ReadonlyArray).concat(second) /** * @since 2.11.0 */ export const concat: (second: ReadonlyArray) => (first: ReadonlyArray) => ReadonlyArray = concatW // TODO: remove non-curried overloading in v3 /** * Creates an array of unique values, in order, from all given arrays using a `Eq` for equality comparisons * * @example * import { union } from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2], union(N.Eq)([2, 3])), [1, 2, 3]) * * @since 2.5.0 */ export function union(E: Eq): { (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray } export function union( E: Eq ): (xs: ReadonlyArray, ys?: ReadonlyArray) => ReadonlyArray | ((ys: ReadonlyArray) => ReadonlyArray) { const unionE = RNEA.union(E) return (first, second?) => { if (second === undefined) { const unionE = union(E) return (second) => unionE(second, first) } return isNonEmpty(first) && isNonEmpty(second) ? unionE(second)(first) : isNonEmpty(first) ? first : second } } // TODO: remove non-curried overloading in v3 /** * Creates an array of unique values that are included in all given arrays using a `Eq` for equality * comparisons. The order and references of result values are determined by the first array. * * @example * import { intersection } from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2], intersection(N.Eq)([2, 3])), [2]) * * @since 2.5.0 */ export function intersection(E: Eq): { (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray } export function intersection( E: Eq ): (xs: ReadonlyArray, ys?: ReadonlyArray) => ReadonlyArray | ((ys: ReadonlyArray) => ReadonlyArray) { const elemE = elem(E) return (xs, ys?) => { if (ys === undefined) { const intersectionE = intersection(E) return (ys) => intersectionE(ys, xs) } return xs.filter((a) => elemE(a, ys)) } } // TODO: remove non-curried overloading in v3 /** * Creates an array of array values not included in the other given array using a `Eq` for equality * comparisons. The order and references of result values are determined by the first array. * * @example * import { difference } from 'fp-ts/ReadonlyArray' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe([1, 2], difference(N.Eq)([2, 3])), [1]) * * @since 2.5.0 */ export function difference(E: Eq): { (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray } export function difference( E: Eq ): (xs: ReadonlyArray, ys?: ReadonlyArray) => ReadonlyArray | ((ys: ReadonlyArray) => ReadonlyArray) { const elemE = elem(E) return (xs, ys?) => { if (ys === undefined) { const differenceE = difference(E) return (ys) => differenceE(ys, xs) } return xs.filter((a) => !elemE(a, ys)) } } const _map: Monad1['map'] = (fa, f) => pipe(fa, map(f)) const _mapWithIndex: FunctorWithIndex1['mapWithIndex'] = (fa, f) => pipe(fa, mapWithIndex(f)) const _ap: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _filter: Filterable1['filter'] = (fa: ReadonlyArray, predicate: Predicate) => pipe(fa, filter(predicate)) const _filterMap: Filterable1['filterMap'] = (fa, f) => pipe(fa, filterMap(f)) const _partition: Filterable1['partition'] = (fa: ReadonlyArray, predicate: Predicate) => pipe(fa, partition(predicate)) const _partitionMap: Filterable1['partitionMap'] = (fa, f) => pipe(fa, partitionMap(f)) const _partitionWithIndex: FilterableWithIndex1['partitionWithIndex'] = ( fa: ReadonlyArray, predicateWithIndex: (i: number, a: A) => boolean ) => pipe(fa, partitionWithIndex(predicateWithIndex)) const _partitionMapWithIndex: FilterableWithIndex1['partitionMapWithIndex'] = ( fa: ReadonlyArray, f: (i: number, a: A) => Either ) => pipe(fa, partitionMapWithIndex(f)) const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) const _reduce: Foldable1['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) const _foldMap: Foldable1['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } const _reduceRight: Foldable1['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) const _reduceWithIndex: FoldableWithIndex1['reduceWithIndex'] = (fa, b, f) => pipe(fa, reduceWithIndex(b, f)) const _foldMapWithIndex: FoldableWithIndex1['foldMapWithIndex'] = (M) => { const foldMapWithIndexM = foldMapWithIndex(M) return (fa, f) => pipe(fa, foldMapWithIndexM(f)) } const _reduceRightWithIndex: FoldableWithIndex1['reduceRightWithIndex'] = (fa, b, f) => pipe(fa, reduceRightWithIndex(b, f)) const _filterMapWithIndex: FilterableWithIndex1['filterMapWithIndex'] = ( fa: ReadonlyArray, f: (i: number, a: A) => Option ) => pipe(fa, filterMapWithIndex(f)) const _filterWithIndex: FilterableWithIndex1['filterWithIndex'] = ( fa: ReadonlyArray, predicateWithIndex: (i: number, a: A) => boolean ) => pipe(fa, filterWithIndex(predicateWithIndex)) const _extend: Extend1['extend'] = (fa, f) => pipe(fa, extend(f)) const _traverse: Traversable1['traverse'] = ( F: ApplicativeHKT ): ((ta: ReadonlyArray, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /* istanbul ignore next */ const _traverseWithIndex: TraversableWithIndex1['traverseWithIndex'] = ( F: ApplicativeHKT ): ((ta: ReadonlyArray, f: (i: number, a: A) => HKT) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta, f) => pipe(ta, traverseWithIndexF(f)) } /** @internal */ export const _chainRecDepthFirst: ChainRec1['chainRec'] = (a, f) => pipe(a, chainRecDepthFirst(f)) /** @internal */ export const _chainRecBreadthFirst: ChainRec1['chainRec'] = (a, f) => pipe(a, chainRecBreadthFirst(f)) /** * @category constructors * @since 2.5.0 */ export const of: (a: A) => ReadonlyArray = RNEA.of /** * @since 2.7.0 */ export const zero: () => ReadonlyArray = () => empty /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.altW(() => ['a', 'b']) * ), * [1, 2, 3, 'a', 'b'] * ) * * @category error handling * @since 2.9.0 */ export const altW = (that: LazyArg>) => (fa: ReadonlyArray): ReadonlyArray => (fa as ReadonlyArray).concat(that()) /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * In case of `ReadonlyArray` concatenates the inputs into a single array. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.alt(() => [4, 5]) * ), * [1, 2, 3, 4, 5] * ) * * @category error handling * @since 2.5.0 */ export const alt: (that: LazyArg>) => (fa: ReadonlyArray) => ReadonlyArray = altW /** * @since 2.5.0 */ export const ap: (fa: ReadonlyArray) => (fab: ReadonlyArray<(a: A) => B>) => ReadonlyArray = (fa) => flatMap((f) => pipe(fa, map(f))) /** * Composes computations in sequence, using the return value of one computation to determine the next computation. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.flatMap((n) => [`a${n}`, `b${n}`]) * ), * ['a1', 'b1', 'a2', 'b2', 'a3', 'b3'] * ) * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.flatMap(() => []) * ), * [] * ) * * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A, i: number) => ReadonlyArray): (ma: ReadonlyArray) => ReadonlyArray (ma: ReadonlyArray, f: (a: A, i: number) => ReadonlyArray): ReadonlyArray } = /*#__PURE__*/ dual( 2, (ma: ReadonlyArray, f: (a: A, i: number) => ReadonlyArray): ReadonlyArray => pipe( ma, chainWithIndex((i, a) => f(a, i)) ) ) /** * @category sequencing * @since 2.5.0 */ export const flatten: (mma: ReadonlyArray>) => ReadonlyArray = /*#__PURE__*/ flatMap(identity) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.5.0 */ export const map: (f: (a: A) => B) => (fa: ReadonlyArray) => ReadonlyArray = (f) => (fa) => fa.map((a) => f(a)) /** * @category mapping * @since 2.5.0 */ export const mapWithIndex: (f: (i: number, a: A) => B) => (fa: ReadonlyArray) => ReadonlyArray = (f) => (fa) => fa.map((a, i) => f(i, a)) /** * @category filtering * @since 2.5.0 */ export const separate = (fa: ReadonlyArray>): Separated, ReadonlyArray> => { const left: Array = [] const right: Array = [] for (const e of fa) { if (e._tag === 'Left') { left.push(e.left) } else { right.push(e.right) } } return separated(left, right) } /** * @category filtering * @since 2.5.0 */ export const filter: { (refinement: Refinement): (as: ReadonlyArray) => ReadonlyArray (predicate: Predicate): (bs: ReadonlyArray) => ReadonlyArray (predicate: Predicate): (as: ReadonlyArray) => ReadonlyArray } = (predicate: Predicate) => (as: ReadonlyArray) => as.filter(predicate) /** * @category filtering * @since 2.5.0 */ export const filterMapWithIndex = (f: (i: number, a: A) => Option) => (fa: ReadonlyArray): ReadonlyArray => { const out: Array = [] for (let i = 0; i < fa.length; i++) { const optionB = f(i, fa[i]) if (_.isSome(optionB)) { out.push(optionB.value) } } return out } /** * @category filtering * @since 2.5.0 */ export const filterMap: (f: (a: A) => Option) => (fa: ReadonlyArray) => ReadonlyArray = (f) => filterMapWithIndex((_, a) => f(a)) /** * @category filtering * @since 2.5.0 */ export const compact: (fa: ReadonlyArray>) => ReadonlyArray = /*#__PURE__*/ filterMap(identity) /** * @category filtering * @since 2.5.0 */ export const partition: { (refinement: Refinement): ( as: ReadonlyArray ) => Separated, ReadonlyArray> (predicate: Predicate): (bs: ReadonlyArray) => Separated, ReadonlyArray> (predicate: Predicate): (as: ReadonlyArray) => Separated, ReadonlyArray> } = (predicate: Predicate): ((as: ReadonlyArray) => Separated, ReadonlyArray>) => partitionWithIndex((_, a) => predicate(a)) /** * @category filtering * @since 2.5.0 */ export const partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( as: ReadonlyArray ) => Separated, ReadonlyArray> (predicateWithIndex: PredicateWithIndex): ( bs: ReadonlyArray ) => Separated, ReadonlyArray> (predicateWithIndex: PredicateWithIndex): ( as: ReadonlyArray ) => Separated, ReadonlyArray> } = (predicateWithIndex: PredicateWithIndex) => (as: ReadonlyArray): Separated, ReadonlyArray> => { const left: Array = [] const right: Array = [] for (let i = 0; i < as.length; i++) { const a = as[i] if (predicateWithIndex(i, a)) { right.push(a) } else { left.push(a) } } return separated(left, right) } /** * @category filtering * @since 2.5.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: ReadonlyArray) => Separated, ReadonlyArray> = (f) => partitionMapWithIndex((_, a) => f(a)) /** * @category filtering * @since 2.5.0 */ export const partitionMapWithIndex = (f: (i: number, a: A) => Either) => (fa: ReadonlyArray): Separated, ReadonlyArray> => { const left: Array = [] const right: Array = [] for (let i = 0; i < fa.length; i++) { const e = f(i, fa[i]) if (e._tag === 'Left') { left.push(e.left) } else { right.push(e.right) } } return separated(left, right) } /** * @category filtering * @since 2.5.0 */ export const filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (as: ReadonlyArray) => ReadonlyArray (predicateWithIndex: PredicateWithIndex): (bs: ReadonlyArray) => ReadonlyArray (predicateWithIndex: PredicateWithIndex): (as: ReadonlyArray) => ReadonlyArray } = (predicateWithIndex: PredicateWithIndex) => (as: ReadonlyArray): ReadonlyArray => as.filter((a, i) => predicateWithIndex(i, a)) /** * @since 2.5.0 */ export const extend: (f: (fa: ReadonlyArray) => B) => (wa: ReadonlyArray) => ReadonlyArray = (f) => (wa) => wa.map((_, i) => f(wa.slice(i))) /** * @since 2.5.0 */ export const duplicate: (wa: ReadonlyArray) => ReadonlyArray> = /*#__PURE__*/ extend(identity) /** * @category folding * @since 2.5.0 */ export const foldMapWithIndex = (M: Monoid) => (f: (i: number, a: A) => M) => (fa: ReadonlyArray): M => fa.reduce((b, a, i) => M.concat(b, f(i, a)), M.empty) /** * @category folding * @since 2.5.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: ReadonlyArray) => B = (b, f) => reduceWithIndex(b, (_, b, a) => f(b, a)) /** * @category folding * @since 2.5.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: ReadonlyArray) => M = (M) => { const foldMapWithIndexM = foldMapWithIndex(M) return (f) => foldMapWithIndexM((_, a) => f(a)) } /** * @category folding * @since 2.5.0 */ export const reduceWithIndex: (b: B, f: (i: number, b: B, a: A) => B) => (fa: ReadonlyArray) => B = (b, f) => (fa) => { const len = fa.length let out = b for (let i = 0; i < len; i++) { out = f(i, out, fa[i]) } return out } /** * @category folding * @since 2.5.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: ReadonlyArray) => B = (b, f) => reduceRightWithIndex(b, (_, a, b) => f(a, b)) /** * @category folding * @since 2.5.0 */ export const reduceRightWithIndex: (b: B, f: (i: number, a: A, b: B) => B) => (fa: ReadonlyArray) => B = (b, f) => (fa) => fa.reduceRight((b, a, i) => f(i, a, b), b) /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT) => (ta: ReadonlyArray) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (f) => traverseWithIndexF((_, a) => f(a)) } /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = (F: ApplicativeHKT) => (ta: ReadonlyArray>): HKT> => { return _reduce(ta, F.of(zero()), (fas, fa) => F.ap( F.map(fas, (as) => (a: A) => pipe(as, append(a))), fa ) ) } /** * @category sequencing * @since 2.6.3 */ export const traverseWithIndex: PipeableTraverseWithIndex1 = (F: ApplicativeHKT) => (f: (i: number, a: A) => HKT): ((ta: ReadonlyArray) => HKT>) => reduceWithIndex(F.of(zero()), (i, fbs, a) => F.ap( F.map(fbs, (bs) => (b: B) => pipe(bs, append(b))), f(i, a) ) ) /** * @category filtering * @since 2.6.5 */ export const wither: PipeableWither1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT>) => (fa: ReadonlyArray) => HKT>) => { const _witherF = _wither(F) return (f) => (fa) => _witherF(fa, f) } /** * @category filtering * @since 2.6.5 */ export const wilt: PipeableWilt1 = ( F: ApplicativeHKT ): (( f: (a: A) => HKT> ) => (fa: ReadonlyArray) => HKT, ReadonlyArray>>) => { const _wiltF = _wilt(F) return (f) => (fa) => _wiltF(fa, f) } /** * @since 2.6.6 */ export const unfold = (b: B, f: (b: B) => Option): ReadonlyArray => { const out: Array = [] let bb: B = b // eslint-disable-next-line no-constant-condition while (true) { const mt = f(bb) if (_.isSome(mt)) { const [a, b] = mt.value out.push(a) bb = b } else { break } } return out } /** * @category type lambdas * @since 2.5.0 */ export const URI = 'ReadonlyArray' /** * @category type lambdas * @since 2.5.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: ReadonlyArray } } /** * @category instances * @since 2.5.0 */ export const getShow = (S: Show): Show> => ({ show: (as) => `[${as.map(S.show).join(', ')}]` }) /** * @category instances * @since 2.5.0 */ export const getSemigroup = (): Semigroup> => ({ concat: (first, second) => (isEmpty(first) ? second : isEmpty(second) ? first : first.concat(second)) }) /** * Returns a `Monoid` for `ReadonlyArray`. * * @example * import { getMonoid } from 'fp-ts/ReadonlyArray' * * const M = getMonoid() * assert.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4]) * * @category instances * @since 2.5.0 */ export const getMonoid = (): Monoid> => ({ concat: getSemigroup().concat, empty }) /** * Derives an `Eq` over the `ReadonlyArray` of a given element type from the `Eq` of that type. The derived `Eq` defines two * arrays as equal if all elements of both arrays are compared equal pairwise with the given `E`. In case of arrays of * different lengths, the result is non equality. * * @example * import * as S from 'fp-ts/string' * import { getEq } from 'fp-ts/ReadonlyArray' * * const E = getEq(S.Eq) * assert.strictEqual(E.equals(['a', 'b'], ['a', 'b']), true) * assert.strictEqual(E.equals(['a'], []), false) * * @category instances * @since 2.5.0 */ export const getEq = (E: Eq): Eq> => fromEquals((xs, ys) => xs.length === ys.length && xs.every((x, i) => E.equals(x, ys[i]))) /** * Derives an `Ord` over the `ReadonlyArray` of a given element type from the `Ord` of that type. The ordering between two such * arrays is equal to: the first non equal comparison of each arrays elements taken pairwise in increasing order, in * case of equality over all the pairwise elements; the longest array is considered the greatest, if both arrays have * the same length, the result is equality. * * @example * import { getOrd } from 'fp-ts/ReadonlyArray' * import * as S from 'fp-ts/string' * * const O = getOrd(S.Ord) * assert.strictEqual(O.compare(['b'], ['a']), 1) * assert.strictEqual(O.compare(['a'], ['a']), 0) * assert.strictEqual(O.compare(['a'], ['b']), -1) * * * @category instances * @since 2.5.0 */ export const getOrd = (O: Ord): Ord> => fromCompare((a, b) => { const aLen = a.length const bLen = b.length const len = Math.min(aLen, bLen) for (let i = 0; i < len; i++) { const ordering = O.compare(a[i], b[i]) if (ordering !== 0) { return ordering } } return N.Ord.compare(aLen, bLen) }) /** * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq): Semigroup> => { const unionE = union(E) return { concat: (first, second) => unionE(second)(first) } } /** * @category instances * @since 2.11.0 */ export const getUnionMonoid = (E: Eq): Monoid> => ({ concat: getUnionSemigroup(E).concat, empty }) /** * @category instances * @since 2.11.0 */ export const getIntersectionSemigroup = (E: Eq): Semigroup> => { const intersectionE = intersection(E) return { concat: (first, second) => intersectionE(second)(first) } } /** * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (E: Eq): Magma> => { const differenceE = difference(E) return { concat: (first, second) => differenceE(second)(first) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.7.0 */ export const FunctorWithIndex: FunctorWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.5.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.5.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.chainFirst(() => ['a', 'b']) * ), * [1, 1, 2, 2, 3, 3] * ) * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.chainFirst(() => []) * ), * [] * ) * * @category sequencing * @since 2.5.0 */ export const chainFirst: (f: (a: A) => ReadonlyArray) => (first: ReadonlyArray) => ReadonlyArray = /*#__PURE__*/ chainFirst_(Chain) /** * @category instances * @since 2.7.0 */ export const Unfoldable: Unfoldable1 = { URI, unfold } /** * @category instances * @since 2.7.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.11.0 */ export const Zero: Zero1 = { URI, zero } /** * @category do notation * @since 2.11.0 */ export const guard = /*#__PURE__*/ guard_(Zero, Pointed) /** * @category instances * @since 2.7.0 */ export const Alternative: Alternative1 = { URI, map: _map, ap: _ap, of, alt: _alt, zero } /** * @category instances * @since 2.7.0 */ export const Extend: Extend1 = { URI, map: _map, extend: _extend } /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category instances * @since 2.7.0 */ export const FilterableWithIndex: FilterableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const FoldableWithIndex: FoldableWithIndex1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.7.0 */ export const TraversableWithIndex: TraversableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverse: _traverse, sequence, traverseWithIndex: _traverseWithIndex } /** * @category sequencing * @since 2.11.0 */ export const chainRecDepthFirst = (f: (a: A) => ReadonlyArray>) => (a: A): ReadonlyArray => { const todo: Array> = [...f(a)] const out: Array = [] while (todo.length > 0) { const e = todo.shift()! if (_.isLeft(e)) { todo.unshift(...f(e.left)) } else { out.push(e.right) } } return out } /** * @category instances * @since 2.11.0 */ export const ChainRecDepthFirst: ChainRec1 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRecDepthFirst } /** * @category sequencing * @since 2.11.0 */ export const chainRecBreadthFirst = (f: (a: A) => ReadonlyArray>) => (a: A): ReadonlyArray => { const initial = f(a) const todo: Array> = [] const out: Array = [] function go(e: Either): void { if (_.isLeft(e)) { f(e.left).forEach((v) => todo.push(v)) } else { out.push(e.right) } } for (const e of initial) { go(e) } while (todo.length > 0) { go(todo.shift()!) } return out } /** * @category instances * @since 2.11.0 */ export const ChainRecBreadthFirst: ChainRec1 = { URI, map: _map, ap: _ap, chain: flatMap, chainRec: _chainRecBreadthFirst } const _wither: Witherable1['wither'] = /*#__PURE__*/ witherDefault(Traversable, Compactable) const _wilt: Witherable1['wilt'] = /*#__PURE__*/ wiltDefault(Traversable, Compactable) /** * @category instances * @since 2.7.0 */ export const Witherable: Witherable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, wither: _wither, wilt: _wilt } /** * Filter values inside a context. * * @example * import { pipe } from 'fp-ts/function' * import * as RA from 'fp-ts/ReadonlyArray' * import * as T from 'fp-ts/Task' * * const filterE = RA.filterE(T.ApplicativePar) * async function test() { * assert.deepStrictEqual( * await pipe( * [-1, 2, 3], * filterE((n) => T.of(n > 0)) * )(), * [2, 3] * ) * } * test() * * @since 2.11.0 */ export const filterE = /*#__PURE__*/ filterE_(Witherable) /** * @category instances * @since 2.11.0 */ export const FromEither: FromEither1 = { URI, fromEither } /** * @category lifting * @since 2.11.0 */ export const fromEitherK: , B>( f: (...a: A) => Either ) => (...a: A) => ReadonlyArray = /*#__PURE__*/ fromEitherK_(FromEither) // ------------------------------------------------------------------------------------- // unsafe // ------------------------------------------------------------------------------------- /** * @category unsafe * @since 2.5.0 */ export const unsafeInsertAt: (i: number, a: A, as: ReadonlyArray) => ReadonlyNonEmptyArray = RNEA.unsafeInsertAt /** * @category unsafe * @since 2.5.0 */ export const unsafeUpdateAt = (i: number, a: A, as: ReadonlyArray): ReadonlyArray => isNonEmpty(as) ? RNEA.unsafeUpdateAt(i, a, as) : as /** * @category unsafe * @since 2.5.0 */ export const unsafeDeleteAt = (i: number, as: ReadonlyArray): ReadonlyArray => { const xs = as.slice() xs.splice(i, 1) return xs } /** * @category conversions * @since 2.5.0 */ export const toArray = (as: ReadonlyArray): Array => as.slice() /** * @category conversions * @since 2.5.0 */ export const fromArray = (as: Array): ReadonlyArray => (isEmpty(as) ? empty : as.slice()) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * An empty array * * @since 2.5.0 */ export const empty: ReadonlyArray = RNEA.empty /** * Check if a predicate holds true for every array member. * * @example * import { every } from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * const isPositive = (n: number): boolean => n > 0 * * assert.deepStrictEqual(pipe([1, 2, 3], every(isPositive)), true) * assert.deepStrictEqual(pipe([1, 2, -3], every(isPositive)), false) * * @since 2.9.0 */ export function every(refinement: Refinement): Refinement, ReadonlyArray> export function every(predicate: Predicate): Predicate> export function every(predicate: Predicate): Predicate> { return (as) => as.every(predicate) } /** * Check if a predicate holds true for any array member. * * @example * import { some } from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * const isPositive = (n: number): boolean => n > 0 * * assert.deepStrictEqual(pipe([-1, -2, 3], some(isPositive)), true) * assert.deepStrictEqual(pipe([-1, -2, -3], some(isPositive)), false) * * @since 2.9.0 */ export const some = (predicate: Predicate) => (as: ReadonlyArray): as is ReadonlyNonEmptyArray => as.some(predicate) /** * Alias of [`some`](#some) * * @since 2.11.0 */ export const exists: (predicate: Predicate) => (as: ReadonlyArray) => as is RNEA.ReadonlyNonEmptyArray = some /** * Places an element in between members of a `ReadonlyArray`, then folds the results using the provided `Monoid`. * * @example * import * as S from 'fp-ts/string' * import { intercalate } from 'fp-ts/ReadonlyArray' * * assert.deepStrictEqual(intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c') * * @since 2.12.0 */ export const intercalate = (M: Monoid): ((middle: A) => (as: ReadonlyArray) => A) => { const intercalateM = RNEA.intercalate(M) return (middle) => match(() => M.empty, intercalateM(middle)) } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: ReadonlyArray<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ bind_(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.5.0 */ export const chain: (f: (a: A) => ReadonlyArray) => (ma: ReadonlyArray) => ReadonlyArray = flatMap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `ReadonlyNonEmptyArray` module instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const range = RNEA.range /** * Use [`prepend`](#prepend) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const cons = RNEA.cons /** * Use [`append`](#append) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const snoc = RNEA.snoc /** * Use [`prependAll`](#prependall) instead. * * @category zone of death * @since 2.9.0 * @deprecated */ export const prependToAll = prependAll /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RA.Functor` instead of `RA.readonlyArray` * (where `RA` is from `import RA from 'fp-ts/ReadonlyArray'`) * * @category zone of death * @since 2.5.0 * @deprecated */ export const readonlyArray: FunctorWithIndex1 & Monad1 & Unfoldable1 & Alternative1 & Extend1 & FilterableWithIndex1 & FoldableWithIndex1 & TraversableWithIndex1 & Witherable1 = { URI, compact, separate, map: _map, ap: _ap, of, chain: flatMap, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, mapWithIndex: _mapWithIndex, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex, alt: _alt, zero, unfold, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverseWithIndex: _traverseWithIndex, extend: _extend, wither: _wither, wilt: _wilt } ================================================ FILE: src/ReadonlyMap.ts ================================================ /** * @since 2.5.0 */ import { Applicative } from './Applicative' import { Compactable2 } from './Compactable' import { Either } from './Either' import { Eq, fromEquals } from './Eq' import { Filterable2 } from './Filterable' import { FilterableWithIndex2C } from './FilterableWithIndex' import { Foldable, Foldable1, Foldable2, Foldable2C, Foldable3 } from './Foldable' import { FoldableWithIndex2C } from './FoldableWithIndex' import { pipe, SK } from './function' import { flap as flap_, Functor2 } from './Functor' import { FunctorWithIndex2C } from './FunctorWithIndex' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import * as _ from './internal' import { Magma } from './Magma' import { Monoid } from './Monoid' import * as O from './Option' import { Ord } from './Ord' import { Predicate } from './Predicate' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import { Traversable2C } from './Traversable' import { TraversableWithIndex2C } from './TraversableWithIndex' import { Unfoldable, Unfoldable1 } from './Unfoldable' import { wiltDefault, Witherable2C, witherDefault } from './Witherable' import Option = O.Option /** * @category conversions * @since 2.5.0 */ export const fromMap = (m: Map): ReadonlyMap => new Map(m) /** * @category conversions * @since 2.5.0 */ export function toMap(m: ReadonlyMap): Map { return new Map(m) } /** * @category instances * @since 2.5.0 */ export function getShow(SK: Show, SA: Show): Show> { return { show: (m) => { const entries: Array = [] m.forEach((a, k) => { entries.push(`[${SK.show(k)}, ${SA.show(a)}]`) }) return `new Map([${entries.sort().join(', ')}])` } } } /** * Calculate the number of key/value pairs in a map * * @since 2.5.0 */ export const size = (m: ReadonlyMap): number => m.size /** * Test whether or not a map is empty * * @since 2.5.0 */ export const isEmpty = (m: ReadonlyMap): boolean => m.size === 0 // TODO: remove non-curried overloading in v3 /** * Test whether or not a key exists in a map * * @since 2.5.0 */ export function member(E: Eq): { (k: K): (m: ReadonlyMap) => boolean (k: K, m: ReadonlyMap): boolean } export function member(E: Eq): (k: K, m?: ReadonlyMap) => boolean | ((m: ReadonlyMap) => boolean) { const lookupE = lookup(E) return (k, m?) => { if (m === undefined) { const memberE = member(E) return (m) => memberE(k, m) } return _.isSome(lookupE(k, m)) } } type Next = IteratorResult // TODO: remove non-curried overloading in v3 /** * Test whether or not a value is a member of a map * * @since 2.5.0 */ export function elem(E: Eq): { (a: A): (m: ReadonlyMap) => boolean (a: A, m: ReadonlyMap): boolean } export function elem(E: Eq): (a: A, m?: ReadonlyMap) => boolean | ((m: ReadonlyMap) => boolean) { return (a, m?) => { if (m === undefined) { const elemE = elem(E) return (m) => elemE(a, m) } const values = m.values() let e: Next while (!(e = values.next()).done) { const v = e.value if (E.equals(a, v)) { return true } } return false } } /** * Get a sorted `ReadonlyArray` of the keys contained in a `ReadonlyMap`. * * @since 2.5.0 */ export const keys = (O: Ord) => (m: ReadonlyMap): ReadonlyArray => Array.from(m.keys()).sort(O.compare) /** * Get a sorted `ReadonlyArray` of the values contained in a `ReadonlyMap`. * * @since 2.5.0 */ export const values = (O: Ord) => (m: ReadonlyMap): ReadonlyArray => Array.from(m.values()).sort(O.compare) /** * @since 2.5.0 */ export function collect(O: Ord): (f: (k: K, a: A) => B) => (m: ReadonlyMap) => ReadonlyArray { const keysO = keys(O) return (f: (k: K, a: A) => B) => (m: ReadonlyMap): ReadonlyArray => { const out: Array = [] const ks = keysO(m) for (const key of ks) { out.push(f(key, m.get(key)!)) } return out } } /** * Get a sorted `ReadonlyArray` of the key/value pairs contained in a `ReadonlyMap`. * * @category conversions * @since 2.5.0 */ export const toReadonlyArray = (O: Ord): ((m: ReadonlyMap) => ReadonlyArray) => collect(O)((k, a) => [k, a] as const) /** * Unfolds a map into a list of key/value pairs * * @category conversions * @since 2.5.0 */ export function toUnfoldable( ord: Ord, U: Unfoldable1 ): (d: ReadonlyMap) => Kind export function toUnfoldable(ord: Ord, U: Unfoldable): (d: ReadonlyMap) => HKT export function toUnfoldable( ord: Ord, U: Unfoldable ): (d: ReadonlyMap) => HKT { const toReadonlyArrayO = toReadonlyArray(ord) return (d) => { const kas = toReadonlyArrayO(d) const len = kas.length return U.unfold(0, (b) => (b < len ? _.some([kas[b], b + 1]) : _.none)) } } /** * Insert or replace a key/value pair in a `ReadonlyMap`. * * @since 2.10.0 */ export const upsertAt = (E: Eq): ((k: K, a: A) => (m: ReadonlyMap) => ReadonlyMap) => { const lookupWithKeyE = lookupWithKey(E) return (k, a) => { const lookupWithKeyEk = lookupWithKeyE(k) return (m) => { const found = lookupWithKeyEk(m) if (_.isNone(found)) { const out = new Map(m) out.set(k, a) return out } else if (found.value[1] !== a) { const out = new Map(m) out.set(found.value[0], a) return out } return m } } } /** * Delete a key and value from a map * * @since 2.5.0 */ export const deleteAt = (E: Eq): ((k: K) => (m: ReadonlyMap) => ReadonlyMap) => { const lookupWithKeyE = lookupWithKey(E) return (k) => (m) => { const found = lookupWithKeyE(k, m) if (_.isSome(found)) { const r = new Map(m) r.delete(found.value[0]) return r } return m } } /** * @since 2.5.0 */ export const updateAt = (E: Eq): ((k: K, a: A) => (m: ReadonlyMap) => Option>) => { const modifyAtE = modifyAt(E) return (k, a) => modifyAtE(k, () => a) } /** * @since 2.5.0 */ export const modifyAt = ( E: Eq ): ((k: K, f: (a: A) => A) => (m: ReadonlyMap) => Option>) => { const lookupWithKeyE = lookupWithKey(E) return (k, f) => (m) => { const found = lookupWithKeyE(k, m) if (_.isNone(found)) { return _.none } const [fk, fv] = found.value const next = f(fv) if (next === fv) { return _.some(m) } const r = new Map(m) r.set(fk, next) return _.some(r) } } /** * Delete a key and value from a map, returning the value as well as the subsequent map * * @since 2.5.0 */ export function pop(E: Eq): (k: K) => (m: ReadonlyMap) => Option]> { const lookupE = lookup(E) const deleteAtE = deleteAt(E) return (k) => { const deleteAtEk = deleteAtE(k) return (m) => pipe( lookupE(k, m), O.map((a) => [a, deleteAtEk(m)]) ) } } // TODO: remove non-curried overloading in v3 /** * Lookup the value for a key in a `Map`. * If the result is a `Some`, the existing key is also returned. * * @since 2.5.0 */ export function lookupWithKey(E: Eq): { (k: K): (m: ReadonlyMap) => Option (k: K, m: ReadonlyMap): Option } export function lookupWithKey( E: Eq ): (k: K, m?: ReadonlyMap) => Option | ((m: ReadonlyMap) => Option) { return (k: K, m?: ReadonlyMap) => { if (m === undefined) { const lookupWithKeyE = lookupWithKey(E) return (m) => lookupWithKeyE(k, m) } const entries = m.entries() let e: Next while (!(e = entries.next()).done) { const [ka, a] = e.value if (E.equals(ka, k)) { return _.some([ka, a]) } } return _.none } } // TODO: remove non-curried overloading in v3 /** * Lookup the value for a key in a `Map`. * * @since 2.5.0 */ export function lookup(E: Eq): { (k: K): (m: ReadonlyMap) => Option (k: K, m: ReadonlyMap): Option } export function lookup( E: Eq ): (k: K, m?: ReadonlyMap) => Option | ((m: ReadonlyMap) => Option) { const lookupWithKeyE = lookupWithKey(E) return (k, m?) => { if (m === undefined) { const lookupE = lookup(E) return (m) => lookupE(k, m) } return pipe( lookupWithKeyE(k, m), O.map(([_, a]) => a) ) } } // TODO: remove non-curried overloading in v3 /** * Test whether or not one `Map` contains all of the keys and values contained in another `Map` * * @since 2.5.0 */ export function isSubmap( SK: Eq, SA: Eq ): { (that: ReadonlyMap): (me: ReadonlyMap) => boolean (me: ReadonlyMap, that: ReadonlyMap): boolean } export function isSubmap( SK: Eq, SA: Eq ): (me: ReadonlyMap, that?: ReadonlyMap) => boolean | ((me: ReadonlyMap) => boolean) { const lookupWithKeyS = lookupWithKey(SK) return (me: ReadonlyMap, that?: ReadonlyMap) => { if (that === undefined) { const isSubmapSKSA = isSubmap(SK, SA) return (that) => isSubmapSKSA(that, me) } const entries = me.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value const d2OptA = lookupWithKeyS(k, that) if (_.isNone(d2OptA) || !SK.equals(k, d2OptA.value[0]) || !SA.equals(a, d2OptA.value[1])) { return false } } return true } } /** * @since 2.5.0 */ export const empty: ReadonlyMap = // the type annotation here is intended (otherwise it doesn't type-check) new Map() /** * @category instances * @since 2.5.0 */ export function getEq(SK: Eq, SA: Eq): Eq> { const isSubmapSKSA = isSubmap(SK, SA) return fromEquals((x, y) => isSubmapSKSA(x, y) && isSubmapSKSA(y, x)) } /** * Gets `Monoid` instance for Maps given `Semigroup` instance for their values * * @category instances * @since 2.5.0 */ export function getMonoid(SK: Eq, SA: Semigroup): Monoid> { const lookupWithKeyS = lookupWithKey(SK) return { concat: (mx, my) => { if (isEmpty(mx)) { return my } if (isEmpty(my)) { return mx } const r = new Map(mx) const entries = my.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value const mxOptA = lookupWithKeyS(k, mx) if (_.isSome(mxOptA)) { r.set(mxOptA.value[0], SA.concat(mxOptA.value[1], a)) } else { r.set(k, a) } } return r }, empty } } /** * Create a map with one key/value pair * * @category constructors * @since 2.5.0 */ export const singleton = (k: K, a: A): ReadonlyMap => new Map([[k, a]]) /** * Create a map from a foldable collection of key/value pairs, using the * specified `Magma` to combine values for duplicate keys. * * @category constructors * @since 2.5.0 */ export function fromFoldable( E: Eq, M: Magma, F: Foldable3 ): (fka: Kind3) => ReadonlyMap export function fromFoldable( E: Eq, M: Magma, F: Foldable2 ): (fka: Kind2) => ReadonlyMap export function fromFoldable( E: Eq, M: Magma, F: Foldable1 ): (fka: Kind) => ReadonlyMap export function fromFoldable( E: Eq, M: Magma, F: Foldable ): (fka: HKT) => ReadonlyMap export function fromFoldable( E: Eq, M: Magma, F: Foldable ): (fka: HKT) => ReadonlyMap { return (fka: HKT) => { const lookupWithKeyE = lookupWithKey(E) return F.reduce>(fka, new Map(), (b, [k, a]) => { const bOpt = lookupWithKeyE(k, b) if (_.isSome(bOpt)) { b.set(bOpt.value[0], M.concat(bOpt.value[1], a)) } else { b.set(k, a) } return b }) } } const _mapWithIndex = (fa: ReadonlyMap, f: (k: K, a: A) => B): ReadonlyMap => { const m = new Map() const entries = fa.entries() let e: Next while (!(e = entries.next()).done) { const [key, a] = e.value m.set(key, f(key, a)) } return m } /** * @since 2.10.0 */ export const partitionMapWithIndex = (f: (k: K, a: A) => Either) => (fa: ReadonlyMap): Separated, ReadonlyMap> => { const left = new Map() const right = new Map() const entries = fa.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value const ei = f(k, a) if (_.isLeft(ei)) { left.set(k, ei.left) } else { right.set(k, ei.right) } } return separated(left, right) } /** * @since 2.10.0 */ export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => a is B ): (m: ReadonlyMap) => Separated, ReadonlyMap> export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => Separated, ReadonlyMap> export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => Separated, ReadonlyMap> export function partitionWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => Separated, ReadonlyMap> { return (m: ReadonlyMap) => { const left = new Map() const right = new Map() const entries = m.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value if (predicateWithIndex(k, a)) { right.set(k, a) } else { left.set(k, a) } } return separated(left, right) } } /** * @since 2.10.0 */ export const filterMapWithIndex = (f: (k: K, a: A) => Option) => (fa: ReadonlyMap): ReadonlyMap => { const m = new Map() const entries = fa.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value const o = f(k, a) if (_.isSome(o)) { m.set(k, o.value) } } return m } /** * @since 2.10.0 */ export function filterWithIndex( predicateWithIndex: (k: K, a: A) => a is B ): (m: ReadonlyMap) => ReadonlyMap export function filterWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => ReadonlyMap export function filterWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => ReadonlyMap export function filterWithIndex( predicateWithIndex: (k: K, a: A) => boolean ): (m: ReadonlyMap) => ReadonlyMap { return (m: ReadonlyMap) => { const out = new Map() const entries = m.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value if (predicateWithIndex(k, a)) { out.set(k, a) } } return out } } const _map: Functor2['map'] = (fa, f) => _mapWithIndex(fa, (_, a) => f(a)) const _filter: Filterable2['filter'] = (fa: ReadonlyMap, p: Predicate) => _filterWithIndex(fa, (_, a) => p(a)) const _filterMap: Filterable2['filterMap'] = (fa, f) => _filterMapWithIndex(fa, (_, a) => f(a)) const _partition: Filterable2['partition'] = (fa: ReadonlyMap, predicate: Predicate) => _partitionWithIndex(fa, (_, a) => predicate(a)) const _partitionMap: Filterable2['partitionMap'] = (fa, f) => _partitionMapWithIndex(fa, (_, a) => f(a)) const _filterWithIndex = (fa: ReadonlyMap, p: (k: K, a: A) => boolean) => pipe(fa, filterWithIndex(p)) const _filterMapWithIndex = (fa: ReadonlyMap, f: (k: K, a: A) => Option) => pipe(fa, filterMapWithIndex(f)) const _partitionWithIndex = (fa: ReadonlyMap, p: (k: K, a: A) => boolean) => pipe(fa, partitionWithIndex(p)) const _partitionMapWithIndex = (fa: ReadonlyMap, f: (k: K, a: A) => Either) => pipe(fa, partitionMapWithIndex(f)) /** * @category filtering * @since 2.5.0 */ export const compact = (fa: ReadonlyMap>): ReadonlyMap => { const m = new Map() const entries = fa.entries() let e: Next]> while (!(e = entries.next()).done) { const [k, oa] = e.value if (_.isSome(oa)) { m.set(k, oa.value) } } return m } /** * @category filtering * @since 2.5.0 */ export const filter: { (refinement: Refinement): (fa: ReadonlyMap) => ReadonlyMap (predicate: Predicate): (fb: ReadonlyMap) => ReadonlyMap (predicate: Predicate): (fa: ReadonlyMap) => ReadonlyMap } = (predicate: Predicate) => (fa: ReadonlyMap) => _filter(fa, predicate) /** * @category filtering * @since 2.5.0 */ export const filterMap: (f: (a: A) => Option) => (fa: ReadonlyMap) => ReadonlyMap = (f) => (fa) => _filterMap(fa, f) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.5.0 */ export const map: (f: (a: A) => B) => (fa: ReadonlyMap) => ReadonlyMap = (f) => (fa) => _map(fa, f) /** * @category mapping * @since 2.7.1 */ export const mapWithIndex: (f: (k: K, a: A) => B) => (fa: ReadonlyMap) => ReadonlyMap = (f) => (fa) => _mapWithIndex(fa, f) /** * @category filtering * @since 2.5.0 */ export const partition: { (refinement: Refinement): ( fa: ReadonlyMap ) => Separated, ReadonlyMap> (predicate: Predicate): ( fb: ReadonlyMap ) => Separated, ReadonlyMap> (predicate: Predicate): (fa: ReadonlyMap) => Separated, ReadonlyMap> } = (predicate: Predicate) => (fa: ReadonlyMap) => _partition(fa, predicate) /** * @category filtering * @since 2.5.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: ReadonlyMap) => Separated, ReadonlyMap> = (f) => (fa) => _partitionMap(fa, f) /** * @category filtering * @since 2.5.0 */ export const separate = ( fa: ReadonlyMap> ): Separated, ReadonlyMap> => { const left = new Map() const right = new Map() const entries = fa.entries() let e: Next]> while (!(e = entries.next()).done) { const [k, ei] = e.value if (_.isLeft(ei)) { left.set(k, ei.left) } else { right.set(k, ei.right) } } return separated(left, right) } /** * @category type lambdas * @since 2.5.0 */ export const URI = 'ReadonlyMap' /** * @category type lambdas * @since 2.5.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: ReadonlyMap } } /** * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq, S: Semigroup): Semigroup> => { const unionES = union(E, S) return { concat: (first, second) => unionES(second)(first) } } /** * @category instances * @since 2.11.0 */ export const getUnionMonoid = (E: Eq, S: Semigroup): Monoid> => ({ concat: getUnionSemigroup(E, S).concat, empty }) /** * @category instances * @since 2.11.0 */ export const getIntersectionSemigroup = (E: Eq, S: Semigroup): Semigroup> => { const intersectionES = intersection(E, S) return { concat: (first, second) => intersectionES(second)(first) } } /** * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (E: Eq) => (): Magma> => { const differenceE = difference(E) return { concat: (first, second) => differenceE(second)(first) } } /** * @category filtering * @since 2.5.0 */ export function getFilterableWithIndex(): FilterableWithIndex2C { return { URI, _E: undefined as any, map: _map, mapWithIndex: _mapWithIndex, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const getFunctorWithIndex = (): FunctorWithIndex2C => ({ URI, _E: undefined as any, map: _map, mapWithIndex: _mapWithIndex }) /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable2 = { URI, compact, separate } /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable2 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category folding * @since 2.11.0 */ export const reduce = (O: Ord): ((b: B, f: (b: B, a: A) => B) => (m: ReadonlyMap) => B) => { const reduceWithIndexO = reduceWithIndex(O) return (b, f) => reduceWithIndexO(b, (_, b, a) => f(b, a)) } /** * @category folding * @since 2.11.0 */ export const foldMap = (O: Ord): ((M: Monoid) => (f: (a: A) => M) => (m: ReadonlyMap) => M) => { const foldMapWithIndexO = foldMapWithIndex(O) return (M) => { const foldMapWithIndexOM = foldMapWithIndexO(M) return (f) => foldMapWithIndexOM((_, a) => f(a)) } } /** * @category folding * @since 2.11.0 */ export const reduceRight = (O: Ord): ((b: B, f: (a: A, b: B) => B) => (m: ReadonlyMap) => B) => { const reduceRightWithIndexO = reduceRightWithIndex(O) return (b, f) => reduceRightWithIndexO(b, (_, b, a) => f(b, a)) } /** * @category folding * @since 2.10.0 */ export const getFoldable = (O: Ord): Foldable2C => { const reduceO = reduce(O) const foldMapO = foldMap(O) const reduceRightO = reduceRight(O) return { URI, _E: undefined as any, reduce: (fa, b, f) => pipe(fa, reduceO(b, f)), foldMap: (M) => { const foldMapOM = foldMapO(M) return (fa, f) => pipe(fa, foldMapOM(f)) }, reduceRight: (fa, b, f) => pipe(fa, reduceRightO(b, f)) } } /** * @category folding * @since 2.11.0 */ export const reduceWithIndex = ( O: Ord ): ((b: B, f: (k: K, b: B, a: A) => B) => (m: ReadonlyMap) => B) => { const keysO = keys(O) return (b, f) => (m) => { let out = b for (const k of keysO(m)) { out = f(k, out, m.get(k)!) } return out } } /** * @category folding * @since 2.11.0 */ export const foldMapWithIndex = ( O: Ord ): ((M: Monoid) => (f: (k: K, a: A) => M) => (m: ReadonlyMap) => M) => { const keysO = keys(O) return (M) => (f) => (m) => { let out = M.empty for (const k of keysO(m)) { out = M.concat(out, f(k, m.get(k)!)) } return out } } /** * @category folding * @since 2.11.0 */ export const reduceRightWithIndex = ( O: Ord ): ((b: B, f: (k: K, a: A, b: B) => B) => (m: ReadonlyMap) => B) => { const keysO = keys(O) return (b, f) => (m) => { let out = b const ks = keysO(m) const len = ks.length for (let i = len - 1; i >= 0; i--) { const k = ks[i] out = f(k, m.get(k)!, out) } return out } } /** * @category folding * @since 2.10.0 */ export const getFoldableWithIndex = (O: Ord): FoldableWithIndex2C => { const F = getFoldable(O) const reduceWithIndexO = reduceWithIndex(O) const foldMapWithIndexO = foldMapWithIndex(O) const reduceRightWithIndexO = reduceRightWithIndex(O) return { URI, _E: undefined as any, reduce: F.reduce, foldMap: F.foldMap, reduceRight: F.reduceRight, reduceWithIndex: (fa, b, f) => pipe(fa, reduceWithIndexO(b, f)), foldMapWithIndex: (M) => { const foldMapWithIndexOM = foldMapWithIndexO(M) return (fa, f) => pipe(fa, foldMapWithIndexOM(f)) }, reduceRightWithIndex: (fa, b, f) => pipe(fa, reduceRightWithIndexO(b, f)) } } /** * @category traversing * @since 2.10.0 */ export const getTraversable = (O: Ord): Traversable2C => { const TWI = getTraversableWithIndex(O) const F = getFoldable(O) return { URI, _E: undefined as any, map: _map, reduce: F.reduce, foldMap: F.foldMap, reduceRight: F.reduceRight, traverse: TWI.traverse, sequence: TWI.sequence } } /** * @category traversing * @since 2.10.0 */ export const getTraversableWithIndex = (O: Ord): TraversableWithIndex2C => { const FWI = getFoldableWithIndex(O) const keysO = keys(O) const traverseWithIndex = ( F: Applicative ): ((ta: ReadonlyMap, f: (k: K, a: A) => HKT) => HKT>) => { return (ta: ReadonlyMap, f: (k: K, a: A) => HKT) => { let fm: HKT> = F.of(new Map()) const ks = keysO(ta) const len = ks.length for (let i = 0; i < len; i++) { const key = ks[i] const a = ta.get(key)! fm = F.ap( F.map(fm, (m) => (b: B) => m.set(key, b)), f(key, a) ) } return fm } } const traverse = ( F: Applicative ): ((ta: ReadonlyMap, f: (a: A) => HKT) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta, f) => traverseWithIndexF(ta, (_, a) => f(a)) } const sequence = (F: Applicative): ((ta: ReadonlyMap>) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta) => traverseWithIndexF(ta, SK) } return { URI, _E: undefined as any, map: _map, mapWithIndex: _mapWithIndex, reduce: FWI.reduce, foldMap: FWI.foldMap, reduceRight: FWI.reduceRight, reduceWithIndex: FWI.reduceWithIndex, foldMapWithIndex: FWI.foldMapWithIndex, reduceRightWithIndex: FWI.reduceRightWithIndex, traverse, sequence, traverseWithIndex } } /** * @category filtering * @since 2.5.0 */ export function getWitherable(O: Ord): Witherable2C & TraversableWithIndex2C { const TWI = getTraversableWithIndex(O) return { URI, _E: undefined as any, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, reduce: TWI.reduce, foldMap: TWI.foldMap, reduceRight: TWI.reduceRight, traverse: TWI.traverse, sequence: TWI.sequence, mapWithIndex: _mapWithIndex, reduceWithIndex: TWI.reduceWithIndex, foldMapWithIndex: TWI.foldMapWithIndex, reduceRightWithIndex: TWI.reduceRightWithIndex, traverseWithIndex: TWI.traverseWithIndex, wilt: wiltDefault(TWI, Compactable), wither: witherDefault(TWI, Compactable) } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const union = ( E: Eq, M: Magma ): ((second: ReadonlyMap) => (first: ReadonlyMap) => ReadonlyMap) => { const lookupE = lookup(E) return (second) => (first) => { if (isEmpty(first)) { return second } if (isEmpty(second)) { return first } const out: Map = new Map() const firstEntries = first.entries() let e: Next while (!(e = firstEntries.next()).done) { const [k, a] = e.value const oka = lookupE(k)(second) if (_.isSome(oka)) { out.set(k, M.concat(a, oka.value)) } else { out.set(k, a) } } const secondEntries = second.entries() while (!(e = secondEntries.next()).done) { const [k, a] = e.value const oka = lookupE(k)(out) if (_.isNone(oka)) { out.set(k, a) } } return out } } /** * @since 2.11.0 */ export const intersection = ( E: Eq, M: Magma ): ((second: ReadonlyMap) => (first: ReadonlyMap) => ReadonlyMap) => { const lookupE = lookup(E) return (second) => (first) => { if (isEmpty(first) || isEmpty(second)) { return empty } const out: Map = new Map() const entries = first.entries() let e: Next while (!(e = entries.next()).done) { const [k, a] = e.value const oka = lookupE(k)(second) if (_.isSome(oka)) { out.set(k, M.concat(a, oka.value)) } } return out } } /** * @since 2.11.0 */ export const difference = ( E: Eq ): ((_second: ReadonlyMap) => (first: ReadonlyMap) => ReadonlyMap) => { const memberE = member(E) return (second: ReadonlyMap) => (first: ReadonlyMap) => { if (isEmpty(first)) { return second } if (isEmpty(second)) { return first } const out: Map = new Map() const firstEntries = first.entries() let e: Next while (!(e = firstEntries.next()).done) { const [k, a] = e.value if (!memberE(k)(second)) { out.set(k, a) } } const secondEntries = second.entries() while (!(e = secondEntries.next()).done) { const [k, a] = e.value if (!memberE(k)(first)) { out.set(k, a) } } return out } } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`upsertAt`](#upsertat) instead. * @category zone of death * @since 2.5.0 * @deprecated */ export const insertAt: (E: Eq) => (k: K, a: A) => (m: ReadonlyMap) => ReadonlyMap = upsertAt /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RM.Functor` instead of `RM.readonlyMap` * (where `RM` is from `import RM from 'fp-ts/ReadonlyMap'`) * * @category zone of death * @since 2.5.0 * @deprecated */ export const readonlyMap: Filterable2 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } ================================================ FILE: src/ReadonlyNonEmptyArray.ts ================================================ /** * Data structure which represents non-empty readonly arrays. * * ```ts * export type ReadonlyNonEmptyArray = ReadonlyArray & { * readonly 0: A * } * ``` * * Note that you don't need any conversion, a `ReadonlyNonEmptyArray` is a `ReadonlyArray`, * so all `ReadonlyArray`'s APIs can be used with a `ReadonlyNonEmptyArray` without further ado. * * @since 2.5.0 */ import { Alt1 } from './Alt' import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain' import { Comonad1 } from './Comonad' import { Endomorphism } from './Endomorphism' import { Eq, fromEquals } from './Eq' import { Extend1 } from './Extend' import { Foldable1 } from './Foldable' import { FoldableWithIndex1 } from './FoldableWithIndex' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { FunctorWithIndex1 } from './FunctorWithIndex' import { HKT } from './HKT' import * as _ from './internal' import { Monad1 } from './Monad' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { getMonoid, Ord } from './Ord' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyRecord } from './ReadonlyRecord' import { Refinement } from './Refinement' import * as Se from './Semigroup' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' import { PipeableTraverseWithIndex1, TraversableWithIndex1 } from './TraversableWithIndex' import Semigroup = Se.Semigroup // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.5.0 */ export type ReadonlyNonEmptyArray = ReadonlyArray & { readonly 0: A } // ------------------------------------------------------------------------------------- // internal // ------------------------------------------------------------------------------------- /** * @internal */ export const empty: ReadonlyArray = _.emptyReadonlyArray /** * @internal */ export const isNonEmpty: (as: ReadonlyArray) => as is ReadonlyNonEmptyArray = _.isNonEmpty /** * @internal */ export const isOutOfBound = (i: number, as: ReadonlyArray): boolean => i < 0 || i >= as.length /** * @internal */ export const prependW = (head: B) => (tail: ReadonlyArray): ReadonlyNonEmptyArray => [head, ...tail] /** * @internal */ export const prepend: (head: A) => (tail: ReadonlyArray) => ReadonlyNonEmptyArray = prependW /** * @internal */ export const appendW = (end: B) => (init: ReadonlyArray): ReadonlyNonEmptyArray => [...init, end] as any /** * @internal */ export const append: (end: A) => (init: ReadonlyArray) => ReadonlyNonEmptyArray = appendW /** * @internal */ export const unsafeInsertAt = (i: number, a: A, as: ReadonlyArray): ReadonlyNonEmptyArray => { if (isNonEmpty(as)) { const xs = _.fromReadonlyNonEmptyArray(as) xs.splice(i, 0, a) return xs } return [a] } /** * @internal */ export const unsafeUpdateAt = (i: number, a: A, as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { if (as[i] === a) { return as } else { const xs = _.fromReadonlyNonEmptyArray(as) xs[i] = a return xs } } /** * Remove duplicates from a `ReadonlyNonEmptyArray`, keeping the first occurrence of an element. * * @example * import { uniq } from 'fp-ts/ReadonlyNonEmptyArray' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2]) * * @since 2.11.0 */ export const uniq = (E: Eq) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { if (as.length === 1) { return as } const out: NonEmptyArray = [head(as)] const rest = tail(as) for (const a of rest) { if (out.every((o) => !E.equals(o, a))) { out.push(a) } } return out } /** * Sort the elements of a `ReadonlyNonEmptyArray` in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`, * etc... * * @example * import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' * import { contramap } from 'fp-ts/Ord' * import * as S from 'fp-ts/string' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * interface Person { * name: string * age: number * } * * const byName = pipe(S.Ord, contramap((p: Person) => p.name)) * * const byAge = pipe(N.Ord, contramap((p: Person) => p.age)) * * const sortByNameByAge = RNEA.sortBy([byName, byAge]) * * const persons: RNEA.ReadonlyNonEmptyArray = [ * { name: 'a', age: 1 }, * { name: 'b', age: 3 }, * { name: 'c', age: 2 }, * { name: 'b', age: 2 } * ] * * assert.deepStrictEqual(sortByNameByAge(persons), [ * { name: 'a', age: 1 }, * { name: 'b', age: 2 }, * { name: 'b', age: 3 }, * { name: 'c', age: 2 } * ]) * * @since 2.11.0 */ export const sortBy = ( ords: ReadonlyArray> ): ((as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray) => { if (isNonEmpty(ords)) { const M = getMonoid() return sort(ords.reduce(M.concat, M.empty)) } return identity } /** * @since 2.11.0 */ export const union = ( E: Eq ): ((second: ReadonlyNonEmptyArray) => (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray) => { const uniqE = uniq(E) return (second) => (first) => uniqE(pipe(first, concat(second))) } /** * Rotate a `ReadonlyNonEmptyArray` by `n` steps. * * @example * import { rotate } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) * assert.deepStrictEqual(rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) * * @since 2.11.0 */ export const rotate = (n: number) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { const len = as.length const m = Math.round(n) % len if (isOutOfBound(Math.abs(m), as) || m === 0) { return as } if (m < 0) { const [f, s] = splitAt(-m)(as) return pipe(s, concat(f)) } else { return rotate(m - len)(as) } } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Return a `ReadonlyNonEmptyArray` from a `ReadonlyArray` returning `none` if the input is empty. * * @category conversions * @since 2.5.0 */ export const fromReadonlyArray = (as: ReadonlyArray): Option> => isNonEmpty(as) ? _.some(as) : _.none /** * Return a `ReadonlyNonEmptyArray` of length `n` with element `i` initialized with `f(i)`. * * **Note**. `n` is normalized to a natural number. * * @example * import { makeBy } from 'fp-ts/ReadonlyNonEmptyArray' * import { pipe } from 'fp-ts/function' * * const double = (n: number): number => n * 2 * assert.deepStrictEqual(pipe(5, makeBy(double)), [0, 2, 4, 6, 8]) * * @category constructors * @since 2.11.0 */ export const makeBy = (f: (i: number) => A) => (n: number): ReadonlyNonEmptyArray => { const j = Math.max(0, Math.floor(n)) const out: NonEmptyArray = [f(0)] for (let i = 1; i < j; i++) { out.push(f(i)) } return out } /** * Create a `ReadonlyNonEmptyArray` containing a value repeated the specified number of times. * * **Note**. `n` is normalized to a natural number. * * @example * import { replicate } from 'fp-ts/ReadonlyNonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(3, replicate('a')), ['a', 'a', 'a']) * * @category constructors * @since 2.11.0 */ export const replicate = (a: A): ((n: number) => ReadonlyNonEmptyArray) => makeBy(() => a) /** * Create a `ReadonlyNonEmptyArray` containing a range of integers, including both endpoints. * * @example * import { range } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(range(1, 5), [1, 2, 3, 4, 5]) * * @category constructors * @since 2.11.0 */ export const range = (start: number, end: number): ReadonlyNonEmptyArray => start <= end ? makeBy((i) => start + i)(end - start + 1) : [start] /** * Return the tuple of the `head` and the `tail`. * * @example * import { unprepend } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(unprepend([1, 2, 3, 4]), [1, [2, 3, 4]]) * * @since 2.9.0 */ export const unprepend = (as: ReadonlyNonEmptyArray): readonly [A, ReadonlyArray] => [head(as), tail(as)] /** * Return the tuple of the `init` and the `last`. * * @example * import { unappend } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) * * @since 2.9.0 */ export const unappend = (as: ReadonlyNonEmptyArray): readonly [ReadonlyArray, A] => [init(as), last(as)] /** * @category conversions * @since 2.5.0 */ export const fromArray = (as: Array): Option> => fromReadonlyArray(as.slice()) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export function concatW( second: ReadonlyNonEmptyArray ): (first: ReadonlyArray) => ReadonlyNonEmptyArray export function concatW( second: ReadonlyArray ): (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray export function concatW(second: ReadonlyArray): (first: ReadonlyNonEmptyArray) => ReadonlyArray { return (first: ReadonlyNonEmptyArray) => first.concat(second) } /** * @since 2.5.0 */ export function concat(second: ReadonlyNonEmptyArray): (first: ReadonlyArray) => ReadonlyNonEmptyArray export function concat(second: ReadonlyArray): (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray /** @deprecated */ export function concat(first: ReadonlyArray, second: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray /** @deprecated */ export function concat(first: ReadonlyNonEmptyArray, second: ReadonlyArray): ReadonlyNonEmptyArray export function concat( x: ReadonlyArray, y?: ReadonlyArray ): ReadonlyArray | ((y: ReadonlyNonEmptyArray) => ReadonlyArray) { return y ? x.concat(y) : (y) => y.concat(x) } /** * @since 2.5.0 */ export const reverse = (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => as.length === 1 ? as : [last(as), ...as.slice(0, -1).reverse()] /** * Group equal, consecutive elements of a `ReadonlyArray` into `ReadonlyNonEmptyArray`s. * * @example * import { group } from 'fp-ts/ReadonlyNonEmptyArray' * import * as N from 'fp-ts/number' * * assert.deepStrictEqual(group(N.Eq)([1, 2, 1, 1]), [ * [1], * [2], * [1, 1] * ]) * * @since 2.5.0 */ export function group(E: Eq): { (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray> (as: ReadonlyArray): ReadonlyArray> } export function group(E: Eq): (as: ReadonlyArray) => ReadonlyArray> { return (as) => { const len = as.length if (len === 0) { return empty } const out: Array> = [] let head: A = as[0] let nea: NonEmptyArray = [head] for (let i = 1; i < len; i++) { const a = as[i] if (E.equals(a, head)) { nea.push(a) } else { out.push(nea) head = a nea = [head] } } out.push(nea) return out } } /** * Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning * function on each element, and grouping the results according to values returned * * @example * import { groupBy } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(groupBy((s: string) => String(s.length))(['a', 'b', 'ab']), { * '1': ['a', 'b'], * '2': ['ab'] * }) * * @since 2.5.0 */ export const groupBy = (f: (a: A) => string) => (as: ReadonlyArray): ReadonlyRecord> => { const out: Record> = {} for (const a of as) { const k = f(a) if (_.has.call(out, k)) { out[k].push(a) } else { out[k] = [a] } } return out } /** * @since 2.5.0 */ export const sort = (O: Ord) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => as.length === 1 ? as : (as.slice().sort(O.compare) as any) /** * @since 2.5.0 */ export const updateAt = (i: number, a: A): ((as: ReadonlyNonEmptyArray) => Option>) => modifyAt(i, () => a) /** * @since 2.5.0 */ export const modifyAt = (i: number, f: (a: A) => A) => (as: ReadonlyNonEmptyArray): Option> => isOutOfBound(i, as) ? _.none : _.some(unsafeUpdateAt(i, f(as[i]), as)) /** * @since 2.5.1 */ export const zipWith = ( as: ReadonlyNonEmptyArray, bs: ReadonlyNonEmptyArray, f: (a: A, b: B) => C ): ReadonlyNonEmptyArray => { const cs: NonEmptyArray = [f(as[0], bs[0])] const len = Math.min(as.length, bs.length) for (let i = 1; i < len; i++) { cs[i] = f(as[i], bs[i]) } return cs } /** * @since 2.5.1 */ export function zip( bs: ReadonlyNonEmptyArray ): (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray export function zip( as: ReadonlyNonEmptyArray, bs: ReadonlyNonEmptyArray ): ReadonlyNonEmptyArray export function zip( as: ReadonlyNonEmptyArray, bs?: ReadonlyNonEmptyArray ): ReadonlyNonEmptyArray | ((bs: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray) { if (bs === undefined) { return (bs) => zip(bs, as) } return zipWith(as, bs, (a, b) => [a, b]) } /** * @since 2.5.1 */ export const unzip = ( abs: ReadonlyNonEmptyArray ): readonly [ReadonlyNonEmptyArray, ReadonlyNonEmptyArray] => { const fa: NonEmptyArray = [abs[0][0]] const fb: NonEmptyArray = [abs[0][1]] for (let i = 1; i < abs.length; i++) { fa[i] = abs[i][0] fb[i] = abs[i][1] } return [fa, fb] } /** * Prepend an element to every member of a `ReadonlyNonEmptyArray`. * * @example * import { prependAll } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4]) * * @since 2.10.0 */ export const prependAll = (middle: A) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { const out: NonEmptyArray = [middle, as[0]] for (let i = 1; i < as.length; i++) { out.push(middle, as[i]) } return out } /** * Places an element in between members of a `ReadonlyNonEmptyArray`. * * @example * import { intersperse } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4]) * * @since 2.9.0 */ export const intersperse = (middle: A) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { const rest = tail(as) return isNonEmpty(rest) ? pipe(rest, prependAll(middle), prepend(head(as))) : as } /** * @category sequencing * @since 2.10.0 */ export const chainWithIndex = (f: (i: number, a: A) => ReadonlyNonEmptyArray) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { const out: NonEmptyArray = _.fromReadonlyNonEmptyArray(f(0, head(as))) for (let i = 1; i < as.length; i++) { const bs = f(i, as[i]) for (let j = 0; j < bs.length; j++) { out.push(bs[j]) } } return out } /** * A useful recursion pattern for processing a `ReadonlyNonEmptyArray` to produce a new `ReadonlyNonEmptyArray`, often used for "chopping" up the input * `ReadonlyNonEmptyArray`. Typically `chop` is called with some function that will consume an initial prefix of the `ReadonlyNonEmptyArray` and produce a * value and the tail of the `ReadonlyNonEmptyArray`. * * @since 2.10.0 */ export const chop = (f: (as: ReadonlyNonEmptyArray) => readonly [B, ReadonlyArray]) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { const [b, rest] = f(as) const out: NonEmptyArray = [b] let next: ReadonlyArray = rest while (isNonEmpty(next)) { const [b, rest] = f(next) out.push(b) next = rest } return out } /** * Splits a `ReadonlyNonEmptyArray` into two pieces, the first piece has max `n` elements. * * @since 2.10.0 */ export const splitAt = (n: number) => (as: ReadonlyNonEmptyArray): readonly [ReadonlyNonEmptyArray, ReadonlyArray] => { const m = Math.max(1, n) return m >= as.length ? [as, empty] : [pipe(as.slice(1, m), prepend(head(as))), as.slice(m)] } /** * Splits a `ReadonlyNonEmptyArray` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the `ReadonlyNonEmptyArray`. * * @since 2.10.0 */ export const chunksOf = ( n: number ): ((as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray>) => chop(splitAt(n)) const _map: Functor1['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _mapWithIndex: FunctorWithIndex1['mapWithIndex'] = (fa, f) => pipe(fa, mapWithIndex(f)) const _ap: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _extend: Extend1['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _reduce: Foldable1['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable1['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable1['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _traverse: Traversable1['traverse'] = ( F: ApplicativeHKT ): ((ta: ReadonlyNonEmptyArray, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) /* istanbul ignore next */ const _reduceWithIndex: FoldableWithIndex1['reduceWithIndex'] = (fa, b, f) => pipe(fa, reduceWithIndex(b, f)) /* istanbul ignore next */ const _foldMapWithIndex: FoldableWithIndex1['foldMapWithIndex'] = (M) => { const foldMapWithIndexM = foldMapWithIndex(M) return (fa, f) => pipe(fa, foldMapWithIndexM(f)) } /* istanbul ignore next */ const _reduceRightWithIndex: FoldableWithIndex1['reduceRightWithIndex'] = (fa, b, f) => pipe(fa, reduceRightWithIndex(b, f)) /* istanbul ignore next */ const _traverseWithIndex: TraversableWithIndex1['traverseWithIndex'] = ( F: ApplicativeHKT ): ((ta: ReadonlyNonEmptyArray, f: (i: number, a: A) => HKT) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (ta, f) => pipe(ta, traverseWithIndexF(f)) } /** * @category constructors * @since 2.5.0 */ export const of: (a: A) => ReadonlyNonEmptyArray = _.singleton /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @example * import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3] as RNEA.ReadonlyNonEmptyArray, * RNEA.altW(() => ['a', 'b']) * ), * [1, 2, 3, 'a', 'b'] * ) * * @category error handling * @since 2.9.0 */ export const altW = (that: LazyArg>) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => pipe(as, concatW(that())) /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * In case of `ReadonlyNonEmptyArray` concatenates the inputs into a single array. * * @example * import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RNEA.alt(() => [4, 5]) * ), * [1, 2, 3, 4, 5] * ) * * @category error handling * @since 2.6.2 */ export const alt: ( that: LazyArg> ) => (as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray = altW /** * @since 2.5.0 */ export const ap = ( as: ReadonlyNonEmptyArray ): ((fab: ReadonlyNonEmptyArray<(a: A) => B>) => ReadonlyNonEmptyArray) => flatMap((f) => pipe(as, map(f))) /** * @example * import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RNEA.flatMap((n) => [`a${n}`, `b${n}`]) * ), * ['a1', 'b1', 'a2', 'b2', 'a3', 'b3'] * ) * * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A, i: number) => ReadonlyNonEmptyArray): (ma: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray (ma: ReadonlyNonEmptyArray, f: (a: A, i: number) => ReadonlyNonEmptyArray): ReadonlyNonEmptyArray } = /*#__PURE__*/ dual( 2, (ma: ReadonlyNonEmptyArray, f: (a: A, i: number) => ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => pipe( ma, chainWithIndex((i, a) => f(a, i)) ) ) /** * @since 2.5.0 */ export const extend = (f: (as: ReadonlyNonEmptyArray) => B) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { let next: ReadonlyArray = tail(as) const out: NonEmptyArray = [f(as)] while (isNonEmpty(next)) { out.push(f(next)) next = tail(next) } return out } /** * @since 2.5.0 */ export const duplicate: (ma: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray> = /*#__PURE__*/ extend(identity) /** * @category sequencing * @since 2.5.0 */ export const flatten: (mma: ReadonlyNonEmptyArray>) => ReadonlyNonEmptyArray = /*#__PURE__*/ flatMap(identity) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.5.0 */ export const map = (f: (a: A) => B): ((as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray) => mapWithIndex((_, a) => f(a)) /** * @category mapping * @since 2.5.0 */ export const mapWithIndex = (f: (i: number, a: A) => B) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => { const out: NonEmptyArray = [f(0, head(as))] for (let i = 1; i < as.length; i++) { out.push(f(i, as[i])) } return out } /** * @category folding * @since 2.5.0 */ export const reduce = (b: B, f: (b: B, a: A) => B): ((as: ReadonlyNonEmptyArray) => B) => reduceWithIndex(b, (_, b, a) => f(b, a)) /** * **Note**. The constraint is relaxed: a `Semigroup` instead of a `Monoid`. * * @category folding * @since 2.5.0 */ export const foldMap = (S: Semigroup) => (f: (a: A) => S) => (as: ReadonlyNonEmptyArray): S => as.slice(1).reduce((s, a) => S.concat(s, f(a)), f(as[0])) /** * @category folding * @since 2.5.0 */ export const reduceRight = (b: B, f: (a: A, b: B) => B): ((as: ReadonlyNonEmptyArray) => B) => reduceRightWithIndex(b, (_, b, a) => f(b, a)) /** * @category folding * @since 2.5.0 */ export const reduceWithIndex = (b: B, f: (i: number, b: B, a: A) => B) => (as: ReadonlyNonEmptyArray): B => as.reduce((b, a, i) => f(i, b, a), b) /** * **Note**. The constraint is relaxed: a `Semigroup` instead of a `Monoid`. * * @category folding * @since 2.5.0 */ export const foldMapWithIndex = (S: Semigroup) => (f: (i: number, a: A) => S) => (as: ReadonlyNonEmptyArray): S => as.slice(1).reduce((s, a, i) => S.concat(s, f(i + 1, a)), f(0, as[0])) /** * @category folding * @since 2.5.0 */ export const reduceRightWithIndex = (b: B, f: (i: number, a: A, b: B) => B) => (as: ReadonlyNonEmptyArray): B => as.reduceRight((b, a, i) => f(i, a, b), b) /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT) => (as: ReadonlyNonEmptyArray) => HKT>) => { const traverseWithIndexF = traverseWithIndex(F) return (f) => traverseWithIndexF((_, a) => f(a)) } /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = ( F: ApplicativeHKT ): ((as: ReadonlyNonEmptyArray>) => HKT>) => traverseWithIndex(F)(SK) /** * @category sequencing * @since 2.6.3 */ export const traverseWithIndex: PipeableTraverseWithIndex1 = (F: ApplicativeHKT) => (f: (i: number, a: A) => HKT) => (as: ReadonlyNonEmptyArray): HKT> => { let out: HKT> = F.map(f(0, head(as)), of) for (let i = 1; i < as.length; i++) { out = F.ap( F.map(out, (bs) => (b: B) => pipe(bs, append(b))), f(i, as[i]) ) } return out } /** * @category Comonad * @since 2.6.3 */ export const extract: Comonad1['extract'] = _.head /** * @category type lambdas * @since 2.5.0 */ export const URI = 'ReadonlyNonEmptyArray' /** * @category type lambdas * @since 2.5.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: ReadonlyNonEmptyArray } } /** * @category instances * @since 2.5.0 */ export const getShow = (S: Show): Show> => ({ show: (as) => `[${as.map(S.show).join(', ')}]` }) /** * Builds a `Semigroup` instance for `ReadonlyNonEmptyArray` * * @category instances * @since 2.5.0 */ export const getSemigroup = (): Semigroup> => ({ concat }) /** * @example * import { getEq } from 'fp-ts/ReadonlyNonEmptyArray' * import * as N from 'fp-ts/number' * * const E = getEq(N.Eq) * assert.strictEqual(E.equals([1, 2], [1, 2]), true) * assert.strictEqual(E.equals([1, 2], [1, 3]), false) * * @category instances * @since 2.5.0 */ export const getEq = (E: Eq): Eq> => fromEquals((xs, ys) => xs.length === ys.length && xs.every((x, i) => E.equals(x, ys[i]))) /** * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq): Semigroup> => { const unionE = union(E) return { concat: (first, second) => unionE(second)(first) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.7.0 */ export const FunctorWithIndex: FunctorWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.5.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.5.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as RA from 'fp-ts/ReadonlyArray' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual( * pipe( * [1, 2, 3], * RA.chainFirst(() => ['a', 'b']) * ), * [1, 1, 2, 2, 3, 3] * ) * * @category sequencing * @since 2.5.0 */ export const chainFirst: ( f: (a: A) => ReadonlyNonEmptyArray ) => (first: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray = /*#__PURE__*/ chainFirst_(Chain) /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const FoldableWithIndex: FoldableWithIndex1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.7.0 */ export const TraversableWithIndex: TraversableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverseWithIndex: _traverseWithIndex } /** * @category instances * @since 2.7.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad1 = { URI, map: _map, extend: _extend, extract } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: ReadonlyNonEmptyArray<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ bind_(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.5.0 */ export const head: (as: ReadonlyNonEmptyArray) => A = extract /** * @since 2.5.0 */ export const tail: (as: ReadonlyNonEmptyArray) => ReadonlyArray = _.tail /** * @since 2.5.0 */ export const last = (as: ReadonlyNonEmptyArray): A => as[as.length - 1] /** * Get all but the last element of a non empty array, creating a new array. * * @example * import { init } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(init([1, 2, 3]), [1, 2]) * assert.deepStrictEqual(init([1]), []) * * @since 2.5.0 */ export const init = (as: ReadonlyNonEmptyArray): ReadonlyArray => as.slice(0, -1) /** * @since 2.5.0 */ export const min = (O: Ord): ((as: ReadonlyNonEmptyArray) => A) => { const S = Se.min(O) return (as) => as.reduce(S.concat) } /** * @since 2.5.0 */ export const max = (O: Ord): ((as: ReadonlyNonEmptyArray) => A) => { const S = Se.max(O) return (as) => as.reduce(S.concat) } /** * @since 2.10.0 */ export const concatAll = (S: Semigroup) => (as: ReadonlyNonEmptyArray): A => as.reduce(S.concat) /** * Break a `ReadonlyArray` into its first element and remaining elements. * * @category pattern matching * @since 2.11.0 */ export const matchLeft = (f: (head: A, tail: ReadonlyArray) => B) => (as: ReadonlyNonEmptyArray): B => f(head(as), tail(as)) /** * Break a `ReadonlyArray` into its initial elements and the last element. * * @category pattern matching * @since 2.11.0 */ export const matchRight = (f: (init: ReadonlyArray, last: A) => B) => (as: ReadonlyNonEmptyArray): B => f(init(as), last(as)) /** * Apply a function to the head, creating a new `ReadonlyNonEmptyArray`. * * @since 2.11.0 */ export const modifyHead = (f: Endomorphism) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => [f(head(as)), ...tail(as)] /** * Change the head, creating a new `ReadonlyNonEmptyArray`. * * @since 2.11.0 */ export const updateHead = (a: A): ((as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray) => modifyHead(() => a) /** * Apply a function to the last element, creating a new `ReadonlyNonEmptyArray`. * * @since 2.11.0 */ export const modifyLast = (f: Endomorphism) => (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray => pipe(init(as), append(f(last(as)))) /** * Change the last element, creating a new `ReadonlyNonEmptyArray`. * * @since 2.11.0 */ export const updateLast = (a: A): ((as: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray) => modifyLast(() => a) /** * Places an element in between members of a `ReadonlyNonEmptyArray`, then folds the results using the provided `Semigroup`. * * @example * import * as S from 'fp-ts/string' * import { intercalate } from 'fp-ts/ReadonlyNonEmptyArray' * * assert.deepStrictEqual(intercalate(S.Semigroup)('-')(['a', 'b', 'c']), 'a-b-c') * * @since 2.12.0 */ export const intercalate = (S: Semigroup): ((middle: A) => (as: ReadonlyNonEmptyArray) => A) => { const concatAllS = concatAll(S) return (middle) => flow(intersperse(middle), concatAllS) } // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.5.0 */ export const chain: ( f: (a: A) => ReadonlyNonEmptyArray ) => (ma: ReadonlyNonEmptyArray) => ReadonlyNonEmptyArray = flatMap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This is just `sort` followed by `group`. * * @category zone of death * @since 2.5.0 * @deprecated */ export function groupSort(O: Ord): { (as: ReadonlyNonEmptyArray): ReadonlyNonEmptyArray> (as: ReadonlyArray): ReadonlyArray> } export function groupSort(O: Ord): (as: ReadonlyArray) => ReadonlyArray> { const sortO = sort(O) const groupO = group(O) return (as) => (isNonEmpty(as) ? groupO(sortO(as)) : empty) } /** * Use [`filter`](./ReadonlyArray.ts.html#filter) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export function filter( refinement: Refinement ): (as: ReadonlyNonEmptyArray) => Option> export function filter( predicate: Predicate ): (bs: ReadonlyNonEmptyArray) => Option> export function filter(predicate: Predicate): (as: ReadonlyNonEmptyArray) => Option> export function filter(predicate: Predicate): (as: ReadonlyNonEmptyArray) => Option> { return filterWithIndex((_, a) => predicate(a)) } /** * Use [`filterWithIndex`](./ReadonlyArray.ts.html#filterwithindex) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const filterWithIndex = (predicate: (i: number, a: A) => boolean) => (as: ReadonlyNonEmptyArray): Option> => fromReadonlyArray(as.filter((a, i) => predicate(i, a))) /** * Use [`unprepend`](#unprepend) instead. * * @category zone of death * @since 2.10.0 * @deprecated */ export const uncons: (as: ReadonlyNonEmptyArray) => readonly [A, ReadonlyArray] = unprepend /** * Use [`unappend`](#unappend) instead. * * @category zone of death * @since 2.10.0 * @deprecated */ export const unsnoc: (as: ReadonlyNonEmptyArray) => readonly [ReadonlyArray, A] = unappend /** * Use [`prepend`](./ReadonlyArray.ts.html#prepend) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export function cons(head: A): (tail: ReadonlyArray) => ReadonlyNonEmptyArray /** @deprecated */ export function cons(head: A, tail: ReadonlyArray): ReadonlyNonEmptyArray export function cons( head: A, tail?: ReadonlyArray ): ReadonlyNonEmptyArray | ((tail: ReadonlyArray) => ReadonlyNonEmptyArray) { return tail === undefined ? prepend(head) : pipe(tail, prepend(head)) } /** * Use [`append`](./ReadonlyArray.ts.html#append) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const snoc = (init: ReadonlyArray, end: A): ReadonlyNonEmptyArray => pipe(init, concat([end])) /** * Use [`insertAt`](./ReadonlyArray.ts.html#insertat) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const insertAt = (i: number, a: A) => (as: ReadonlyArray): Option> => i < 0 || i > as.length ? _.none : _.some(unsafeInsertAt(i, a, as)) /** * Use [`prependAll`](#prependall) instead. * * @category zone of death * @since 2.9.0 * @deprecated */ export const prependToAll = prependAll /** * Use [`concatAll`](#concatall) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const fold = concatAll /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RNEA.Functor` instead of `RNEA.readonlyNonEmptyArray` * (where `RNEA` is from `import RNEA from 'fp-ts/ReadonlyNonEmptyArray'`) * * @category zone of death * @since 2.5.0 * @deprecated */ export const readonlyNonEmptyArray: Monad1 & Comonad1 & TraversableWithIndex1 & FunctorWithIndex1 & FoldableWithIndex1 & Alt1 = { URI, of, map: _map, mapWithIndex: _mapWithIndex, ap: _ap, chain: flatMap, extend: _extend, extract: extract, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, reduceWithIndex: _reduceWithIndex, foldMapWithIndex: _foldMapWithIndex, reduceRightWithIndex: _reduceRightWithIndex, traverseWithIndex: _traverseWithIndex, alt: _alt } ================================================ FILE: src/ReadonlyRecord.ts ================================================ /** * The `ReadonlyRecord.ts` module enables dealing in a functional way with * Typescript's `Readonly>` type. That is similar to the * `Record.ts` module, but for a record with all properties * declared as `readonly`. * * @since 2.5.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C, Applicative4 } from './Applicative' import { Compactable1 } from './Compactable' import { Either } from './Either' import { Eq, fromEquals } from './Eq' import { Filterable1 } from './Filterable' import { FilterableWithIndex1, PredicateWithIndex, RefinementWithIndex } from './FilterableWithIndex' import { Foldable as FoldableHKT, Foldable1, Foldable2, Foldable3 } from './Foldable' import { FoldableWithIndex1 } from './FoldableWithIndex' import { flow, identity, pipe, SK } from './function' import { flap as flap_, Functor1 } from './Functor' import { FunctorWithIndex1 } from './FunctorWithIndex' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import * as _ from './internal' import { Magma } from './Magma' import { Monoid } from './Monoid' import { Option } from './Option' import { Ord } from './Ord' import { Predicate } from './Predicate' import { Refinement } from './Refinement' import * as Se from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' import * as S from './string' import { Traversable1 } from './Traversable' import { TraversableWithIndex1 } from './TraversableWithIndex' import { Unfoldable, Unfoldable1 } from './Unfoldable' import { PipeableWilt1, PipeableWither1, wiltDefault, Witherable1, witherDefault } from './Witherable' import Semigroup = Se.Semigroup // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.5.0 */ export type ReadonlyRecord = Readonly> /** * Builds a `ReadonlyRecord` by copying a `Record`. * * @example * import { ReadonlyRecord, fromRecord } from "fp-ts/ReadonlyRecord" * * const x: Record = { a: 1, b: 2 }; * const y: ReadonlyRecord = fromRecord(x); * assert.deepStrictEqual(x,y); * // `y.a = 5` gives compiler error * * @category conversions * @since 2.5.0 */ export const fromRecord = (r: Record): ReadonlyRecord => Object.assign({}, r) /** * Builds a mutable `Record` from a `ReadonlyRecord`. * * @example * import { ReadonlyRecord, toRecord } from "fp-ts/ReadonlyRecord" * * const x: ReadonlyRecord = { a: 1, b: 2 }; * const y: Record = toRecord(x); * assert.deepStrictEqual(x,y); * y.a = 5; // it's ok, y is mutable * * @category conversions * @since 2.5.0 */ export const toRecord = (r: ReadonlyRecord): Record => Object.assign({}, r) /** * Calculate the number of key/value pairs in a `ReadonlyRecord`, * * @example * import { size } from "fp-ts/ReadonlyRecord"; * * assert.deepStrictEqual(size({ a: true, b: 2, c: "three" }), 3); * * @since 2.5.0 */ export const size = (r: ReadonlyRecord): number => Object.keys(r).length /** * Test whether a `ReadonlyRecord` is empty. * * @example * import { isEmpty } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual(isEmpty({}), true); * assert.deepStrictEqual(isEmpty({ a: 3 }), false); * @since 2.5.0 */ export const isEmpty = (r: ReadonlyRecord): boolean => { for (const k in r) { if (_.has.call(r, k)) { return false } } return true } const keys_ = (O: Ord) => (r: ReadonlyRecord): ReadonlyArray => (Object.keys(r) as any).sort(O.compare) /** * @since 2.5.0 */ export const keys: (r: ReadonlyRecord) => ReadonlyArray = /*#__PURE__*/ keys_(S.Ord) /** * Map a `ReadonlyRecord` into an `ReadonlyArray`. * * @example * import { collect } from 'fp-ts/ReadonlyRecord' * import { Ord } from 'fp-ts/string' * * const f = (k: string, a: A) => `${k.toUpperCase()}-${a}`; * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(collect(Ord)(f)(x), ["A-foo", "B-false", "C-3"]); * * @since 2.5.0 */ export function collect( O: Ord ): (f: (k: K, a: A) => B) => (r: ReadonlyRecord) => ReadonlyArray /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function collect(f: (k: K, a: A) => B): (r: ReadonlyRecord) => ReadonlyArray export function collect( O: Ord | ((k: string, a: A) => B) ): | ((f: (k: K, a: A) => B) => (r: ReadonlyRecord) => ReadonlyArray) | ((r: ReadonlyRecord) => ReadonlyArray) { if (typeof O === 'function') { return collect(S.Ord)(O) } const keysO = keys_(O) return (f: (k: K, a: A) => B) => (r: ReadonlyRecord) => { const out: Array = [] for (const key of keysO(r)) { out.push(f(key, r[key])) } return out } } /** * Get a sorted `ReadonlyArray` of the key/value pairs contained in a `ReadonlyRecord`. * * @example * import { toReadonlyArray } from 'fp-ts/ReadonlyRecord' * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(toReadonlyArray(x), [ * ["a", "foo"], * ["b", false], * ["c", 3], * ]); * * @category conversions * @since 2.5.0 */ export const toReadonlyArray: (r: ReadonlyRecord) => ReadonlyArray = /*#__PURE__*/ collect(S.Ord)((k, a) => [k, a]) /** * Unfolds a `ReadonlyRecord` into a list of key/value pairs. * * Given an `Unfoldable` class type `U` such as `array` or `readonlyArray`, * it uses the `unfold` function to create an instance of `U`, * providing an iterating function that iterates over each * key/value pair in the record sorted alphabetically by key. * * @example * import { array, readonlyArray } from 'fp-ts' * import { toUnfoldable } from 'fp-ts/ReadonlyRecord' * * assert.deepStrictEqual(toUnfoldable(array)({ b: 2, a: 1 }),[ [ 'a', 1 ], [ 'b', 2 ]]) * assert.deepStrictEqual(toUnfoldable(readonlyArray)({ b: 2, a: 1 }),[ [ 'a', 1 ], [ 'b', 2 ]]) * * @category conversions * @since 2.5.0 */ export function toUnfoldable( U: Unfoldable1 ): (r: ReadonlyRecord) => Kind export function toUnfoldable( U: Unfoldable ): (r: ReadonlyRecord) => HKT export function toUnfoldable(U: Unfoldable): (r: ReadonlyRecord) => HKT { return (r) => { const sas = toReadonlyArray(r) const len = sas.length return U.unfold(0, (b) => (b < len ? _.some([sas[b], b + 1]) : _.none)) } } /** * Insert or replace a key/value pair in a `ReadonlyRecord`. * * @example * import { upsertAt } from 'fp-ts/ReadonlyRecord' * * assert.deepStrictEqual(upsertAt("a", 5)({ a: 1, b: 2 }), { a: 5, b: 2 }); * assert.deepStrictEqual(upsertAt("c", 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 }); * * @since 2.10.0 */ export const upsertAt = (k: string, a: A) => (r: ReadonlyRecord): ReadonlyRecord => { if (_.has.call(r, k) && r[k] === a) { return r } const out: Record = Object.assign({}, r) out[k] = a return out } /** * Test whether or not a key exists in a `ReadonlyRecord`. * * Note. This function is not pipeable because is a `Refinement`. * * @example * import { has } from 'fp-ts/ReadonlyRecord' * * assert.deepStrictEqual(has("a", { a: 1, b: 2 }), true); * assert.deepStrictEqual(has("c", { a: 1, b: 2 }), false); * * @since 2.10.0 */ export const has = (k: string, r: ReadonlyRecord): k is K => _.has.call(r, k) /** * Delete a key and value from a `ReadonlyRecord`. * * @example * import { deleteAt } from 'fp-ts/ReadonlyRecord' * * assert.deepStrictEqual(deleteAt("a")({ a: 1, b: 2 }), { b: 2 }); * assert.deepStrictEqual(deleteAt("c")({ a: 1, b: 2 }), { a: 1, b: 2 }); * * @since 2.5.0 */ export function deleteAt( k: K ): (r: ReadonlyRecord) => ReadonlyRecord, A> export function deleteAt(k: string): (r: ReadonlyRecord) => ReadonlyRecord { return (r: ReadonlyRecord) => { if (!_.has.call(r, k)) { return r } const out: Record = Object.assign({}, r) delete out[k] return out } } /** * Replace a key/value pair in a `ReadonlyRecord`. * * @returns If the specified key exists it returns an `Option` containing a new `Record` * with the entry updated, otherwise it returns `None` * * @example * import { updateAt } from 'fp-ts/ReadonlyRecord' * import { option } from 'fp-ts' * * assert.deepStrictEqual(updateAt("a", 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })); * assert.deepStrictEqual(updateAt("c", 3)({ a: 1, b: 2 }), option.none); * * @since 2.5.0 */ export const updateAt = (k: string, a: A) => (r: ReadonlyRecord): Option> => { if (!has(k, r)) { return _.none } if (r[k] === a) { return _.some(r) } const out: Record = Object.assign({}, r) out[k] = a return _.some(out) } /** * Applies a mapping function to one specific key/value pair in a `ReadonlyRecord`. * * @returns If the specified key exists it returns an `Option` containing a new `Record` * with the entry updated, otherwise it returns `None` * * @example * import { modifyAt } from 'fp-ts/ReadonlyRecord' * import { option } from 'fp-ts' * * assert.deepStrictEqual(modifyAt("a", (x: number) => x * 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })); * assert.deepStrictEqual(modifyAt("c", (x: number) => x * 3)({ a: 1, b: 2 }), option.none); * * @since 2.5.0 */ export const modifyAt = (k: string, f: (a: A) => A) => (r: ReadonlyRecord): Option> => { if (!has(k, r)) { return _.none } const next = f(r[k]) if (next === r[k]) { return _.some(r) } const out: Record = Object.assign({}, r) out[k] = next return _.some(out) } /** * Delete a key and value from a `ReadonlyRecord`, returning the value as well as the subsequent `ReadonlyRecord`. * * @returns If the specified key exists it returns an `Option` containing a new `ReadonlyRecord` * with the entry removed, otherwise it returns `None` * * @example * import { pop } from 'fp-ts/ReadonlyRecord' * import { option } from 'fp-ts' * * assert.deepStrictEqual(pop("a")({ a: 1, b: 2, c: 3 }), option.some([1, { b: 2, c: 3 }])); * assert.deepStrictEqual(pop("x")({ a: 1, b: 2, c: 3 }), option.none); * * @since 2.5.0 */ export function pop( k: K ): ( r: ReadonlyRecord ) => Option, A>]> export function pop(k: string): (r: ReadonlyRecord) => Option]> { const deleteAtk = deleteAt(k) return (r) => { const oa = lookup(k, r) return _.isNone(oa) ? _.none : _.some([oa.value, deleteAtk(r)]) } } // TODO: remove non-curried overloading in v3 /** * Test whether one `ReadonlyRecord` contains all of the keys and values * contained in another `ReadonlyRecord`. * * @example * import { isSubrecord } from 'fp-ts/ReadonlyRecord' * import { string } from 'fp-ts' * * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar", c: "baz" })({ a: "foo", b: "bar", c: "baz" }), * true * ); * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar", c: "baz" })({ a: "foo", c: "baz" }), * true * ); * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar", c: "baz" })({ a: "foo", b: "not-bar", c: "baz" }), * false * ); * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar" })({ a: "foo", b: "bar", c: "baz" }), * false * ); * * @since 2.5.0 */ export function isSubrecord(E: Eq): { (that: ReadonlyRecord): (me: ReadonlyRecord) => boolean (me: ReadonlyRecord, that: ReadonlyRecord): boolean } export function isSubrecord( E: Eq ): ( me: ReadonlyRecord, that?: ReadonlyRecord ) => boolean | ((me: ReadonlyRecord) => boolean) { return (me, that?) => { if (that === undefined) { const isSubrecordE = isSubrecord(E) return (that) => isSubrecordE(that, me) } for (const k in me) { if (!_.has.call(that, k) || !E.equals(me[k], that[k])) { return false } } return true } } // TODO: remove non-curried overloading in v3 /** * Lookup the value for a key in a `ReadonlyRecord`. * * @returns If the specified key exists it returns an `Option` containing the value, * otherwise it returns `None` * * @example * import { lookup } from 'fp-ts/ReadonlyRecord' * import { option } from 'fp-ts' * * assert.deepStrictEqual(lookup("b")({ a: "foo", b: "bar" }), option.some("bar")); * assert.deepStrictEqual(lookup("c")({ a: "foo", b: "bar" }), option.none); * * @since 2.5.0 */ export function lookup(k: string): (r: ReadonlyRecord) => Option export function lookup(k: string, r: ReadonlyRecord): Option export function lookup( k: string, r?: ReadonlyRecord ): Option | ((r: ReadonlyRecord) => Option) { if (r === undefined) { return (r) => lookup(k, r) } return _.has.call(r, k) ? _.some(r[k]) : _.none } /** * @since 2.5.0 */ export const empty: ReadonlyRecord = {} /** * Map a `ReadonlyRecord` passing the keys to the iterating function. * * @example * import { mapWithIndex } from "fp-ts/ReadonlyRecord"; * * const f = (k: string, n: number) => `${k.toUpperCase()}-${n}`; * assert.deepStrictEqual(mapWithIndex(f)({ a: 3, b: 5 }), { a: "A-3", b: "B-5" }); * * @since 2.5.0 */ export function mapWithIndex( f: (k: K, a: A) => B ): (fa: ReadonlyRecord) => ReadonlyRecord export function mapWithIndex( f: (k: string, a: A) => B ): (fa: ReadonlyRecord) => ReadonlyRecord { return (r) => { const out: Record = {} for (const k in r) { if (_.has.call(r, k)) { out[k] = f(k, r[k]) } } return out } } /** * Map a `ReadonlyRecord` passing the values to the iterating function. * * @example * import { map } from "fp-ts/ReadonlyRecord"; * * const f = (n: number) => `-${n}-`; * assert.deepStrictEqual(map(f)({ a: 3, b: 5 }), { a: "-3-", b: "-5-" }); * * @since 2.5.0 */ export function map(f: (a: A) => B): (fa: ReadonlyRecord) => ReadonlyRecord export function map(f: (a: A) => B): (fa: ReadonlyRecord) => ReadonlyRecord { return mapWithIndex((_, a) => f(a)) } /** * Reduces a `ReadonlyRecord` passing each key/value pair to the iterating function. * Entries are processed in the order, sorted by key according to * the given `Ord`. * * @example * import { reduceWithIndex } from "fp-ts/ReadonlyRecord"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduceWithIndex(Ord)([] as string[], (k, b, a) => [...b, `${k}-${a}`])(x), [ * "a-foo", * "b-false", * "c-3", * ]); * * @since 2.5.0 */ export function reduceWithIndex( O: Ord ): (b: B, f: (k: K, b: B, a: A) => B) => (fa: ReadonlyRecord) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduceWithIndex( b: B, f: (k: K, b: B, a: A) => B ): (fa: ReadonlyRecord) => B export function reduceWithIndex( ...args: [Ord] | [B, (k: string, b: B, a: A) => B] ): | ((b: B, f: (k: string, b: B, a: A) => B) => (fa: ReadonlyRecord) => B) | ((fa: ReadonlyRecord) => B) { if (args.length === 2) { return reduceWithIndex(S.Ord)(...args) } const keysO = keys_(args[0]) return (b, f) => (fa) => { let out: B = b const ks = keysO(fa) const len = ks.length for (let i = 0; i < len; i++) { const k = ks[i] out = f(k, out, fa[k]) } return out } } /** * Map and fold a `ReadonlyRecord`. * Map the `ReadonlyRecord` passing each key/value pair to the iterating function. * Then fold the results using the provided `Monoid`. * * @example * import { foldMapWithIndex } from "fp-ts/ReadonlyRecord"; * import { Ord } from "fp-ts/string"; * import { Monoid } from "fp-ts/Monoid"; * * const m: Monoid = { empty: "", concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) }; * const f = (k:string, a: number) => `${k}-${a}` * const x = { c: 3, a: 1, b: 2 }; * assert.deepStrictEqual(foldMapWithIndex(Ord)(m)(f)(x), "a-1 -> b-2 -> c-3"); * * @since 2.5.0 */ export function foldMapWithIndex( O: Ord ): (M: Monoid) => (f: (k: K, a: A) => M) => (fa: ReadonlyRecord) => M /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function foldMapWithIndex( M: Monoid ): (f: (k: K, a: A) => M) => (fa: ReadonlyRecord) => M export function foldMapWithIndex( O: Ord | Monoid ): | ((M: Monoid) => (f: (k: string, a: A) => M) => (fa: ReadonlyRecord) => M) | ((f: (k: string, a: A) => M) => (fa: ReadonlyRecord) => M) { if ('compare' in O) { const keysO = keys_(O) return (M: Monoid) => (f: (k: string, a: A) => M) => (fa: ReadonlyRecord) => { let out: M = M.empty const ks = keysO(fa) const len = ks.length for (let i = 0; i < len; i++) { const k = ks[i] out = M.concat(out, f(k, fa[k])) } return out } } return foldMapWithIndex(S.Ord)(O) } /** * Same as `reduceWithIndex`, but reduce starting from the right * (i.e. in reverse order, from the last to the first entry according to * the given `Ord`). * * @example * import { reduceRightWithIndex } from "fp-ts/ReadonlyRecord"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduceRightWithIndex(Ord)([] as string[], (k, a, b) => [...b, `${k}-${a}`])(x), [ * "c-3", * "b-false", * "a-foo", * ]); * * @since 2.5.0 */ export function reduceRightWithIndex( O: Ord ): (b: B, f: (k: K, a: A, b: B) => B) => (fa: ReadonlyRecord) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduceRightWithIndex( b: B, f: (k: K, a: A, b: B) => B ): (fa: ReadonlyRecord) => B export function reduceRightWithIndex( ...args: [Ord] | [B, (k: string, a: A, b: B) => B] ): | ((b: B, f: (k: string, a: A, b: B) => B) => (fa: ReadonlyRecord) => B) | ((fa: ReadonlyRecord) => B) { if (args.length === 2) { return reduceRightWithIndex(S.Ord)(...args) } const keysO = keys_(args[0]) return (b, f) => (fa) => { let out: B = b const ks = keysO(fa) const len = ks.length for (let i = len - 1; i >= 0; i--) { const k = ks[i] out = f(k, fa[k], out) } return out } } /** * Create a `ReadonlyRecord` with one key/value pair. * * @example * import { singleton } from "fp-ts/ReadonlyRecord"; * * assert.deepStrictEqual(singleton("a", 1), { a: 1 }); * * @category constructors * @since 2.5.0 */ export const singleton = (k: string, a: A): ReadonlyRecord => ({ [k]: a }) /** * @since 2.5.0 */ export function traverseWithIndex( F: Applicative4 ): ( f: (k: K, a: A) => Kind4 ) => (ta: ReadonlyRecord) => Kind4> export function traverseWithIndex( F: Applicative3 ): ( f: (k: K, a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export function traverseWithIndex( F: Applicative3C ): ( f: (k: K, a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export function traverseWithIndex( F: Applicative2 ): ( f: (k: K, a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export function traverseWithIndex( F: Applicative2C ): ( f: (k: K, a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export function traverseWithIndex( F: Applicative1 ): ( f: (k: K, a: A) => Kind ) => (ta: ReadonlyRecord) => Kind> export function traverseWithIndex( F: Applicative ): (f: (k: K, a: A) => HKT) => (ta: ReadonlyRecord) => HKT> export function traverseWithIndex( F: Applicative ): (f: (k: string, a: A) => HKT) => (ta: ReadonlyRecord) => HKT> { const traverseWithIndexOF = _traverseWithIndex(S.Ord)(F) return (f) => (ta) => traverseWithIndexOF(ta, f) } /** * @since 2.5.0 */ export function traverse( F: Applicative4 ): ( f: (a: A) => Kind4 ) => (ta: ReadonlyRecord) => Kind4> export function traverse( F: Applicative3 ): ( f: (a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export function traverse( F: Applicative3C ): ( f: (a: A) => Kind3 ) => (ta: ReadonlyRecord) => Kind3> export function traverse( F: Applicative2 ): ( f: (a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export function traverse( F: Applicative2C ): ( f: (a: A) => Kind2 ) => (ta: ReadonlyRecord) => Kind2> export function traverse( F: Applicative1 ): (f: (a: A) => Kind) => (ta: ReadonlyRecord) => Kind> export function traverse( F: Applicative ): (f: (a: A) => HKT) => (ta: ReadonlyRecord) => HKT> export function traverse( F: Applicative ): (f: (a: A) => HKT) => (ta: ReadonlyRecord) => HKT> { const traverseOF = _traverse(S.Ord)(F) return (f) => (ta) => traverseOF(ta, f) } /** * `ReadonlyRecord` sequencing, * i.e., take a `ReadonlyRecord` in which elements are monads * and return a monad of a `ReadonlyRecord` of the base types. * The following example for instance shows sequencing * a `ReadonlyRecord>` * into an `Option>`. * * `sequence` in `ReadonlyRecord` is equivalent to `sequenceS` in `Apply.ts`. * * @example * import { sequence } from "fp-ts/ReadonlyRecord"; * import { option } from "fp-ts"; * import { sequenceS } from "fp-ts/Apply"; * * assert.deepStrictEqual( * sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), * option.some({ a: 1, b: 2 }) * ); * assert.deepStrictEqual(sequence(option.Applicative)({ a: option.some(1), b: option.none }), option.none); * assert.deepStrictEqual( * sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), * sequenceS(option.Applicative)({ a: option.some(1), b: option.some(2) }) * ); * * @since 2.5.0 */ export function sequence( F: Applicative3 ): (ta: ReadonlyRecord>) => Kind3> export function sequence( F: Applicative3C ): (ta: ReadonlyRecord>) => Kind3> export function sequence( F: Applicative2 ): (ta: ReadonlyRecord>) => Kind2> export function sequence( F: Applicative2C ): (ta: ReadonlyRecord>) => Kind2> export function sequence( F: Applicative1 ): (ta: ReadonlyRecord>) => Kind> export function sequence( F: Applicative ): (ta: ReadonlyRecord>) => HKT> export function sequence( F: Applicative ): (ta: ReadonlyRecord>) => HKT> { return _sequence(S.Ord)(F) } /** * @category filtering * @since 2.6.5 */ export const wither: PipeableWither1 = ( F: Applicative ): ((f: (a: A) => HKT>) => (fa: ReadonlyRecord) => HKT>) => { const traverseF = traverse(F) return (f) => (fa) => F.map(pipe(fa, traverseF(f)), compact) } /** * @category filtering * @since 2.6.5 */ export const wilt: PipeableWilt1 = ( F: Applicative ): (( f: (a: A) => HKT> ) => (fa: ReadonlyRecord) => HKT, ReadonlyRecord>>) => { const traverseF = traverse(F) return (f) => (fa) => F.map(pipe(fa, traverseF(f)), separate) } /** * Maps a `ReadonlyRecord` with a function returning an `Either` and * partitions the resulting `ReadonlyRecord` into `Left`s and `Right`s. * * @example * import { partitionMapWithIndex } from "fp-ts/ReadonlyRecord" * import { either } from "fp-ts" * * const f = (key: string, a: number) => * a >= 0 ? either.right(`${key} is >= 0 (${a})`) : either.left(`${key} is < 0 (${a})`); * assert.deepStrictEqual(partitionMapWithIndex(f)({ a: -1, b: 2, c: 123 }), { * left: { * a: "a is < 0 (-1)", * }, * right: { * b: "b is >= 0 (2)", * c: "c is >= 0 (123)", * }, * }); * * @since 2.5.0 */ export function partitionMapWithIndex( f: (key: K, a: A) => Either ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> export function partitionMapWithIndex( f: (key: string, a: A) => Either ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> { return (r) => { const left: Record = {} const right: Record = {} for (const k in r) { if (_.has.call(r, k)) { const e = f(k, r[k]) switch (e._tag) { case 'Left': left[k] = e.left break case 'Right': right[k] = e.right break } } } return separated(left, right) } } /** * Partition a `ReadonlyRecord` into two parts according to a predicate * that takes a key and a value. * * @example * import { partitionWithIndex } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual( * partitionWithIndex((key: string, a: number) => key.length <= 1 && a > 0)({ a: -1, b: 2, ccc: 7 }), * { * left: { * a: -1, * ccc: 7, * }, * right: { * b: 2, * }, * } * ); * * @since 2.5.0 */ export function partitionWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> export function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: ReadonlyRecord) => Separated, ReadonlyRecord> export function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> export function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: ReadonlyRecord) => Separated, ReadonlyRecord> { return (r) => { const left: Record = {} const right: Record = {} for (const k in r) { if (_.has.call(r, k)) { const a = r[k] if (predicateWithIndex(k, a)) { right[k] = a } else { left[k] = a } } } return separated(left, right) } } /** * Maps a `ReadonlyRecord` with an iterating function that takes key and value and * returns an `Option`, keeping only the `Some` values and discarding `None`s. * * @example * import { filterMapWithIndex } from "fp-ts/ReadonlyRecord" * import { option } from "fp-ts" * * const f = (key: string, a: number) => (a >= 0 ? option.some(`${key}${a}`) : option.none); * assert.deepStrictEqual(filterMapWithIndex(f)({ a: -1, b: 2, c: 3 }), { * b: "b2", * c: "c3", * }); * * @since 2.5.0 */ export function filterMapWithIndex( f: (key: K, a: A) => Option ): (fa: ReadonlyRecord) => ReadonlyRecord export function filterMapWithIndex( f: (key: string, a: A) => Option ): (fa: ReadonlyRecord) => ReadonlyRecord { return (r) => { const out: Record = {} for (const k in r) { if (_.has.call(r, k)) { const ob = f(k, r[k]) if (_.isSome(ob)) { out[k] = ob.value } } } return out } } /** * Produce a new `ReadonlyRecord` keeping only the entries that satisfy * a predicate taking key and value as input. * * @example * import { filterWithIndex } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual( * filterWithIndex((s: string, v: number) => s.length <= 1 && v > 0)({ a: 1, b: -2, ccc: 3 }), * { * a: 1, * } * ); * * @since 2.5.0 */ export function filterWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: ReadonlyRecord) => ReadonlyRecord export function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: ReadonlyRecord) => ReadonlyRecord export function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: ReadonlyRecord) => ReadonlyRecord export function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: ReadonlyRecord) => ReadonlyRecord { return (fa) => { const out: Record = {} let changed = false for (const key in fa) { if (_.has.call(fa, key)) { const a = fa[key] if (predicateWithIndex(key, a)) { out[key] = a } else { changed = true } } } return changed ? out : fa } } /** * Create a `ReadonlyRecord` from a foldable collection of key/value pairs, using the * specified `Magma` to combine values for duplicate keys. * * @since 2.5.0 */ export function fromFoldable( M: Magma, F: Foldable3 ): (fka: Kind3) => ReadonlyRecord export function fromFoldable( M: Magma, F: Foldable2 ): (fka: Kind2) => ReadonlyRecord export function fromFoldable( M: Magma, F: Foldable1 ): (fka: Kind) => ReadonlyRecord export function fromFoldable( M: Magma, F: FoldableHKT ): (fka: HKT) => ReadonlyRecord export function fromFoldable( M: Magma, F: FoldableHKT ): (fka: HKT) => ReadonlyRecord { const fromFoldableMapM = fromFoldableMap(M, F) return (fka) => fromFoldableMapM(fka, identity) } /** * Create a `ReadonlyRecord` from a foldable collection using the specified functions to: * * - map to key/value pairs * - combine values for duplicate keys. * * @example * import { last } from 'fp-ts/Semigroup' * import { Foldable, zip } from 'fp-ts/ReadonlyArray' * import { identity } from 'fp-ts/function' * import { ReadonlyRecord, fromFoldableMap } from 'fp-ts/ReadonlyRecord' * * export const zipObject = (keys: ReadonlyArray, values: ReadonlyArray): ReadonlyRecord => * fromFoldableMap(last(), Foldable)(zip(keys, values), identity) * * assert.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 }) * * interface User { * readonly id: string * readonly name: string * } * * const users: ReadonlyArray = [ * { id: 'id1', name: 'name1' }, * { id: 'id2', name: 'name2' }, * { id: 'id1', name: 'name3' } * ] * * assert.deepStrictEqual(fromFoldableMap(last(), Foldable)(users, user => [user.id, user]), { * id1: { id: 'id1', name: 'name3' }, * id2: { id: 'id2', name: 'name2' } * }) * * @since 2.5.0 */ export function fromFoldableMap( M: Magma, F: Foldable3 ): (fa: Kind3, f: (a: A) => readonly [string, B]) => ReadonlyRecord export function fromFoldableMap( M: Magma, F: Foldable2 ): (fa: Kind2, f: (a: A) => readonly [string, B]) => ReadonlyRecord export function fromFoldableMap( M: Magma, F: Foldable1 ): (fa: Kind, f: (a: A) => readonly [string, B]) => ReadonlyRecord export function fromFoldableMap( M: Magma, F: FoldableHKT ): (fa: HKT, f: (a: A) => readonly [string, B]) => ReadonlyRecord export function fromFoldableMap( M: Magma, F: FoldableHKT ): (fa: HKT, f: (a: A) => readonly [string, B]) => ReadonlyRecord { return (ta: HKT, f: (a: A) => readonly [string, B]) => { return F.reduce>(ta, {}, (r, a) => { const [k, b] = f(a) r[k] = _.has.call(r, k) ? M.concat(r[k], b) : b return r }) } } /** * Alias of [`toReadonlyArray`](#toreadonlyarray). * * @example * import { toEntries } from 'fp-ts/ReadonlyRecord' * * assert.deepStrictEqual(toEntries({ b: 2, a: 1 }), [['a', 1], ['b', 2]]) * * @category conversions * @since 2.12.0 */ export const toEntries = toReadonlyArray /** * Converts a `ReadonlyArray` of `[key, value]` tuples into a `ReadonlyRecord`. * * @example * import { fromEntries } from 'fp-ts/ReadonlyRecord' * * assert.deepStrictEqual(fromEntries([['a', 1], ['b', 2], ['a', 3]]), { b: 2, a: 3 }) * * @since 2.12.0 * @category conversions */ export const fromEntries = (fa: ReadonlyArray): ReadonlyRecord => { const out: Record = {} for (const a of fa) { out[a[0]] = a[1] } return out } /** * Test if every value in a `ReadonlyRecord` satisfies the predicate. * * @example * import { every } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: 2 }), true); * assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: -1 }), false); * * @since 2.5.0 */ export function every( refinement: Refinement ): Refinement, ReadonlyRecord> export function every(predicate: Predicate): Predicate> export function every(predicate: Predicate): Predicate> { return (r) => { for (const k in r) { if (!predicate(r[k])) { return false } } return true } } /** * Test if at least one value in a `ReadonlyRecord` satisfies the predicate. * * @example * import { some } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual(some((n: number) => n >= 0)({ a: 1, b: -2 }), true); * assert.deepStrictEqual(some((n: number) => n >= 0)({ a: -1, b: -2 }), false); * * @since 2.5.0 */ export function some(predicate: (a: A) => boolean): (r: ReadonlyRecord) => boolean { return (r) => { for (const k in r) { if (predicate(r[k])) { return true } } return false } } // TODO: remove non-curried overloading in v3 /** * Given an `Eq` checks if a `ReadonlyRecord` contains an entry with * value equal to a provided value. * * @example * import { elem } from "fp-ts/ReadonlyRecord" * import { number } from "fp-ts" * * assert.deepStrictEqual(elem(number.Eq)(123, { foo: 123, bar: 234 }), true); * assert.deepStrictEqual(elem(number.Eq)(-7, { foo: 123, bar: 234 }), false); * * @since 2.5.0 */ export function elem(E: Eq): { (a: A): (fa: ReadonlyRecord) => boolean (a: A, fa: ReadonlyRecord): boolean } export function elem( E: Eq ): (a: A, fa?: ReadonlyRecord) => boolean | ((fa: ReadonlyRecord) => boolean) { return (a, fa?) => { if (fa === undefined) { const elemE = elem(E) return (fa) => elemE(a, fa) } for (const k in fa) { if (E.equals(fa[k], a)) { return true } } return false } } /** * Union of two `ReadonlyRecord`s. * Takes two `ReadonlyRecord`s and produces a `ReadonlyRecord` combining all the * entries of the two inputs. * It uses the `concat` function of the provided `Magma` to * combine the elements with the same key. * * @example * import { union } from "fp-ts/ReadonlyRecord"; * import { Magma } from "fp-ts/Magma"; * * const m1: Magma = { concat: (x: number, y: number) => x + y }; * assert.deepStrictEqual(union(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4, b: 2, c: 3 }); * const m2: Magma = { concat: (x: number) => x }; * assert.deepStrictEqual(union(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 }); * * @since 2.11.0 */ export const union = (M: Magma) => (second: ReadonlyRecord) => (first: ReadonlyRecord): ReadonlyRecord => { if (isEmpty(first)) { return second } if (isEmpty(second)) { return first } const out: Record = {} for (const k in first) { if (has(k, second)) { out[k] = M.concat(first[k], second[k]) } else { out[k] = first[k] } } for (const k in second) { if (!has(k, out)) { out[k] = second[k] } } return out } /** * Intersection of two `ReadonlyRecord`s. * Takes two `ReadonlyRecord`s and produces a `ReadonlyRecord` combining only the * entries of the two inputswith the same key. * It uses the `concat` function of the provided `Magma` to * combine the elements. * * @example * import { intersection } from "fp-ts/ReadonlyRecord"; * import { Magma } from "fp-ts/Magma"; * * const m1: Magma = { concat: (x: number, y: number) => x + y }; * assert.deepStrictEqual(intersection(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4}); * const m2: Magma = { concat: (x: number) => x }; * assert.deepStrictEqual(intersection(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1}); * * @since 2.11.0 */ export const intersection = (M: Magma) => (second: ReadonlyRecord) => (first: ReadonlyRecord): ReadonlyRecord => { if (isEmpty(first) || isEmpty(second)) { return empty } const out: Record = {} for (const k in first) { if (has(k, second)) { out[k] = M.concat(first[k], second[k]) } } return out } /** * Difference between two `ReadonlyRecord`s. * Takes two `ReadonlyRecord`s and produces a `ReadonlyRecord` composed by the * entries of the two inputs, removing the entries with the same * key in both inputs. * * @example * import { difference } from "fp-ts/ReadonlyRecord"; * * assert.deepStrictEqual(difference({ a: 1 })({ a: 1, b: 2 }), { b: 2 }); * assert.deepStrictEqual(difference({ a: 3 })({ a: 1, b: 2 }), { b: 2 }); * assert.deepStrictEqual(difference({ a: 3, c: 3 })({ a: 1, b: 2 }), { b: 2, c: 3 }); * * @since 2.11.0 */ export const difference = (second: ReadonlyRecord) => (first: ReadonlyRecord): ReadonlyRecord => { if (isEmpty(first)) { return second } if (isEmpty(second)) { return first } const out: Record = {} for (const k in first) { if (!has(k, second)) { out[k] = first[k] } } for (const k in second) { if (!has(k, first)) { out[k] = second[k] } } return out } /** @internal */ export const _map: Functor1['map'] = (fa, f) => pipe(fa, map(f)) /** @internal */ /* istanbul ignore next */ export const _mapWithIndex: FunctorWithIndex1['mapWithIndex'] = (fa, f) => pipe(fa, mapWithIndex(f)) /** @internal */ /* istanbul ignore next */ export const _reduce: (O: Ord) => Foldable1['reduce'] = (O: Ord) => { const reduceO = reduce(O) return (fa, b, f) => pipe(fa, reduceO(b, f)) } /** @internal */ export const _foldMap: (O: Ord) => Foldable1['foldMap'] = (O) => (M) => { const foldMapM = foldMap(O)(M) return (fa, f) => pipe(fa, foldMapM(f)) } /** @internal */ /* istanbul ignore next */ export const _reduceRight: (O: Ord) => Foldable1['reduceRight'] = (O) => { const reduceRightO = reduceRight(O) return (fa, b, f) => pipe(fa, reduceRightO(b, f)) } /** @internal */ /* istanbul ignore next */ export const _filter = (fa: ReadonlyRecord, predicate: Predicate): ReadonlyRecord => pipe(fa, filter(predicate)) /** @internal */ /* istanbul ignore next */ export const _filterMap: Filterable1['filterMap'] = (fa, f) => pipe(fa, filterMap(f)) /** @internal */ /* istanbul ignore next */ export const _partition = ( fa: ReadonlyRecord, predicate: Predicate ): Separated, ReadonlyRecord> => pipe(fa, partition(predicate)) /** @internal */ /* istanbul ignore next */ export const _partitionMap: Filterable1['partitionMap'] = (fa, f) => pipe(fa, partitionMap(f)) /** @internal */ /* istanbul ignore next */ export const _reduceWithIndex: (O: Ord) => FoldableWithIndex1['reduceWithIndex'] = (O) => { const reduceWithIndexO = reduceWithIndex(O) return (fa, b, f) => pipe(fa, reduceWithIndexO(b, f)) } /** @internal */ export const _foldMapWithIndex: (O: Ord) => FoldableWithIndex1['foldMapWithIndex'] = (O) => { const foldMapWithIndexO = foldMapWithIndex(O) return (M) => { const foldMapWithIndexM = foldMapWithIndexO(M) return (fa, f) => pipe(fa, foldMapWithIndexM(f)) } } /** @internal */ /* istanbul ignore next */ export const _reduceRightWithIndex: (O: Ord) => FoldableWithIndex1['reduceRightWithIndex'] = ( O ) => { const reduceRightWithIndexO = reduceRightWithIndex(O) return (fa, b, f) => pipe(fa, reduceRightWithIndexO(b, f)) } /** @internal */ /* istanbul ignore next */ export const _partitionMapWithIndex = ( fa: ReadonlyRecord, f: (key: string, a: A) => Either ): Separated, ReadonlyRecord> => pipe(fa, partitionMapWithIndex(f)) /** @internal */ /* istanbul ignore next */ export const _partitionWithIndex = ( fa: ReadonlyRecord, predicateWithIndex: PredicateWithIndex ): Separated>, Readonly>> => pipe(fa, partitionWithIndex(predicateWithIndex)) /** @internal */ /* istanbul ignore next */ export const _filterMapWithIndex = ( fa: ReadonlyRecord, f: (key: string, a: A) => Option ): Readonly> => pipe(fa, filterMapWithIndex(f)) /** @internal */ /* istanbul ignore next */ export const _filterWithIndex = ( fa: ReadonlyRecord, predicateWithIndex: PredicateWithIndex ): Readonly> => pipe(fa, filterWithIndex(predicateWithIndex)) /** @internal */ export const _traverse = ( O: Ord ): (( F: Applicative ) => (ta: ReadonlyRecord, f: (a: A) => HKT) => HKT>) => { const traverseWithIndexO = _traverseWithIndex(O) return (F) => { const traverseWithIndexOF = traverseWithIndexO(F) return (ta, f) => traverseWithIndexOF(ta, flow(SK, f)) } } /** @internal */ export const _sequence = ( O: Ord ): ((F: Applicative) => (ta: ReadonlyRecord>) => HKT>) => { const traverseO = _traverse(O) return (F) => { const traverseOF = traverseO(F) return (ta) => traverseOF(ta, identity) } } const _traverseWithIndex = (O: Ord) => ( F: Applicative ): (( ta: ReadonlyRecord, f: (k: string, a: A) => HKT ) => HKT>) => { const keysO = keys_(O) return (ta: ReadonlyRecord, f: (k: string, a: A) => HKT) => { const ks = keysO(ta) if (ks.length === 0) { return F.of(empty) } let fr: HKT> = F.of({}) for (const key of ks) { fr = F.ap( F.map(fr, (r) => (b: B) => Object.assign({}, r, { [key]: b })), f(key, ta[key]) ) } return fr } } /** * Given a `Predicate`, it produces a new `ReadonlyRecord` keeping only the entries with a * value that satisfies the provided predicate. * * @example * import { filter } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual(filter((s: string) => s.length < 4)({ a: "foo", b: "bar", c: "verylong" }), { * a: "foo", * b: "bar", * }); * * @category filtering * @since 2.5.0 */ export const filter: { (refinement: Refinement): (fa: ReadonlyRecord) => ReadonlyRecord (predicate: Predicate): (fb: ReadonlyRecord) => ReadonlyRecord (predicate: Predicate): (fa: ReadonlyRecord) => ReadonlyRecord } = (predicate: Predicate): ((fa: ReadonlyRecord) => ReadonlyRecord) => filterWithIndex((_, a) => predicate(a)) /** * Maps a `ReadonlyRecord` with an iterating function that returns an `Option` * and it keeps only the `Some` values discarding the `None`s. * * @example * import { filterMap } from "fp-ts/ReadonlyRecord" * import { option } from "fp-ts" * * const f = (s: string) => s.length < 4 ? option.some(`${s} is short`): option.none * assert.deepStrictEqual(filterMap(f)({ a: "foo", b: "bar", c: "verylong" }), { * a: "foo is short", * b: "bar is short", * }); * * @category filtering * @since 2.5.0 */ export const filterMap: ( f: (a: A) => Option ) => (fa: ReadonlyRecord) => ReadonlyRecord = (f) => filterMapWithIndex((_, a) => f(a)) /** * Partition a `ReadonlyRecord` into two parts according to a `Predicate`. * * @example * import { partition } from "fp-ts/ReadonlyRecord" * * assert.deepStrictEqual(partition((s: string) => s.length < 4)({ a: "foo", b: "bar", c: "verylong" }), { * left:{ * c: "verylong" * }, * right: { * a: "foo", * b: "bar", * }, * }); * * @category filtering * @since 2.5.0 */ export const partition: { (refinement: Refinement): ( fa: ReadonlyRecord ) => Separated, ReadonlyRecord> (predicate: Predicate): ( fb: ReadonlyRecord ) => Separated, ReadonlyRecord> (predicate: Predicate): ( fa: ReadonlyRecord ) => Separated, ReadonlyRecord> } = ( predicate: Predicate ): ((fa: ReadonlyRecord) => Separated, ReadonlyRecord>) => partitionWithIndex((_, a) => predicate(a)) /** * Maps a `ReadonlyRecord` with a function returning an `Either` and * partitions the resulting `ReadonlyRecord` into `Left`s and `Right`s. * * @example * import { partitionMap } from "fp-ts/ReadonlyRecord" * import { either } from "fp-ts" * * const f = (s: string) => (s.length < 4 ? either.right(`${s} is short`) : either.left(`${s} is not short`)); * assert.deepStrictEqual(partitionMap(f)({ a: "foo", b: "bar", c: "verylong" }), { * left: { * c: "verylong is not short", * }, * right: { * a: "foo is short", * b: "bar is short", * }, * }); * * @category filtering * @since 2.5.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: ReadonlyRecord) => Separated, ReadonlyRecord> = (f) => partitionMapWithIndex((_, a) => f(a)) /** * Reduces a `ReadonlyRecord` passing each value to the iterating function. * Entries are processed in order, sorted by key according to * the given `Ord`. * * @example * import { reduce } from "fp-ts/ReadonlyRecord"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduce(Ord)([] as string[], (b, a) => [...b, `-${a}-`])(x), [ * "-foo-", * "-false-", * "-3-", * ]); * * @category folding * @since 2.5.0 */ export function reduce(O: Ord): (b: B, f: (b: B, a: A) => B) => (fa: ReadonlyRecord) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduce(b: B, f: (b: B, a: A) => B): (fa: ReadonlyRecord) => B export function reduce( ...args: [Ord] | [B, (b: B, a: A) => B] ): ((b: B, f: (b: B, a: A) => B) => (fa: ReadonlyRecord) => B) | ((fa: ReadonlyRecord) => B) { if (args.length === 1) { const reduceWithIndexO = reduceWithIndex(args[0]) return (b: B, f: (b: B, a: A) => B) => reduceWithIndexO(b, (_, b, a) => f(b, a)) } return reduce(S.Ord)(...args) } /** * Map and fold a `ReadonlyRecord`. * Map the `ReadonlyRecord` passing each value to the iterating function. * Then fold the results using the provided `Monoid`. * * @example * import { foldMap } from "fp-ts/ReadonlyRecord"; * import { Ord } from "fp-ts/string"; * import { Monoid } from "fp-ts/Monoid"; * * const m: Monoid = { empty: "", concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) }; * const f = (a: number) => `-${a}-`; * const x = { c: 3, a: 1, b: 2 }; * assert.deepStrictEqual(foldMap(Ord)(m)(f)(x), "-1- -> -2- -> -3-"); * * @category folding * @since 2.5.0 */ export function foldMap( O: Ord ): (M: Monoid) => (f: (a: A) => M) => (fa: ReadonlyRecord) => M /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function foldMap(M: Monoid): (f: (a: A) => M) => (fa: ReadonlyRecord) => M export function foldMap( O: Ord | Monoid ): | ((M: Monoid) => (f: (a: A) => M) => (fa: ReadonlyRecord) => M) | ((f: (a: A) => M) => (fa: ReadonlyRecord) => M) { if ('compare' in O) { const foldMapWithIndexO = foldMapWithIndex(O) return (M: Monoid) => { const foldMapWithIndexM = foldMapWithIndexO(M) return (f: (a: A) => M): ((fa: ReadonlyRecord) => M) => foldMapWithIndexM((_, a) => f(a)) } } return foldMap(S.Ord)(O) } /** * Same as `reduce` but entries are processed _from the right_, * i.e. in reverse order, from the last to the first entry, according to * the given `Ord`. * * @example * import { reduceRight } from "fp-ts/ReadonlyRecord"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduceRight(Ord)([] as string[], (a, b) => [...b, `-${a}-`])(x), [ * "-3-", * "-false-", * "-foo-", * ]); * * @category folding * @since 2.5.0 */ export function reduceRight(O: Ord): (b: B, f: (a: A, b: B) => B) => (fa: ReadonlyRecord) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduceRight(b: B, f: (a: A, b: B) => B): (fa: ReadonlyRecord) => B export function reduceRight( ...args: [Ord] | [B, (a: A, b: B) => B] ): ((b: B, f: (a: A, b: B) => B) => (fa: ReadonlyRecord) => B) | ((fa: ReadonlyRecord) => B) { if (args.length === 1) { const reduceRightWithIndexO = reduceRightWithIndex(args[0]) return (b: B, f: (a: A, b: B) => B) => reduceRightWithIndexO(b, (_, b, a) => f(b, a)) } return reduceRight(S.Ord)(...args) } /** * Compact a `ReadonlyRecord` of `Option`s discarding the `None` values and * keeping the `Some` values. * * @example * import { compact } from 'fp-ts/ReadonlyRecord' * import { option } from 'fp-ts' * * assert.deepStrictEqual(compact({ a: option.some("foo"), b: option.none, c: option.some("bar") }), { * a: "foo", * c: "bar", * }); * * @category filtering * @since 2.5.0 */ export const compact = (r: ReadonlyRecord>): ReadonlyRecord => { const out: Record = {} for (const k in r) { if (_.has.call(r, k)) { const oa = r[k] if (_.isSome(oa)) { out[k] = oa.value } } } return out } /** * Separate a `ReadonlyRecord` of `Either`s into `Left`s and `Right`s. * * @example * import { separate } from 'fp-ts/ReadonlyRecord' * import { either } from 'fp-ts' * * assert.deepStrictEqual( * separate({ a: either.right("foo"), b: either.left("bar"), c: either.right("baz") }), * { * right: { * a: "foo", * c: "baz", * }, * left: { * b: "bar", * }, * } * ); * * @category filtering * @since 2.5.0 */ export const separate = ( r: ReadonlyRecord> ): Separated, ReadonlyRecord> => { const left: Record = {} const right: Record = {} for (const k in r) { if (_.has.call(r, k)) { const e = r[k] if (_.isLeft(e)) { left[k] = e.left } else { right[k] = e.right } } } return separated(left, right) } /** * @category type lambdas * @since 2.5.0 */ export const URI = 'ReadonlyRecord' /** * @category type lambdas * @since 2.5.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: ReadonlyRecord } } /** * Produces a `Show` for a `ReadonlyRecord`, given a `Show` for the base type * (a `Show` produces a human-readable representation of an instance). * `ReadonlyRecord` entries are sorted by key with the provided `Ord`. * * @example * import { getShow, ReadonlyRecord } from "fp-ts/ReadonlyRecord" * import { Show } from "fp-ts/Show" * import { Ord } from "fp-ts/string" * * const sNumber: Show = { show: (n: number) => `${n}` }; * const sRecord: Show> = getShow(Ord)(sNumber); * assert.deepStrictEqual(sRecord.show({ b: 2, a: 1 }), '{ "a": 1, "b": 2 }'); * * @category instances * @since 2.5.0 */ export function getShow(O: Ord): (S: Show) => Show> /** * Use the overload constrained by `Ord` instead. * * @category zone of death * @deprecated */ export function getShow(S: Show): Show> export function getShow( O: Ord | Show ): ((S: Show) => Show>) | Show> { if ('compare' in O) { return (S: Show) => ({ show: (r: ReadonlyRecord) => { const elements = collect(O)((k, a: A) => `${JSON.stringify(k)}: ${S.show(a)}`)(r).join(', ') return elements === '' ? '{}' : `{ ${elements} }` } }) } return getShow(S.Ord)(O) } /** * Given an `Eq` for the base type, it produces an `Eq` * for a `ReadonlyRecord` of that base type. * * @example * import { getEq, ReadonlyRecord } from "fp-ts/ReadonlyRecord"; * import { string } from "fp-ts"; * import { Eq } from "fp-ts/Eq"; * * const eq: Eq> = getEq(string.Eq); * assert.deepStrictEqual(eq.equals({ a: "foo" }, { b: "bar" }), false); * assert.deepStrictEqual(eq.equals({ a: "foo" }, { a: "foo" }), true); * * @category instances * @since 2.5.0 */ export function getEq(E: Eq): Eq> export function getEq(E: Eq): Eq> { const isSubrecordE = isSubrecord(E) return fromEquals((x, y) => isSubrecordE(x)(y) && isSubrecordE(y)(x)) } /** * Returns a `Monoid` instance for `ReadonlyRecord`s, given a `Semigroup` * instance for the base type. * The `Monoid` makes the union of two `ReadonlyRecord`s comining the * overlapping entries with the provided `Semigroup`. * * @example * import { SemigroupSum } from 'fp-ts/number' * import { getMonoid } from 'fp-ts/ReadonlyRecord' * * const M = getMonoid(SemigroupSum); * assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579 , bar: 234, baz: 567 }); * * @category instances * @since 2.5.0 */ export function getMonoid(S: Semigroup): Monoid> export function getMonoid(S: Semigroup): Monoid> { return { concat: (first, second) => { if (isEmpty(first)) { return second } if (isEmpty(second)) { return first } const r: Record = Object.assign({}, first) for (const k in second) { if (_.has.call(second, k)) { r[k] = _.has.call(first, k) ? S.concat(first[k], second[k]) : second[k] } } return r }, empty } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Takes a value and a `ReadonlyRecord` of functions and returns a * `ReadonlyRecord` by applying each function to the input value. * * @example * import { flap } from "fp-ts/ReadonlyRecord" * * const fab = { x: (n: number) => `${n} times 2`, y: (n: number) => `${n * 2}` }; * assert.deepStrictEqual(flap(3)(fab), { * x: "3 times 2", * y: "6", * }); * * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.7.0 */ export const FunctorWithIndex: FunctorWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex } /** * Produces a `Foldable` instance for a `ReadonlyRecord`, using the * provided `Ord` to sort the `ReadonlyRecord`'s entries by key. * * @category folding * @since 2.11.0 */ export const getFoldable = (O: Ord): Foldable1 => ({ URI, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O) }) /** * Produces a `FoldableWithIndex1` instance for a `ReadonlyRecord`, using the * provided `Ord` to sort the `ReadonlyRecord`'s entries by key. * * @category folding * @since 2.11.0 */ export const getFoldableWithIndex = (O: Ord): FoldableWithIndex1 => ({ URI, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), reduceWithIndex: _reduceWithIndex(O), foldMapWithIndex: _foldMapWithIndex(O), reduceRightWithIndex: _reduceRightWithIndex(O) }) /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category instances * @since 2.7.0 */ export const FilterableWithIndex: FilterableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex } /** * Produces a `Traversable` instance for a `ReadonlyRecord`, using the * provided `Ord` to sort the `ReadonlyRecord`'s entries by key. * * @category traversing * @since 2.11.0 */ export const getTraversable = (O: Ord): Traversable1 => ({ URI, map: _map, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), traverse: _traverse(O), sequence: _sequence(O) }) /** * Produces a `TraversableWithIndex` instance for a `ReadonlyRecord`, using the * provided `Ord` to sort the `ReadonlyRecord`'s entries by key. * * @category traversing * @since 2.11.0 */ export const getTraversableWithIndex = (O: Ord): TraversableWithIndex1 => ({ URI, map: _map, mapWithIndex: _mapWithIndex, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), reduceWithIndex: _reduceWithIndex(O), foldMapWithIndex: _foldMapWithIndex(O), reduceRightWithIndex: _reduceRightWithIndex(O), traverse: _traverse(O), sequence: _sequence(O), traverseWithIndex: _traverseWithIndex(O) }) /** * @category filtering * @since 2.11.0 */ export const getWitherable = (O: Ord): Witherable1 => { const T = getTraversable(O) return { URI, map: _map, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), traverse: T.traverse, sequence: T.sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, wither: witherDefault(T, Compactable), wilt: wiltDefault(T, Compactable) } } /** * Given a `Semigroup` in the base type, it produces a `Semigroup` * in the `ReadonlyRecord` of the base type. * The resulting `Semigroup` concatenates two `ReadonlyRecord`s by * `union`. * * @example * import { getUnionSemigroup, ReadonlyRecord } from "fp-ts/ReadonlyRecord" * import { Semigroup } from "fp-ts/Semigroup" * * const sNumber: Semigroup = { concat: (x, y) => x - y }; * const sReadonlyRecord: Semigroup> = getUnionSemigroup(sNumber); * assert.deepStrictEqual(sReadonlyRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { a: 1, b: -1, c: 4 }); * * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (S: Semigroup): Semigroup> => { const unionS = union(S) return { concat: (first, second) => unionS(second)(first) } } /** * Same as `getMonoid`. * Returns a `Monoid` instance for `ReadonlyRecord`s given a `Semigroup` * instance for the base type. * The `Monoid` makes the union of two `ReadonlyRecord`s combining the * entries that have the same key with the provided `Semigroup`. * * @example * import { SemigroupSum } from 'fp-ts/number' * import { getUnionMonoid } from 'fp-ts/ReadonlyRecord' * * const M = getUnionMonoid(SemigroupSum); * assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579 , bar: 234, baz: 567 }); * * @category instances * @since 2.11.0 */ export const getUnionMonoid = (S: Semigroup): Monoid> => ({ concat: getUnionSemigroup(S).concat, empty }) /** * Given a `Semigroup` in the base type, it produces a `Semigroup` * in the `ReadonlyRecord` of the base type. * The resulting `Semigroup` concatenates two `ReadonlyRecord`s by * `intersection`. * * @example * import { getIntersectionSemigroup, ReadonlyRecord } from "fp-ts/ReadonlyRecord" * import { Semigroup } from "fp-ts/Semigroup" * * const sNumber: Semigroup = { concat: (x, y) => x - y }; * const sReadonlyRecord: Semigroup> = getIntersectionSemigroup(sNumber); * assert.deepStrictEqual(sReadonlyRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { b: -1 }); * * @category instances * @since 2.11.0 */ export const getIntersectionSemigroup = (S: Semigroup): Semigroup> => { const intersectionS = intersection(S) return { concat: (first, second) => intersectionS(second)(first) } } /** * Produces a `Magma` with a `concat` function that combines * two `ReadonlyRecord`s by making the `difference`. * * @example * import { getDifferenceMagma, difference, ReadonlyRecord } from "fp-ts/ReadonlyRecord" * import { Magma } from "fp-ts/Magma" * * const r1 = { a: 3, c: 3 }; * const r2 = { a: 1, b: 2 }; * const m: Magma> = getDifferenceMagma(); * assert.deepStrictEqual(m.concat(r1, r2), difference(r2)(r1)); * assert.deepStrictEqual(m.concat(r1, r2), { c: 3, b: 2 }); * * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (): Magma> => ({ concat: (first, second) => difference(second)(first) }) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `getFoldable` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const Foldable: Foldable1 = { URI, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord) } /** * Use `getFoldableWithIndex` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const FoldableWithIndex: FoldableWithIndex1 = { URI, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), reduceWithIndex: /*#__PURE__*/ _reduceWithIndex(S.Ord), foldMapWithIndex: /*#__PURE__*/ _foldMapWithIndex(S.Ord), reduceRightWithIndex: /*#__PURE__*/ _reduceRightWithIndex(S.Ord) } /** * Use `getTraversable` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const Traversable: Traversable1 = { URI, map: _map, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence } /** * Use `getTraversableWithIndex` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const TraversableWithIndex: TraversableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), reduceWithIndex: /*#__PURE__*/ _reduceWithIndex(S.Ord), foldMapWithIndex: /*#__PURE__*/ _foldMapWithIndex(S.Ord), reduceRightWithIndex: /*#__PURE__*/ _reduceRightWithIndex(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence, traverseWithIndex: /*#__PURE__*/ _traverseWithIndex(S.Ord) } const _wither = /*#__PURE__*/ witherDefault(Traversable, Compactable) const _wilt = /*#__PURE__*/ wiltDefault(Traversable, Compactable) /** * Use `getWitherable` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const Witherable: Witherable1 = { URI, map: _map, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, wither: _wither, wilt: _wilt } /** * Use [`upsertAt`](#upsertat) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const insertAt: (k: string, a: A) => (r: ReadonlyRecord) => ReadonlyRecord = upsertAt /** * Use [`has`](#has) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export function hasOwnProperty(k: string, r: ReadonlyRecord): k is K export function hasOwnProperty(this: any, k: string, r?: ReadonlyRecord): k is K { return _.has.call(r === undefined ? this : r, k) } /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RR.Functor` instead of `RR.readonlyRecord` * (where `RR` is from `import RR from 'fp-ts/ReadonlyRecord'`) * * @category zone of death * @since 2.5.0 * @deprecated */ export const readonlyRecord: FunctorWithIndex1 & FoldableWithIndex1 & FilterableWithIndex1 & TraversableWithIndex1 & Witherable1 = { URI, map: _map, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, mapWithIndex: _mapWithIndex, reduceWithIndex: /*#__PURE__*/ _reduceWithIndex(S.Ord), foldMapWithIndex: /*#__PURE__*/ _foldMapWithIndex(S.Ord), reduceRightWithIndex: /*#__PURE__*/ _reduceRightWithIndex(S.Ord), filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, traverseWithIndex: /*#__PURE__*/ _traverseWithIndex(S.Ord), wither: _wither, wilt: _wilt } ================================================ FILE: src/ReadonlySet.ts ================================================ /** * @since 2.5.0 */ import { Either } from './Either' import { Eq, fromEquals } from './Eq' import { identity } from './function' import { Magma } from './Magma' import { Monoid } from './Monoid' import { Option } from './Option' import { Ord } from './Ord' import { not, Predicate } from './Predicate' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' /** * @category conversions * @since 2.5.0 */ export const fromSet = (s: Set): ReadonlySet => new Set(s) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Create a set with one element * * @category constructors * @since 2.5.0 */ export const singleton = (a: A): ReadonlySet => new Set([a]) /** * Create a `ReadonlySet` from a `ReadonlyArray` * * @category conversions * @since 2.10.0 */ export const fromReadonlyArray = (E: Eq) => (as: ReadonlyArray): ReadonlySet => { const len = as.length const out = new Set() const has = elem(E) for (let i = 0; i < len; i++) { const a = as[i] if (!has(a, out)) { out.add(a) } } return out } /** * @category conversions * @since 2.5.0 */ export function toSet(s: ReadonlySet): Set { return new Set(s) } type Next = IteratorResult /** * Projects a Set through a function * * @since 2.5.0 */ export function map(E: Eq): (f: (x: A) => B) => (set: ReadonlySet) => ReadonlySet { const elemE = elem(E) return (f) => (set) => { const r = new Set() set.forEach((e) => { const v = f(e) if (!elemE(v, r)) { r.add(v) } }) return r } } /** * @since 2.5.0 */ export function chain(E: Eq): (f: (x: A) => ReadonlySet) => (set: ReadonlySet) => ReadonlySet { const elemE = elem(E) return (f) => (set) => { const r = new Set() set.forEach((e) => { f(e).forEach((e) => { if (!elemE(e, r)) { r.add(e) } }) }) return r } } /** * @since 2.5.0 */ export function filter(refinement: Refinement): (set: ReadonlySet) => ReadonlySet export function filter(predicate: Predicate): (set: ReadonlySet) => ReadonlySet export function filter(predicate: Predicate): (set: ReadonlySet) => ReadonlySet export function filter(predicate: Predicate): (set: ReadonlySet) => ReadonlySet { return (set: ReadonlySet) => { const values = set.values() let e: Next const r = new Set() while (!(e = values.next()).done) { const a = e.value if (predicate(a)) { r.add(a) } } return r } } /** * @since 2.5.0 */ export function partition( refinement: Refinement ): (set: ReadonlySet) => Separated, ReadonlySet> export function partition( predicate: Predicate ): (set: ReadonlySet) => Separated, ReadonlySet> export function partition( predicate: Predicate ): (set: ReadonlySet) => Separated, ReadonlySet> export function partition( predicate: Predicate ): (set: ReadonlySet) => Separated, ReadonlySet> { return (set: ReadonlySet) => { const values = set.values() let e: Next const right = new Set() const left = new Set() while (!(e = values.next()).done) { const a = e.value if (predicate(a)) { right.add(a) } else { left.add(a) } } return separated(left, right) } } // TODO: remove non-curried overloading in v3 /** * Form the union of two sets * * @since 2.5.0 */ export function union(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => ReadonlySet (me: ReadonlySet, that: ReadonlySet): ReadonlySet } export function union( E: Eq ): (me: ReadonlySet, that?: ReadonlySet) => ReadonlySet | ((me: ReadonlySet) => ReadonlySet) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const unionE = union(E) return (that) => unionE(me, that) } if (isEmpty(me)) { return that } if (isEmpty(that)) { return me } const r = new Set(me) that.forEach((e) => { if (!elemE(e, r)) { r.add(e) } }) return r } } // TODO: remove non-curried overloading in v3 /** * The set of elements which are in both the first and second set * * @since 2.5.0 */ export function intersection(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => ReadonlySet (me: ReadonlySet, that: ReadonlySet): ReadonlySet } export function intersection( E: Eq ): (me: ReadonlySet, that?: ReadonlySet) => ReadonlySet | ((that: ReadonlySet) => ReadonlySet) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const intersectionE = intersection(E) return (that) => intersectionE(that, me) } if (isEmpty(me) || isEmpty(that)) { return empty } const r = new Set() me.forEach((e) => { if (elemE(e, that)) { r.add(e) } }) return r } } /** * @since 2.5.0 */ export function partitionMap( EB: Eq, EC: Eq ): (f: (a: A) => Either) => (set: ReadonlySet) => Separated, ReadonlySet> { return (f: (a: A) => Either) => (set: ReadonlySet) => { const values = set.values() let e: Next const left = new Set() const right = new Set() const hasB = elem(EB) const hasC = elem(EC) while (!(e = values.next()).done) { const v = f(e.value) switch (v._tag) { case 'Left': if (!hasB(v.left, left)) { left.add(v.left) } break case 'Right': if (!hasC(v.right, right)) { right.add(v.right) } break } } return separated(left, right) } } // TODO: remove non-curried overloading in v3 /** * Form the set difference (`x` - `y`) * * @example * import { difference } from 'fp-ts/ReadonlySet' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(new Set([1, 2]), difference(N.Eq)(new Set([1, 3]))), new Set([2])) * * @since 2.5.0 */ export function difference(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => ReadonlySet (me: ReadonlySet, that: ReadonlySet): ReadonlySet } export function difference( E: Eq ): (me: ReadonlySet, that?: ReadonlySet) => ReadonlySet | ((me: ReadonlySet) => ReadonlySet) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const differenceE = difference(E) return (that) => differenceE(that, me) } return filter((a: A) => !elemE(a, that))(me) } } /** * @since 2.5.0 */ export function reduce(O: Ord): (b: B, f: (b: B, a: A) => B) => (fa: ReadonlySet) => B { const toReadonlyArrayO = toReadonlyArray(O) return (b, f) => (fa) => toReadonlyArrayO(fa).reduce(f, b) } /** * @since 2.5.0 */ export function foldMap(O: Ord, M: Monoid): (f: (a: A) => M) => (fa: ReadonlySet) => M { const toReadonlyArrayO = toReadonlyArray(O) return (f) => (fa) => toReadonlyArrayO(fa).reduce((b, a) => M.concat(b, f(a)), M.empty) } /** * @category folding * @since 2.11.0 */ export const reduceRight = (O: Ord): ((b: B, f: (a: A, b: B) => B) => (fa: ReadonlySet) => B) => { const toReadonlyArrayO = toReadonlyArray(O) return (b, f) => (fa) => toReadonlyArrayO(fa).reduceRight((b, a) => f(a, b), b) } /** * Insert a value into a set * * @since 2.5.0 */ export function insert(E: Eq): (a: A) => (set: ReadonlySet) => ReadonlySet { const elemE = elem(E) return (a) => (set) => { if (!elemE(a)(set)) { const r = new Set(set) r.add(a) return r } else { return set } } } /** * Delete a value from a set * * @since 2.5.0 */ export const remove = (E: Eq) => (a: A) => (set: ReadonlySet): ReadonlySet => filter((ax: A) => !E.equals(a, ax))(set) /** * Checks an element is a member of a set; * If yes, removes the value from the set * If no, inserts the value to the set * * @since 2.10.0 */ export const toggle = (E: Eq): ((a: A) => (set: ReadonlySet) => ReadonlySet) => { const elemE = elem(E) const removeE = remove(E) const insertE = insert(E) return (a) => (set) => (elemE(a, set) ? removeE : insertE)(a)(set) } /** * @since 2.5.0 */ export const compact = (E: Eq): ((fa: ReadonlySet>) => ReadonlySet) => filterMap(E)(identity) /** * @since 2.5.0 */ export function separate( EE: Eq, EA: Eq ): (fa: ReadonlySet>) => Separated, ReadonlySet> { return (fa) => { const elemEE = elem(EE) const elemEA = elem(EA) const left: Set = new Set() const right: Set = new Set() fa.forEach((e) => { switch (e._tag) { case 'Left': if (!elemEE(e.left, left)) { left.add(e.left) } break case 'Right': if (!elemEA(e.right, right)) { right.add(e.right) } break } }) return separated(left, right) } } /** * @since 2.5.0 */ export function filterMap(E: Eq): (f: (a: A) => Option) => (fa: ReadonlySet) => ReadonlySet { const elemE = elem(E) return (f) => (fa) => { const r: Set = new Set() fa.forEach((a) => { const ob = f(a) if (ob._tag === 'Some' && !elemE(ob.value, r)) { r.add(ob.value) } }) return r } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.5.0 */ export const empty: ReadonlySet = new Set() /** * Test whether a `ReadonlySet` is empty. * * @since 2.10.0 */ export const isEmpty = (set: ReadonlySet): boolean => set.size === 0 /** * Calculate the number of elements in a `ReadonlySet`. * * @since 2.10.0 */ export const size = (set: ReadonlySet): number => set.size /** * @since 2.5.0 */ export const some = (predicate: Predicate) => (set: ReadonlySet): boolean => { const values = set.values() let e: Next let found = false while (!found && !(e = values.next()).done) { found = predicate(e.value) } return found } /** * @since 2.5.0 */ export function every(refinement: Refinement): Refinement, ReadonlySet> export function every(predicate: Predicate): Predicate> export function every(predicate: Predicate): Predicate> { return not(some(not(predicate))) } // TODO: remove non-curried overloading in v3 /** * `true` if and only if every element in the first set is an element of the second set * * @since 2.5.0 */ export function isSubset(E: Eq): { (that: ReadonlySet): (me: ReadonlySet) => boolean (me: ReadonlySet, that: ReadonlySet): boolean } export function isSubset( E: Eq ): (me: ReadonlySet, that?: ReadonlySet) => boolean | ((me: ReadonlySet) => boolean) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const isSubsetE = isSubset(E) return (that) => isSubsetE(that, me) } return every((a: A) => elemE(a, that))(me) } } // TODO: remove non-curried overloading in v3 /** * Test if a value is a member of a set * * @since 2.5.0 */ export function elem(E: Eq): { (a: A): (set: ReadonlySet) => boolean (a: A, set: ReadonlySet): boolean } export function elem(E: Eq): (a: A, set?: ReadonlySet) => boolean | ((set: ReadonlySet) => boolean) { return (a, set?) => { if (set === undefined) { const elemE = elem(E) return (set) => elemE(a, set) } const values = set.values() let e: Next let found = false while (!found && !(e = values.next()).done) { found = E.equals(a, e.value) } return found } } /** * Get a sorted `ReadonlyArray` of the values contained in a `ReadonlySet`. * * @category conversions * @since 2.5.0 */ export const toReadonlyArray = (O: Ord) => (set: ReadonlySet): ReadonlyArray => { const out: Array = [] set.forEach((e) => out.push(e)) return out.sort(O.compare) } /** * @category type lambdas * @since 2.11.0 */ export const URI = 'ReadonlySet' /** * @category type lambdas * @since 2.11.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: ReadonlySet } } /** * @category instances * @since 2.5.0 */ export function getShow(S: Show): Show> { return { show: (s) => { const entries: Array = [] s.forEach((a) => { entries.push(S.show(a)) }) return `new Set([${entries.sort().join(', ')}])` } } } /** * @category instances * @since 2.5.0 */ export function getEq(E: Eq): Eq> { const subsetE = isSubset(E) return fromEquals((x, y) => subsetE(x, y) && subsetE(y, x)) } /** * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq): Semigroup> => ({ concat: union(E) }) /** * @category instances * @since 2.5.0 */ export const getUnionMonoid = (E: Eq): Monoid> => ({ concat: getUnionSemigroup(E).concat, empty }) /** * @category instances * @since 2.5.0 */ export const getIntersectionSemigroup = (E: Eq): Semigroup> => ({ concat: intersection(E) }) /** * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (E: Eq): Magma> => ({ concat: difference(E) }) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`fromReadonlyArray`](#fromreadonlyarray) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const fromArray: (E: Eq) => (as: ReadonlyArray) => ReadonlySet = fromReadonlyArray ================================================ FILE: src/ReadonlyTuple.ts ================================================ /** * @since 2.5.0 */ import { Applicative, Applicative2C } from './Applicative' import { Apply2C } from './Apply' import { Bifunctor2 } from './Bifunctor' import { Chain2C } from './Chain' import { ChainRec2C } from './ChainRec' import { Comonad2 } from './Comonad' import { Either } from './Either' import { Extend2 } from './Extend' import { Foldable2 } from './Foldable' import { identity, pipe } from './function' import { flap as flap_, Functor2 } from './Functor' import { HKT } from './HKT' import { Monad2C } from './Monad' import { Monoid } from './Monoid' import { Semigroup } from './Semigroup' import { Semigroupoid2 } from './Semigroupoid' import { PipeableTraverse2, Traversable2 } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.5.0 */ export function fst(ea: readonly [A, E]): A { return ea[0] } /** * @since 2.5.0 */ export function snd(ea: readonly [A, E]): E { return ea[1] } /** * @since 2.5.0 */ export const swap = (ea: readonly [A, E]): readonly [E, A] => [snd(ea), fst(ea)] /** * @category instances * @since 2.5.0 */ export function getApply(S: Semigroup): Apply2C { return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => [fst(fab)(fst(fa)), S.concat(snd(fab), snd(fa))] } } const of = (M: Monoid) => (a: A): readonly [A, M] => { return [a, M.empty] } /** * @category instances * @since 2.5.0 */ export function getApplicative(M: Monoid): Applicative2C { const A = getApply(M) return { URI, _E: undefined as any, map: _map, ap: A.ap, of: of(M) } } /** * @category instances * @since 2.5.0 */ export function getChain(S: Semigroup): Chain2C { const A = getApply(S) return { URI, _E: undefined as any, map: _map, ap: A.ap, chain: (ma, f) => { const [b, s] = f(fst(ma)) return [b, S.concat(snd(ma), s)] } } } /** * @category instances * @since 2.5.0 */ export function getMonad(M: Monoid): Monad2C { const C = getChain(M) return { URI, _E: undefined as any, map: _map, ap: C.ap, chain: C.chain, of: of(M) } } /** * @category instances * @since 2.5.0 */ export function getChainRec(M: Monoid): ChainRec2C { const chainRec = (a: A, f: (a: A) => readonly [Either, M]): readonly [B, M] => { let result: readonly [Either, M] = f(a) let acc: M = M.empty let s: Either = fst(result) while (s._tag === 'Left') { acc = M.concat(acc, snd(result)) result = f(s.left) s = fst(result) } return [s.right, M.concat(acc, snd(result))] } const C = getChain(M) return { URI, _E: undefined as any, map: _map, ap: C.ap, chain: C.chain, chainRec } } /* istanbul ignore next */ const _compose: Semigroupoid2['compose'] = (bc, ab) => pipe(bc, compose(ab)) /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, mapFst(f)) /* istanbul ignore next */ const _bimap: Bifunctor2['bimap'] = (fa, f, g) => pipe(fa, bimap(f, g)) /* istanbul ignore next */ const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapSnd(f)) /* istanbul ignore next */ const _extend: Extend2['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _reduce: Foldable2['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable2['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable2['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _traverse = ( F: Applicative ): ((ta: readonly [A, S], f: (a: A) => HKT) => HKT) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.5.0 */ export const bimap: ( mapSnd: (e: E) => G, mapFst: (a: A) => B ) => (fa: readonly [A, E]) => readonly [B, G] = (f, g) => (fa) => [g(fst(fa)), f(snd(fa))] /** * Map a function over the first component of a `ReadonlyTuple`. * * This is the `map` operation of the `Functor` instance. * * @category mapping * @since 2.10.0 */ export const mapFst: (f: (a: A) => B) => (fa: readonly [A, E]) => readonly [B, E] = (f) => (fa) => [f(fst(fa)), snd(fa)] /** * Map a function over the second component of a `ReadonlyTuple`. * * This is the `mapLeft` operation of the `Bifunctor` instance. * * @category mapping * @since 2.10.0 */ export const mapSnd: (f: (e: E) => G) => (fa: readonly [A, E]) => readonly [A, G] = (f) => (fa) => [fst(fa), f(snd(fa))] /** * @since 2.5.0 */ export const compose: (ab: readonly [B, A]) => (bc: readonly [C, B]) => readonly [C, A] = (ab) => (bc) => [fst(bc), snd(ab)] /** * @since 2.5.0 */ export const extend: (f: (wa: readonly [A, E]) => B) => (wa: readonly [A, E]) => readonly [B, E] = (f) => (wa) => [f(wa), snd(wa)] /** * @category Extract * @since 2.6.2 */ export const extract: (wa: readonly [A, E]) => A = fst /** * @since 2.5.0 */ export const duplicate: (wa: readonly [A, E]) => readonly [readonly [A, E], E] = /*#__PURE__*/ extend(identity) /** * @category folding * @since 2.5.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: readonly [A, E]) => B = (b, f) => (fa) => f(b, fst(fa)) /** * @category folding * @since 2.5.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: readonly [A, E]) => M = () => { return (f) => (fa) => f(fst(fa)) } /** * @category folding * @since 2.5.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: readonly [A, E]) => B = (b, f) => (fa) => f(fst(fa), b) /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse2 = ( F: Applicative ): ((f: (a: A) => HKT) => (as: readonly [A, E]) => HKT) => { return (f) => (ta) => F.map(f(fst(ta)), (b) => [b, snd(ta)]) } /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable2['sequence'] = (F: Applicative) => (fas: readonly [HKT, E]): HKT => { return F.map(fst(fas), (a) => [a, snd(fas)]) } /** * @category type lambdas * @since 2.5.0 */ export const URI = 'ReadonlyTuple' /** * @category type lambdas * @since 2.5.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: readonly [A, E] } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * Alias of [`mapFst`](#mapfst). * * @category mapping * @since 2.5.0 */ export const map: (f: (a: A) => B) => (fa: readonly [A, E]) => readonly [B, E] = mapFst /** * Alias of [`mapSnd`](#mapsnd). * * @category error handling * @since 2.5.0 */ export const mapLeft: (f: (e: E) => G) => (fa: readonly [A, E]) => readonly [A, G] = mapSnd /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * @category instances * @since 2.7.0 */ export const Semigroupoid: Semigroupoid2 = { URI, compose: _compose } /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad2 = { URI, map: _map, extend: _extend, extract } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable2 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable2 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `RT.Functor` instead of `RT.readonlyTuple` * (where `RT` is from `import RT from 'fp-ts/ReadonlyTuple'`) * * @category zone of death * @since 2.5.0 * @deprecated */ export const readonlyTuple: Semigroupoid2 & Bifunctor2 & Comonad2 & Foldable2 & Traversable2 = { URI, compose: _compose, map: _map, bimap: _bimap, mapLeft: _mapLeft, extract, extend: _extend, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } ================================================ FILE: src/Record.ts ================================================ /** * The `Record` module enables dealing with Typescript's `Record` * type in a functional way, basically treating it as a `Functor` in `T`. * * @since 2.0.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C, Applicative4 } from './Applicative' import * as A from './Array' import { Compactable1 } from './Compactable' import { Either } from './Either' import { Eq } from './Eq' import { Filterable1 } from './Filterable' import { FilterableWithIndex1, PredicateWithIndex, RefinementWithIndex } from './FilterableWithIndex' import { Foldable as FoldableHKT, Foldable1, Foldable2, Foldable3 } from './Foldable' import { FoldableWithIndex1 } from './FoldableWithIndex' import { pipe } from './function' import { flap as flap_, Functor1 } from './Functor' import { FunctorWithIndex1 } from './FunctorWithIndex' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import * as _ from './internal' import { Magma } from './Magma' import { Monoid } from './Monoid' import { Option } from './Option' import { Ord } from './Ord' import { Predicate } from './Predicate' import * as RR from './ReadonlyRecord' import { Refinement } from './Refinement' import * as Se from './Semigroup' import { Separated } from './Separated' import { Show } from './Show' import * as S from './string' import { Traversable1 } from './Traversable' import { TraversableWithIndex1 } from './TraversableWithIndex' import { Unfoldable, Unfoldable1 } from './Unfoldable' import { PipeableWilt1, PipeableWither1, wiltDefault, Witherable1, witherDefault } from './Witherable' import Semigroup = Se.Semigroup // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * Calculate the number of key/value pairs in a `Record`. * * @example * import { size } from "fp-ts/Record"; * * assert.deepStrictEqual(size({ a: true, b: 2, c: "three" }), 3); * * @since 2.0.0 */ export const size: (r: Record) => number = RR.size /** * Test whether a `Record` is empty. * * @example * import { isEmpty } from "fp-ts/Record"; * * assert.deepStrictEqual(isEmpty({}), true); * assert.deepStrictEqual(isEmpty({ a: 3 }), false); * * @since 2.0.0 */ export const isEmpty: (r: Record) => boolean = RR.isEmpty const keys_ = (O: Ord) => (r: Record): Array => (Object.keys(r) as any).sort(O.compare) /** * The keys of a `Record`, sorted alphabetically. * * @example * import { keys } from "fp-ts/Record"; * * assert.deepStrictEqual(keys({ c: 1, a: 2, b: 3 }), ["a", "b", "c"]); * * @since 2.0.0 */ export const keys: (r: Record) => Array = /*#__PURE__*/ keys_(S.Ord) /** * Map a `Record` into an `Array`. * It passes each key/value pair to the iterating function and collects * the results in an array, sorted alphabetically by the original key. * * @example * import { collect } from 'fp-ts/Record' * import { Ord } from 'fp-ts/string' * * const f = (k: string, a: A) => `${k.toUpperCase()}-${a}`; * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual( * collect(Ord)(f)(x), * [ * "A-foo", * "B-false", * "C-3", * ] * ); * * @since 2.0.0 */ export function collect(O: Ord): (f: (k: K, a: A) => B) => (r: Record) => Array /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function collect(f: (k: K, a: A) => B): (r: Record) => Array export function collect( O: Ord | ((k: string, a: A) => B) ): | ((f: (k: K, a: A) => B) => (r: Record) => Array) | ((r: Record) => Array) { if (typeof O === 'function') { return collect(S.Ord)(O) } const keysO = keys_(O) return (f: (k: K, a: A) => B) => (r: Record) => { const out: Array = [] for (const key of keysO(r)) { out.push(f(key, r[key])) } return out } } /** * Get a sorted `Array` of the key/value pairs contained in a `Record`. * Sorted alphabetically by key. * * @example * import { toArray } from 'fp-ts/Record' * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(toArray(x), [ * ["a", "foo"], * ["b", false], * ["c", 3], * ]); * * @category conversions * @since 2.0.0 */ export const toArray: (r: Record) => Array<[K, A]> = /*#__PURE__*/ collect(S.Ord)((k, a) => [ k, a ]) /** * Unfolds a `Record` into a list of key/value pairs. * * Given an `Unfoldable` class type `U` such as `array` or `readonlyArray`, * it uses the `unfold` function to create an instance of `U`, * providing an iterating function that iterates over each * key/value pair in the record sorted alphabetically by key. * * @example * import { array, readonlyArray } from 'fp-ts' * import { toUnfoldable } from 'fp-ts/Record' * * assert.deepStrictEqual(toUnfoldable(array)({ b: 2, a: 1 }),[ [ 'a', 1 ], [ 'b', 2 ]]) * assert.deepStrictEqual(toUnfoldable(readonlyArray)({ b: 2, a: 1 }),[ [ 'a', 1 ], [ 'b', 2 ]]) * * @since 2.0.0 */ export function toUnfoldable( U: Unfoldable1 ): (r: Record) => Kind export function toUnfoldable(U: Unfoldable): (r: Record) => HKT export function toUnfoldable(U: Unfoldable): (r: Record) => HKT { return (r) => { const sas = toArray(r) const len = sas.length return U.unfold(0, (b) => (b < len ? _.some([sas[b], b + 1]) : _.none)) } } /** * Insert or replace a key/value pair in a `Record`. * * @example * import { upsertAt } from 'fp-ts/Record' * * assert.deepStrictEqual(upsertAt("a", 5)({ a: 1, b: 2 }), { a: 5, b: 2 }); * assert.deepStrictEqual(upsertAt("c", 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 }); * * @since 2.10.0 */ export const upsertAt: (k: string, a: A) => (r: Record) => Record = RR.upsertAt /** * Test whether or not a key exists in a `Record`. * * Note. This function is not pipeable because is a `Refinement`. * * @example * import { has } from 'fp-ts/Record' * * assert.deepStrictEqual(has("a", { a: 1, b: 2 }), true); * assert.deepStrictEqual(has("c", { a: 1, b: 2 }), false); * * @since 2.10.0 */ export const has: (k: string, r: Record) => k is K = RR.has /** * Delete a key and value from a `Record`. * * @example * import { deleteAt } from 'fp-ts/Record' * * assert.deepStrictEqual(deleteAt("a")({ a: 1, b: 2 }), { b: 2 }); * assert.deepStrictEqual(deleteAt("c")({ a: 1, b: 2 }), { a: 1, b: 2 }); * * @since 2.0.0 */ export function deleteAt( k: K ): (r: Record) => Record, A> export function deleteAt(k: string): (r: Record) => Record { return (r: Record) => { if (!_.has.call(r, k)) { return r } const out: Record = Object.assign({}, r) delete out[k] return out } } /** * Replace a key/value pair in a `Record`. * * @returns If the specified key exists it returns an `Option` containing a new `Record` * with the entry updated, otherwise it returns `None` * * @example * import { updateAt } from 'fp-ts/Record' * import { option } from 'fp-ts' * * assert.deepStrictEqual(updateAt("a", 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })); * assert.deepStrictEqual(updateAt("c", 3)({ a: 1, b: 2 }), option.none); * * @since 2.0.0 */ export const updateAt = (k: string, a: A): ((r: Record) => Option>) => modifyAt(k, () => a) /** * Applies a mapping function to one spcific key/value pair in a `Record`. * * @returns If the specified key exists it returns an `Option` containing a new `Record` * with the entry updated, otherwise it returns `None` * * @example * import { modifyAt } from 'fp-ts/Record' * import { option } from 'fp-ts' * * assert.deepStrictEqual(modifyAt("a", (x: number) => x * 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 })); * assert.deepStrictEqual(modifyAt("c", (x: number) => x * 3)({ a: 1, b: 2 }), option.none); * * @since 2.0.0 */ export const modifyAt = (k: string, f: (a: A) => A) => (r: Record): Option> => { if (!has(k, r)) { return _.none } const out: Record = Object.assign({}, r) out[k] = f(r[k]) return _.some(out) } /** * Delete a key and value from a `Record`, returning the value as well as the subsequent `Record`. * * @returns If the specified key exists it returns an `Option` containing a new `Record` * with the entry removed, otherwise it returns `None` * * @example * import { pop } from 'fp-ts/Record' * import { option } from 'fp-ts' * * assert.deepStrictEqual(pop("a")({ a: 1, b: 2, c: 3 }), option.some([1, { b: 2, c: 3 }])); * assert.deepStrictEqual(pop("x")({ a: 1, b: 2, c: 3 }), option.none); * * @since 2.0.0 */ export function pop( k: K ): (r: Record) => Option<[A, Record, A>]> export function pop(k: string): (r: Record) => Option<[A, Record]> { const deleteAtk = deleteAt(k) return (r) => { const oa = lookup(k, r) return _.isNone(oa) ? _.none : _.some([oa.value, deleteAtk(r)]) } } // TODO: remove non-curried overloading in v3 /** * Test whether one `Record` contains all of the keys and values * contained in another `Record`. * * @example * import { isSubrecord } from 'fp-ts/Record' * import { string } from 'fp-ts' * * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar", c: "baz" })({ a: "foo", b: "bar", c: "baz" }), * true * ); * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar", c: "baz" })({ a: "foo", c: "baz" }), * true * ); * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar", c: "baz" })({ a: "foo", b: "not-bar", c: "baz" }), * false * ); * assert.deepStrictEqual( * isSubrecord(string.Eq)({ a: "foo", b: "bar" })({ a: "foo", b: "bar", c: "baz" }), * false * ); * * @since 2.0.0 */ export const isSubrecord: (E: Eq) => { (that: Record): (me: Record) => boolean (me: Record, that: Record): boolean } = RR.isSubrecord // TODO: remove non-curried overloading in v3 /** * Lookup the value for a key in a `Record`. * * @returns If the specified key exists it returns an `Option` containing the value, * otherwise it returns `None` * * @example * import { lookup } from 'fp-ts/Record' * import { option } from 'fp-ts' * * assert.deepStrictEqual(lookup("b")({ a: "foo", b: "bar" }), option.some("bar")); * assert.deepStrictEqual(lookup("c")({ a: "foo", b: "bar" }), option.none); * * @since 2.0.0 */ export const lookup: { (k: string): (r: Record) => Option (k: string, r: Record): Option } = RR.lookup /** * Map a `Record` passing the key/value pairs to the iterating function. * * @example * import { mapWithIndex } from "fp-ts/Record"; * * const f = (k: string, n: number) => `${k.toUpperCase()}-${n}`; * assert.deepStrictEqual(mapWithIndex(f)({ a: 3, b: 5 }), { a: "A-3", b: "B-5" }); * * @since 2.0.0 */ export const mapWithIndex: (f: (k: K, a: A) => B) => (fa: Record) => Record = RR.mapWithIndex /** * Map a `Record` passing the values to the iterating function. * * @example * import { map } from "fp-ts/Record"; * * const f = (n: number) => `-${n}-`; * assert.deepStrictEqual(map(f)({ a: 3, b: 5 }), { a: "-3-", b: "-5-" }); * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Record) => Record = RR.map /** * Reduces a `Record` passing each key/value pair to the iterating function. * Entries are processed in the order, sorted by key according to * the given `Ord`. * * @example * import { reduceWithIndex } from "fp-ts/Record"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduceWithIndex(Ord)([] as string[], (k, b, a) => [...b, `${k}-${a}`])(x), [ * "a-foo", * "b-false", * "c-3", * ]); * * @since 2.0.0 */ export function reduceWithIndex( O: Ord ): (b: B, f: (k: K, b: B, a: A) => B) => (fa: Record) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduceWithIndex(b: B, f: (k: K, b: B, a: A) => B): (fa: Record) => B export function reduceWithIndex( ...args: [Ord] | [B, (k: string, b: B, a: A) => B] ): ((b: B, f: (k: string, b: B, a: A) => B) => (fa: Record) => B) | ((fa: Record) => B) { return args.length === 1 ? RR.reduceWithIndex(args[0]) : RR.reduceWithIndex(S.Ord)(...args) } /** * Map and fold a `Record`. * Map the `Record` passing each key/value pair to the iterating function. * Then fold the results using the provided `Monoid`. * * @example * import { foldMapWithIndex } from "fp-ts/Record"; * import { Ord } from "fp-ts/string"; * import { Monoid } from "fp-ts/Monoid"; * * const m: Monoid = { empty: "", concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) }; * const f = (k:string, a: number) => `${k}-${a}` * const x = { c: 3, a: 1, b: 2 }; * assert.deepStrictEqual(foldMapWithIndex(Ord)(m)(f)(x), "a-1 -> b-2 -> c-3"); * * @since 2.0.0 */ export function foldMapWithIndex( O: Ord ): (M: Monoid) => (f: (k: K, a: A) => M) => (fa: Record) => M /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function foldMapWithIndex( M: Monoid ): (f: (k: K, a: A) => M) => (fa: Record) => M export function foldMapWithIndex( O: Ord | Monoid ): | ((M: Monoid) => (f: (k: string, a: A) => M) => (fa: Record) => M) | ((f: (k: string, a: A) => M) => (fa: Record) => M) { return 'compare' in O ? RR.foldMapWithIndex(O) : RR.foldMapWithIndex(S.Ord)(O) } /** * Same as `reduceWithIndex`, but reduce starting from the right * (i.e. in reverse order, from the last to the first entry according to * the given `Ord`). * * @example * import { reduceRightWithIndex } from "fp-ts/Record"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduceRightWithIndex(Ord)([] as string[], (k, a, b) => [...b, `${k}-${a}`])(x), [ * "c-3", * "b-false", * "a-foo", * ]); * * @since 2.0.0 */ export function reduceRightWithIndex( O: Ord ): (b: B, f: (k: K, a: A, b: B) => B) => (fa: Record) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduceRightWithIndex(b: B, f: (k: K, a: A, b: B) => B): (fa: Record) => B export function reduceRightWithIndex( ...args: [Ord] | [B, (k: string, a: A, b: B) => B] ): ((b: B, f: (k: string, a: A, b: B) => B) => (fa: Record) => B) | ((fa: Record) => B) { return args.length === 1 ? RR.reduceRightWithIndex(args[0]) : RR.reduceRightWithIndex(S.Ord)(...args) } /** * Create a `Record` with one key/value pair. * * @example * import { singleton } from "fp-ts/Record"; * * assert.deepStrictEqual(singleton("a", 1), { a: 1 }); * * @since 2.0.0 */ export const singleton: (k: string, a: A) => Record = RR.singleton /** * @since 2.0.0 */ export function traverseWithIndex( F: Applicative4 ): ( f: (k: K, a: A) => Kind4 ) => (ta: Record) => Kind4> export function traverseWithIndex( F: Applicative3 ): ( f: (k: K, a: A) => Kind3 ) => (ta: Record) => Kind3> export function traverseWithIndex( F: Applicative3C ): ( f: (k: K, a: A) => Kind3 ) => (ta: Record) => Kind3> export function traverseWithIndex( F: Applicative2 ): (f: (k: K, a: A) => Kind2) => (ta: Record) => Kind2> export function traverseWithIndex( F: Applicative2C ): (f: (k: K, a: A) => Kind2) => (ta: Record) => Kind2> export function traverseWithIndex( F: Applicative1 ): (f: (k: K, a: A) => Kind) => (ta: Record) => Kind> export function traverseWithIndex( F: Applicative ): (f: (k: K, a: A) => HKT) => (ta: Record) => HKT> export function traverseWithIndex( F: Applicative ): (f: (k: string, a: A) => HKT) => (ta: Record) => HKT> { return RR.traverseWithIndex(F) } /** * @since 2.0.0 */ export function traverse( F: Applicative4 ): ( f: (a: A) => Kind4 ) => (ta: Record) => Kind4> export function traverse( F: Applicative3 ): (f: (a: A) => Kind3) => (ta: Record) => Kind3> export function traverse( F: Applicative3C ): (f: (a: A) => Kind3) => (ta: Record) => Kind3> export function traverse( F: Applicative2 ): (f: (a: A) => Kind2) => (ta: Record) => Kind2> export function traverse( F: Applicative2C ): (f: (a: A) => Kind2) => (ta: Record) => Kind2> export function traverse( F: Applicative1 ): (f: (a: A) => Kind) => (ta: Record) => Kind> export function traverse( F: Applicative ): (f: (a: A) => HKT) => (ta: Record) => HKT> export function traverse( F: Applicative ): (f: (a: A) => HKT) => (ta: Record) => HKT> { return RR.traverse(F) } /** * `Record` sequencing, * i.e., take a `Record` in which elements are monads * and return a monad of a `Record` of the base types. * The following example for instance shows sequencing * a `Record>` * into an `Option>`. * * `sequence` in `Record` is equivalent to `sequenceS` in `Apply.ts`. * * @example * import { sequence } from "fp-ts/Record"; * import { option } from "fp-ts"; * import { sequenceS } from "fp-ts/Apply"; * * assert.deepStrictEqual( * sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), * option.some({ a: 1, b: 2 }) * ); * assert.deepStrictEqual(sequence(option.Applicative)({ a: option.some(1), b: option.none }), option.none); * assert.deepStrictEqual( * sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }), * sequenceS(option.Applicative)({ a: option.some(1), b: option.some(2) }) * ); * * @since 2.0.0 */ export function sequence( F: Applicative3 ): (ta: Record>) => Kind3> export function sequence( F: Applicative3C ): (ta: Record>) => Kind3> export function sequence( F: Applicative2 ): (ta: Record>) => Kind2> export function sequence( F: Applicative2C ): (ta: Record>) => Kind2> export function sequence( F: Applicative1 ): (ta: Record>) => Kind> export function sequence(F: Applicative): (ta: Record>) => HKT> export function sequence(F: Applicative): (ta: Record>) => HKT> { return RR.sequence(F) } /** * @category filtering * @since 2.6.5 */ export const wither: PipeableWither1 = ( F: Applicative ): ((f: (a: A) => HKT>) => (fa: Record) => HKT>) => { const traverseF = traverse(F) return (f) => (fa) => F.map(pipe(fa, traverseF(f)), compact) } /** * @category filtering * @since 2.6.5 */ export const wilt: PipeableWilt1 = ( F: Applicative ): (( f: (a: A) => HKT> ) => (fa: Record) => HKT, Record>>) => { const traverseF = traverse(F) return (f) => (fa) => F.map(pipe(fa, traverseF(f)), separate) } /** * Maps a `Record` with a function returning an `Either` and * partitions the resulting `Record` into `Left`s and `Right`s. * * @example * import { partitionMapWithIndex } from "fp-ts/Record" * import { either } from "fp-ts" * * const f = (key: string, a: number) => * a >= 0 ? either.right(`${key} is >= 0 (${a})`) : either.left(`${key} is < 0 (${a})`); * assert.deepStrictEqual(partitionMapWithIndex(f)({ a: -1, b: 2, c: 123 }), { * left: { * a: "a is < 0 (-1)", * }, * right: { * b: "b is >= 0 (2)", * c: "c is >= 0 (123)", * }, * }); * * @since 2.0.0 */ export const partitionMapWithIndex: ( f: (key: K, a: A) => Either ) => (fa: Record) => Separated, Record> = RR.partitionMapWithIndex /** * Partition a `Record` into two parts according to a predicate * that takes a key and a value. * * @example * import { partitionWithIndex } from "fp-ts/Record" * * assert.deepStrictEqual( * partitionWithIndex((key: string, a: number) => key.length <= 1 && a > 0)({ a: -1, b: 2, ccc: 7 }), * { * left: { * a: -1, * ccc: 7, * }, * right: { * b: 2, * }, * } * ); * * @since 2.0.0 */ export function partitionWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: Record) => Separated, Record> export function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: Record) => Separated, Record> export function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: Record) => Separated, Record> export function partitionWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: Record) => Separated, Record> { return RR.partitionWithIndex(predicateWithIndex) } /** * Maps a `Record` with an iterating function that takes key and value and * returns an `Option`, keeping only the `Some` values and discarding `None`s. * * @example * import { filterMapWithIndex } from "fp-ts/Record" * import { option } from "fp-ts" * * const f = (key: string, a: number) => (a >= 0 ? option.some(`${key}${a}`) : option.none); * assert.deepStrictEqual(filterMapWithIndex(f)({ a: -1, b: 2, c: 3 }), { * b: "b2", * c: "c3", * }); * * @since 2.0.0 */ export const filterMapWithIndex: ( f: (key: K, a: A) => Option ) => (fa: Record) => Record = RR.filterMapWithIndex /** * Produce a new `Record` keeping only the entries that satisfy * a predicate taking key and value as input. * * @example * import { filterWithIndex } from "fp-ts/Record" * * assert.deepStrictEqual( * filterWithIndex((s: string, v: number) => s.length <= 1 && v > 0)({ a: 1, b: -2, ccc: 3 }), * { * a: 1, * } * ); * * @since 2.0.0 */ export function filterWithIndex( refinementWithIndex: RefinementWithIndex ): (fa: Record) => Record export function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fb: Record) => Record export function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: Record) => Record export function filterWithIndex( predicateWithIndex: PredicateWithIndex ): (fa: Record) => Record { return RR.filterWithIndex(predicateWithIndex) } /** * Create a `Record` from a foldable collection of key/value pairs, using the * specified `Magma` to combine values for duplicate keys. * * @since 2.0.0 */ export function fromFoldable( M: Magma, F: Foldable3 ): (fka: Kind3) => Record export function fromFoldable( M: Magma, F: Foldable2 ): (fka: Kind2) => Record export function fromFoldable( M: Magma, F: Foldable1 ): (fka: Kind) => Record export function fromFoldable(M: Magma, F: FoldableHKT): (fka: HKT) => Record export function fromFoldable(M: Magma, F: FoldableHKT): (fka: HKT) => Record { return RR.fromFoldable(M, F) } /** * Alias of [`toArray`](#toArray). * * @example * import { toEntries } from 'fp-ts/Record' * * assert.deepStrictEqual(toEntries({ b: 2, a: 1 }), [['a', 1], ['b', 2]]) * * @since 2.12.0 * @category conversions */ export const toEntries = toArray /** * Converts an `Array` of `[key, value]` tuples into a `Record`. * * @example * import { fromEntries } from 'fp-ts/Record' * * assert.deepStrictEqual(fromEntries([['a', 1], ['b', 2], ['a', 3]]), { b: 2, a: 3 }) * * @since 2.12.0 * @category conversions */ export const fromEntries = (fa: Array<[string, A]>): Record => fromFoldable(Se.last(), A.Foldable)(fa) /** * Create a `Record` from a foldable collection using the specified functions to * * - map to key/value pairs * - combine values for duplicate keys. * * @example * import { last } from 'fp-ts/Semigroup' * import { Foldable, zip } from 'fp-ts/Array' * import { identity } from 'fp-ts/function' * import { fromFoldableMap } from 'fp-ts/Record' * * export const zipObject = (keys: Array, values: Array): Record => * fromFoldableMap(last(), Foldable)(zip(keys, values), identity) * * assert.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 }) * * interface User { * readonly id: string * readonly name: string * } * * const users: Array = [ * { id: 'id1', name: 'name1' }, * { id: 'id2', name: 'name2' }, * { id: 'id1', name: 'name3' } * ] * * assert.deepStrictEqual(fromFoldableMap(last(), Foldable)(users, user => [user.id, user]), { * id1: { id: 'id1', name: 'name3' }, * id2: { id: 'id2', name: 'name2' } * }) * * @since 2.0.0 */ export function fromFoldableMap( M: Magma, F: Foldable3 ): (fa: Kind3, f: (a: A) => [string, B]) => Record export function fromFoldableMap( M: Magma, F: Foldable2 ): (fa: Kind2, f: (a: A) => [string, B]) => Record export function fromFoldableMap( M: Magma, F: Foldable1 ): (fa: Kind, f: (a: A) => [string, B]) => Record export function fromFoldableMap( M: Magma, F: FoldableHKT ): (fa: HKT, f: (a: A) => [string, B]) => Record export function fromFoldableMap( M: Magma, F: FoldableHKT ): (fa: HKT, f: (a: A) => [string, B]) => Record { return RR.fromFoldableMap(M, F) } /** * Test if every value in a `Record` satisfies the predicate. * * @example * import { every } from "fp-ts/Record" * * assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: 2 }), true); * assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: -1 }), false); * * @since 2.0.0 */ export const every: { (refinement: Refinement): Refinement, Record> (predicate: Predicate): Predicate> } = RR.every as any /** * Test if at least one value in a `Record` satisfies the predicate. * * @example * import { some } from "fp-ts/Record" * * assert.deepStrictEqual(some((n: number) => n >= 0)({ a: 1, b: -2 }), true); * assert.deepStrictEqual(some((n: number) => n >= 0)({ a: -1, b: -2 }), false); * * @since 2.0.0 */ export const some: (predicate: (a: A) => boolean) => (r: Record) => boolean = RR.some // TODO: remove non-curried overloading in v3 /** * Given an `Eq` checks if a `Record` contains an entry with * value equal to a provided value. * * @example * import { elem } from "fp-ts/Record" * import { number } from "fp-ts" * * assert.deepStrictEqual(elem(number.Eq)(123, { foo: 123, bar: 234 }), true); * assert.deepStrictEqual(elem(number.Eq)(-7, { foo: 123, bar: 234 }), false); * * @since 2.0.0 */ export const elem: (E: Eq) => { (a: A): (fa: Record) => boolean (a: A, fa: Record): boolean } = RR.elem /** * Union of two `Record`s. * Takes two `Record`s and produces a `Record` combining all the * entries of the two inputs. * It uses the `concat` function of the provided `Magma` to * combine the elements with the same key. * * @example * import { union } from "fp-ts/Record"; * import { Magma } from "fp-ts/Magma"; * * const m1: Magma = { concat: (x: number, y: number) => x + y }; * assert.deepStrictEqual(union(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4, b: 2, c: 3 }); * const m2: Magma = { concat: (x: number) => x }; * assert.deepStrictEqual(union(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 }); * * @since 2.11.0 */ export const union = ( M: Magma ): ((second: Record) => (first: Record) => Record) => { const unionM = RR.union(M) return (second) => (first) => { if (isEmpty(first)) { return { ...second } } if (isEmpty(second)) { return { ...first } } return unionM(second)(first) } } /** * Intersection of two `Record`s. * Takes two `Record`s and produces a `Record` combining only the * entries of the two inputswith the same key. * It uses the `concat` function of the provided `Magma` to * combine the elements. * * @example * import { intersection } from "fp-ts/Record"; * import { Magma } from "fp-ts/Magma"; * * const m1: Magma = { concat: (x: number, y: number) => x + y }; * assert.deepStrictEqual(intersection(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4}); * const m2: Magma = { concat: (x: number) => x }; * assert.deepStrictEqual(intersection(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1}); * * @since 2.11.0 */ export const intersection = (M: Magma) => (second: Record) => (first: Record): Record => { if (isEmpty(first) || isEmpty(second)) { return {} } return RR.intersection(M)(second)(first) } /** * Difference between two `Record`s. * Takes two `Record`s and produces a `Record` composed by the * entries of the two inputs, removing the entries with the same * key in both inputs. * * @example * import { difference } from "fp-ts/Record"; * * assert.deepStrictEqual(difference({ a: 1 })({ a: 1, b: 2 }), { b: 2 }); * assert.deepStrictEqual(difference({ a: 3 })({ a: 1, b: 2 }), { b: 2 }); * assert.deepStrictEqual(difference({ a: 3, c: 3 })({ a: 1, b: 2 }), { b: 2, c: 3 }); * * @since 2.11.0 */ export const difference = (second: Record) => (first: Record): Record => { if (isEmpty(first)) { return { ...second } } if (isEmpty(second)) { return { ...first } } return RR.difference(second)(first) } const _map = RR._map const _mapWithIndex = RR._mapWithIndex const _reduce = RR._reduce const _foldMap = RR._foldMap const _reduceRight = RR._reduceRight const _filter = RR._filter const _filterMap = RR._filterMap const _partition = RR._partition const _partitionMap = RR._partitionMap const _reduceWithIndex = RR._reduceWithIndex const _foldMapWithIndex = RR._foldMapWithIndex const _reduceRightWithIndex = RR._reduceRightWithIndex const _partitionMapWithIndex = RR._partitionMapWithIndex const _partitionWithIndex = RR._partitionWithIndex const _filterMapWithIndex = RR._filterMapWithIndex const _filterWithIndex = RR._filterWithIndex const _traverse = RR._traverse const _sequence = RR._sequence const _traverseWithIndex = (O: Ord) => ( F: Applicative ): ((ta: Record, f: (k: string, a: A) => HKT) => HKT>) => { const keysO = keys_(O) return (ta: Record, f: (k: string, a: A) => HKT) => { const ks = keysO(ta) if (ks.length === 0) { return F.of({}) } let fr: HKT> = F.of({}) for (const key of ks) { fr = F.ap( F.map(fr, (r) => (b: B) => { r[key] = b return r }), f(key, ta[key]) ) } return fr } } /** * Given a `Predicate`, it produces a new `Record` keeping only the entries with a * value that satisfies the provided predicate. * * @example * import { filter } from "fp-ts/Record" * * assert.deepStrictEqual(filter((s: string) => s.length < 4)({ a: "foo", b: "bar", c: "verylong" }), { * a: "foo", * b: "bar", * }); * * @category filtering * @since 2.0.0 */ export const filter: { (refinement: Refinement): (fa: Record) => Record (predicate: Predicate): (fb: Record) => Record (predicate: Predicate): (fa: Record) => Record } = RR.filter /** * Maps a `Record` with an iterating function that returns an `Option` * and it keeps only the `Some` values discarding the `None`s. * * @example * import { filterMap } from "fp-ts/Record" * import { option } from "fp-ts" * * const f = (s: string) => s.length < 4 ? option.some(`${s} is short`): option.none * assert.deepStrictEqual(filterMap(f)({ a: "foo", b: "bar", c: "verylong" }), { * a: "foo is short", * b: "bar is short", * }); * * @category filtering * @since 2.0.0 */ export const filterMap: (f: (a: A) => Option) => (fa: Record) => Record = RR.filterMap /** * Partition a `Record` into two parts according to a `Predicate`. * * @example * import { partition } from "fp-ts/Record" * * assert.deepStrictEqual(partition((s: string) => s.length < 4)({ a: "foo", b: "bar", c: "verylong" }), { * left:{ * c: "verylong" * }, * right: { * a: "foo", * b: "bar", * }, * }); * * @category filtering * @since 2.0.0 */ export const partition: { (refinement: Refinement): ( fa: Record ) => Separated, Record> (predicate: Predicate): (fb: Record) => Separated, Record> (predicate: Predicate): (fa: Record) => Separated, Record> } = RR.partition /** * Maps a `Record` with a function returning an `Either` and * partitions the resulting `Record` into `Left`s and `Right`s. * * @example * import { partitionMap } from "fp-ts/Record" * import { either } from "fp-ts" * * const f = (s: string) => (s.length < 4 ? either.right(`${s} is short`) : either.left(`${s} is not short`)); * assert.deepStrictEqual(partitionMap(f)({ a: "foo", b: "bar", c: "verylong" }), { * left: { * c: "verylong is not short", * }, * right: { * a: "foo is short", * b: "bar is short", * }, * }); * * @category filtering * @since 2.0.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: Record) => Separated, Record> = RR.partitionMap /** * Reduces a `Record` passing each value to the iterating function. * Entries are processed in order, sorted by key according to * the given `Ord`. * * @example * import { reduce } from "fp-ts/Record"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduce(Ord)([] as string[], (b, a) => [...b, `-${a}-`])(x), [ * "-foo-", * "-false-", * "-3-", * ]); * * @category folding * @since 2.0.0 */ export function reduce(O: Ord): (b: B, f: (b: B, a: A) => B) => (fa: Record) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduce(b: B, f: (b: B, a: A) => B): (fa: Record) => B export function reduce( ...args: [Ord] | [B, (b: B, a: A) => B] ): ((b: B, f: (b: B, a: A) => B) => (fa: Record) => B) | ((fa: Record) => B) { return args.length === 1 ? RR.reduce(args[0]) : RR.reduce(S.Ord)(...args) } /** * Map and fold a `Record`. * Map the `Record` passing each value to the iterating function. * Then fold the results using the provided `Monoid`. * * @example * import { foldMap } from "fp-ts/Record"; * import { Ord } from "fp-ts/string"; * import { Monoid } from "fp-ts/Monoid"; * * const m: Monoid = { empty: "", concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) }; * const f = (a: number) => `-${a}-`; * const x = { c: 3, a: 1, b: 2 }; * assert.deepStrictEqual(foldMap(Ord)(m)(f)(x), "-1- -> -2- -> -3-"); * * @category folding * @since 2.0.0 */ export function foldMap(O: Ord): (M: Monoid) => (f: (a: A) => M) => (fa: Record) => M /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function foldMap(M: Monoid): (f: (a: A) => M) => (fa: Record) => M export function foldMap( O: Ord | Monoid ): | ((M: Monoid) => (f: (a: A) => M) => (fa: Record) => M) | ((f: (a: A) => M) => (fa: Record) => M) { return 'compare' in O ? RR.foldMap(O) : RR.foldMap(S.Ord)(O) } /** * Same as `reduce` but entries are processed _from the right_, * i.e. in reverse order, from the last to the first entry, according to * the given `Ord`. * * @example * import { reduceRight } from "fp-ts/Record"; * import { Ord } from "fp-ts/string"; * * const x = { c: 3, a: "foo", b: false }; * assert.deepStrictEqual(reduceRight(Ord)([] as string[], (a, b) => [...b, `-${a}-`])(x), [ * "-3-", * "-false-", * "-foo-", * ]); * * @category folding * @since 2.0.0 */ export function reduceRight(O: Ord): (b: B, f: (a: A, b: B) => B) => (fa: Record) => B /** * Use the overload constrained by `Ord` instead. * * @deprecated */ export function reduceRight(b: B, f: (a: A, b: B) => B): (fa: Record) => B export function reduceRight( ...args: [Ord] | [B, (a: A, b: B) => B] ): ((b: B, f: (a: A, b: B) => B) => (fa: Record) => B) | ((fa: Record) => B) { return args.length === 1 ? RR.reduceRight(args[0]) : RR.reduceRight(S.Ord)(...args) } /** * Compact a `Record` of `Option`s discarding the `None` values and * keeping the `Some` values. * * @example * import { compact } from 'fp-ts/Record' * import { option } from 'fp-ts' * * assert.deepStrictEqual(compact({ a: option.some("foo"), b: option.none, c: option.some("bar") }), { * a: "foo", * c: "bar", * }); * * @category filtering * @since 2.0.0 */ export const compact: (fa: Record>) => Record = RR.compact /** * Separate a `Record` of `Either`s into `Left`s and `Right`s. * * @example * import { separate } from 'fp-ts/Record' * import { either } from 'fp-ts' * * assert.deepStrictEqual( * separate({ a: either.right("foo"), b: either.left("bar"), c: either.right("baz") }), * { * right: { * a: "foo", * c: "baz", * }, * left: { * b: "bar", * }, * } * ); * * @category filtering * @since 2.0.0 */ export const separate: (fa: Record>) => Separated, Record> = RR.separate /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Record' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Record } } /** * Produces a `Show` for a `Record`, given a `Show` for the base type * (a `Show` produces a human-readable representation of an instance). * `Record` entries are sorted by key with the provided `Ord`. * * @example * import { getShow } from "fp-ts/Record" * import { Show } from "fp-ts/Show" * import { Ord } from "fp-ts/string" * * const sNumber: Show = { show: (n: number) => `${n}` }; * const sRecord: Show> = getShow(Ord)(sNumber); * assert.deepStrictEqual(sRecord.show({ b: 2, a: 1 }), '{ "a": 1, "b": 2 }'); * * @category instances * @since 2.0.0 */ export function getShow(O: Ord): (S: Show) => Show> /** * Use the overload constrained by `Ord` instead. * * @category zone of death * @deprecated */ export function getShow(S: Show): Show> export function getShow( O: Ord | Show ): ((S: Show) => Show>) | Show> { return 'compare' in O ? RR.getShow(O) : RR.getShow(S.Ord)(O) } /** * Given an `Eq` for the base type, it produces an `Eq` * for a `Record` of that base type. * * @example * import { getEq } from "fp-ts/Record"; * import { string } from "fp-ts"; * import { Eq } from "fp-ts/Eq"; * * const eq: Eq> = getEq(string.Eq); * assert.deepStrictEqual(eq.equals({ a: "foo" }, { b: "bar" }), false); * assert.deepStrictEqual(eq.equals({ a: "foo" }, { a: "foo" }), true); * * @category instances * @since 2.0.0 */ export const getEq: (E: Eq) => Eq> = RR.getEq /** * Returns a `Monoid` instance for `Record`s, given a `Semigroup` * instance for the base type. * The `Monoid` makes the union of two `Record`s comining the * overlapping entries with the provided `Semigroup`. * * @example * import { SemigroupSum } from 'fp-ts/number' * import { getMonoid } from 'fp-ts/Record' * * const M = getMonoid(SemigroupSum); * assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579 , bar: 234, baz: 567 }); * * @category instances * @since 2.0.0 */ export const getMonoid: (S: Semigroup) => Monoid> = RR.getMonoid /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Takes a value and a `Record` of functions and returns a * `Record` by applying each function to the input value. * * @example * import { flap } from "fp-ts/Record" * * const fab = { x: (n: number) => `${n} times 2`, y: (n: number) => `${n * 2}` }; * assert.deepStrictEqual(flap(3)(fab), { * x: "3 times 2", * y: "6", * }); * * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.7.0 */ export const FunctorWithIndex: FunctorWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex } /** * Produces a `Foldable` instance for a `Record`, using the * provided `Ord` to sort the `Record`'s entries by key. * * @category folding * @since 2.11.0 */ export const getFoldable = (O: Ord): Foldable1 => ({ URI, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O) }) /** * Produces a `FoldableWithIndex1` instance for a `Record`, using the * provided `Ord` to sort the `Record`'s entries by key. * * @category folding * @since 2.11.0 */ export const getFoldableWithIndex = (O: Ord): FoldableWithIndex1 => ({ URI, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), reduceWithIndex: _reduceWithIndex(O), foldMapWithIndex: _foldMapWithIndex(O), reduceRightWithIndex: _reduceRightWithIndex(O) }) /** * @category instances * @since 2.7.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category instances * @since 2.7.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category instances * @since 2.7.0 */ export const FilterableWithIndex: FilterableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex } /** * Produces a `Traversable` instance for a `Record`, using the * provided `Ord` to sort the `Record`'s entries by key. * * @category traversing * @since 2.11.0 */ export const getTraversable = (O: Ord): Traversable1 => ({ URI, map: _map, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), traverse: _traverse(O), sequence: _sequence(O) }) /** * Produces a `TraversableWithIndex` instance for a `Record`, using the * provided `Ord` to sort the `Record`'s entries by key. * * @category traversing * @since 2.11.0 */ export const getTraversableWithIndex = (O: Ord): TraversableWithIndex1 => ({ URI, map: _map, mapWithIndex: _mapWithIndex, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), reduceWithIndex: _reduceWithIndex(O), foldMapWithIndex: _foldMapWithIndex(O), reduceRightWithIndex: _reduceRightWithIndex(O), traverse: _traverse(O), sequence: _sequence(O), traverseWithIndex: _traverseWithIndex(O) }) /** * @category filtering * @since 2.11.0 */ export const getWitherable = (O: Ord): Witherable1 => { const T = getTraversable(O) return { URI, map: _map, reduce: _reduce(O), foldMap: _foldMap(O), reduceRight: _reduceRight(O), traverse: T.traverse, sequence: T.sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, wither: witherDefault(T, Compactable), wilt: wiltDefault(T, Compactable) } } /** * Given a `Semigroup` in the base type, it produces a `Semigroup` * in the `Record` of the base type. * The resulting `Semigroup` concatenates two `Record`s by * `union`. * * @example * import { getUnionSemigroup } from "fp-ts/Record" * import { Semigroup } from "fp-ts/Semigroup" * * const sNumber: Semigroup = { concat: (x, y) => x - y }; * const sRecord: Semigroup> = getUnionSemigroup(sNumber); * assert.deepStrictEqual(sRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { a: 1, b: -1, c: 4 }); * * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (S: Semigroup): Semigroup> => { const unionS = union(S) return { concat: (first, second) => unionS(second)(first) } } /** * Same as `getMonoid`. * Returns a `Monoid` instance for `Record`s given a `Semigroup` * instance for the base type. * The `Monoid` makes the union of two `Record`s combining the * entries that have the same key with the provided `Semigroup`. * * @example * import { SemigroupSum } from 'fp-ts/number' * import { getUnionMonoid } from 'fp-ts/Record' * * const M = getUnionMonoid(SemigroupSum); * assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579 , bar: 234, baz: 567 }); * * @category instances * @since 2.11.0 */ export const getUnionMonoid = (S: Semigroup): Monoid> => ({ concat: getUnionSemigroup(S).concat, empty: {} }) /** * Given a `Semigroup` in the base type, it produces a `Semigroup` * in the `Record` of the base type. * The resulting `Semigroup` concatenates two `Record`s by * `intersection`. * * @example * import { getIntersectionSemigroup } from "fp-ts/Record" * import { Semigroup } from "fp-ts/Semigroup" * * const sNumber: Semigroup = { concat: (x, y) => x - y }; * const sRecord: Semigroup> = getIntersectionSemigroup(sNumber); * assert.deepStrictEqual(sRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { b: -1 }); * * @category instances * @since 2.11.0 */ export const getIntersectionSemigroup = (S: Semigroup): Semigroup> => { const intersectionS = intersection(S) return { concat: (first, second) => intersectionS(second)(first) } } /** * Produces a `Magma` with a `concat` function that combines * two `Record`s by making the `difference`. * * @example * import { getDifferenceMagma, difference } from "fp-ts/Record" * import { Magma } from "fp-ts/Magma" * * const r1 = { a: 3, c: 3 }; * const r2 = { a: 1, b: 2 }; * const m: Magma> = getDifferenceMagma(); * assert.deepStrictEqual(m.concat(r1, r2), difference(r2)(r1)); * assert.deepStrictEqual(m.concat(r1, r2), { c: 3, b: 2 }); * * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (): Magma> => ({ concat: (first, second) => difference(second)(first) }) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `getFoldable` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const Foldable: Foldable1 = { URI, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord) } /** * Use `getFoldableWithIndex` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const FoldableWithIndex: FoldableWithIndex1 = { URI, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), reduceWithIndex: /*#__PURE__*/ _reduceWithIndex(S.Ord), foldMapWithIndex: /*#__PURE__*/ _foldMapWithIndex(S.Ord), reduceRightWithIndex: /*#__PURE__*/ _reduceRightWithIndex(S.Ord) } /** * Use `getTraversable` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const Traversable: Traversable1 = { URI, map: _map, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence } /** * Use the `getTraversableWithIndex` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const TraversableWithIndex: TraversableWithIndex1 = { URI, map: _map, mapWithIndex: _mapWithIndex, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), reduceWithIndex: /*#__PURE__*/ _reduceWithIndex(S.Ord), foldMapWithIndex: /*#__PURE__*/ _foldMapWithIndex(S.Ord), reduceRightWithIndex: /*#__PURE__*/ _reduceRightWithIndex(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence, traverseWithIndex: /*#__PURE__*/ _traverseWithIndex(S.Ord) } const _wither = /*#__PURE__*/ witherDefault(Traversable, Compactable) const _wilt = /*#__PURE__*/ wiltDefault(Traversable, Compactable) /** * Use `getWitherable` instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const Witherable: Witherable1 = { URI, map: _map, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, wither: _wither, wilt: _wilt } /** * Use a new `{}` instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const empty: Record = {} /** * Use [`upsertAt`](#upsertat) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const insertAt: (k: string, a: A) => (r: Record) => Record = upsertAt /** * Use [`has`](#has) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const hasOwnProperty: (k: string, r: Record) => k is K = RR.hasOwnProperty /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `R.Functor` instead of `R.record` * (where `R` is from `import R from 'fp-ts/Record'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const record: FunctorWithIndex1 & FoldableWithIndex1 & FilterableWithIndex1 & TraversableWithIndex1 & Witherable1 = { URI, map: _map, reduce: /*#__PURE__*/ _reduce(S.Ord), foldMap: /*#__PURE__*/ _foldMap(S.Ord), reduceRight: /*#__PURE__*/ _reduceRight(S.Ord), traverse: /*#__PURE__*/ _traverse(S.Ord), sequence, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap, mapWithIndex: _mapWithIndex, reduceWithIndex: /*#__PURE__*/ _reduceWithIndex(S.Ord), foldMapWithIndex: /*#__PURE__*/ _foldMapWithIndex(S.Ord), reduceRightWithIndex: /*#__PURE__*/ _reduceRightWithIndex(S.Ord), filterMapWithIndex: _filterMapWithIndex, filterWithIndex: _filterWithIndex, partitionMapWithIndex: _partitionMapWithIndex, partitionWithIndex: _partitionWithIndex, traverseWithIndex: /*#__PURE__*/ _traverseWithIndex(S.Ord), wither: _wither, wilt: _wilt } ================================================ FILE: src/Refinement.ts ================================================ /** * @since 2.11.0 */ import { Either } from './Either' import * as _ from './internal' import { Option } from './Option' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export interface Refinement { (a: A): a is B } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Returns a `Refinement` from a `Option` returning function. * This function ensures that a `Refinement` definition is type-safe. * * @category lifting * @since 2.11.0 */ export const fromOptionK = (getOption: (a: A) => Option): Refinement => { return (a: A): a is B => _.isSome(getOption(a)) } /** * @category lifting * @since 2.11.0 */ export const fromEitherK = (getEither: (a: A) => Either): Refinement => { return (a: A): a is B => _.isRight(getEither(a)) } /** * @category constructors * @since 2.11.0 */ export const id = (): Refinement => { return (_): _ is A => true } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const not = (refinement: Refinement): Refinement> => (a): a is Exclude => !refinement(a) /** * @since 2.11.0 */ export const or = (second: Refinement) => (first: Refinement): Refinement => (a): a is B | C => first(a) || second(a) /** * @since 2.11.0 */ export const and = (second: Refinement) => (first: Refinement): Refinement => (a): a is B & C => first(a) && second(a) /** * @since 2.11.0 */ export const zero = (): Refinement => { return (_): _ is B => false } /** * @since 2.11.0 */ export const compose = (bc: Refinement) => (ab: Refinement): Refinement => { return (i): i is C => ab(i) && bc(i) } ================================================ FILE: src/Ring.ts ================================================ /** * The `Ring` class is for types that support addition, multiplication, and subtraction operations. * * Instances must satisfy the following law in addition to the `Semiring` laws: * * - Additive inverse: `a - a <-> (zero - a) + a <-> zero` * * Adapted from https://github.com/purescript/purescript-prelude/blob/master/src/Data/Ring.purs * * @since 2.0.0 */ import { getRing } from './function' import { Semiring } from './Semiring' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Ring extends Semiring { readonly sub: (x: A, y: A) => A } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Given a tuple of `Ring`s returns a `Ring` for the tuple * * @example * import { tuple } from 'fp-ts/Ring' * import * as N from 'fp-ts/number' * * const R = tuple(N.Field, N.Field, N.Field) * assert.deepStrictEqual(R.add([1, 2, 3], [4, 5, 6]), [5, 7, 9]) * assert.deepStrictEqual(R.mul([1, 2, 3], [4, 5, 6]), [4, 10, 18]) * assert.deepStrictEqual(R.one, [1, 1, 1]) * assert.deepStrictEqual(R.sub([1, 2, 3], [4, 5, 6]), [-3, -3, -3]) * assert.deepStrictEqual(R.zero, [0, 0, 0]) * * @since 2.10.0 */ export const tuple = >(...rings: { [K in keyof A]: Ring }): Ring> => ({ add: (x: any, y: any) => rings.map((R, i) => R.add(x[i], y[i])), zero: rings.map((R) => R.zero), mul: (x: any, y: any) => rings.map((R, i) => R.mul(x[i], y[i])), one: rings.map((R) => R.one), sub: (x: any, y: any) => rings.map((R, i) => R.sub(x[i], y[i])) } as any) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * `negate x` can be used as a shorthand for `zero - x` * * @since 2.0.0 */ export const negate = (R: Ring) => (a: A): A => R.sub(R.zero, a) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`tuple`](#tuple) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getTupleRing: >>( ...rings: T ) => Ring<{ [K in keyof T]: T[K] extends Ring ? A : never }> = tuple as any /** * Use [`getRing`](./function.ts.html#getring) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFunctionRing: (R: Ring) => Ring<(a: A) => B> = getRing ================================================ FILE: src/Semigroup.ts ================================================ /** * If a type `A` can form a `Semigroup` it has an **associative** binary operation. * * ```ts * interface Semigroup { * readonly concat: (x: A, y: A) => A * } * ``` * * Associativity means the following equality must hold for any choice of `x`, `y`, and `z`. * * ```ts * concat(x, concat(y, z)) = concat(concat(x, y), z) * ``` * * A common example of a semigroup is the type `string` with the operation `+`. * * ```ts * import { Semigroup } from 'fp-ts/Semigroup' * * const semigroupString: Semigroup = { * concat: (x, y) => x + y * } * * const x = 'x' * const y = 'y' * const z = 'z' * * semigroupString.concat(x, y) // 'xy' * * semigroupString.concat(x, semigroupString.concat(y, z)) // 'xyz' * * semigroupString.concat(semigroupString.concat(x, y), z) // 'xyz' * ``` * * *Adapted from https://typelevel.org/cats* * * @since 2.0.0 */ import { getSemigroup, identity } from './function' import * as _ from './internal' import * as M from './Magma' import * as Or from './Ord' import { ReadonlyRecord } from './ReadonlyRecord' import Ord = Or.Ord import Magma = M.Magma // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Semigroup extends Magma {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Get a semigroup where `concat` will return the minimum, based on the provided order. * * @example * import * as N from 'fp-ts/number' * import * as S from 'fp-ts/Semigroup' * * const S1 = S.min(N.Ord) * * assert.deepStrictEqual(S1.concat(1, 2), 1) * * @category constructors * @since 2.10.0 */ export const min = (O: Ord): Semigroup => ({ concat: Or.min(O) }) /** * Get a semigroup where `concat` will return the maximum, based on the provided order. * * @example * import * as N from 'fp-ts/number' * import * as S from 'fp-ts/Semigroup' * * const S1 = S.max(N.Ord) * * assert.deepStrictEqual(S1.concat(1, 2), 2) * * @category constructors * @since 2.10.0 */ export const max = (O: Ord): Semigroup => ({ concat: Or.max(O) }) /** * @category constructors * @since 2.10.0 */ export const constant = (a: A): Semigroup => ({ concat: () => a }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * The dual of a `Semigroup`, obtained by swapping the arguments of `concat`. * * @example * import { reverse } from 'fp-ts/Semigroup' * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(reverse(S.Semigroup).concat('a', 'b'), 'ba') * * @since 2.10.0 */ export const reverse: (S: Semigroup) => Semigroup = M.reverse /** * Given a struct of semigroups returns a semigroup for the struct. * * @example * import { struct } from 'fp-ts/Semigroup' * import * as N from 'fp-ts/number' * * interface Point { * readonly x: number * readonly y: number * } * * const S = struct({ * x: N.SemigroupSum, * y: N.SemigroupSum * }) * * assert.deepStrictEqual(S.concat({ x: 1, y: 2 }, { x: 3, y: 4 }), { x: 4, y: 6 }) * * @since 2.10.0 */ export const struct = (semigroups: { [K in keyof A]: Semigroup }): Semigroup<{ readonly [K in keyof A]: A[K] }> => ({ concat: (first, second) => { const r: A = {} as any for (const k in semigroups) { if (_.has.call(semigroups, k)) { r[k] = semigroups[k].concat(first[k], second[k]) } } return r } }) /** * Given a tuple of semigroups returns a semigroup for the tuple. * * @example * import { tuple } from 'fp-ts/Semigroup' * import * as B from 'fp-ts/boolean' * import * as N from 'fp-ts/number' * import * as S from 'fp-ts/string' * * const S1 = tuple(S.Semigroup, N.SemigroupSum) * assert.deepStrictEqual(S1.concat(['a', 1], ['b', 2]), ['ab', 3]) * * const S2 = tuple(S.Semigroup, N.SemigroupSum, B.SemigroupAll) * assert.deepStrictEqual(S2.concat(['a', 1, true], ['b', 2, false]), ['ab', 3, false]) * * @since 2.10.0 */ export const tuple = >( ...semigroups: { [K in keyof A]: Semigroup } ): Semigroup> => ({ concat: (first, second) => semigroups.map((s, i) => s.concat(first[i], second[i])) as any }) /** * Between each pair of elements insert `middle`. * * @example * import { intercalate } from 'fp-ts/Semigroup' * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * const S1 = pipe(S.Semigroup, intercalate(' + ')) * * assert.strictEqual(S1.concat('a', 'b'), 'a + b') * * @since 2.10.0 */ export const intercalate = (middle: A) => (S: Semigroup): Semigroup => ({ concat: (x, y) => S.concat(x, S.concat(middle, y)) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * Always return the first argument. * * @example * import * as S from 'fp-ts/Semigroup' * * assert.deepStrictEqual(S.first().concat(1, 2), 1) * * @category instances * @since 2.10.0 */ export const first = (): Semigroup => ({ concat: identity }) /** * Always return the last argument. * * @example * import * as S from 'fp-ts/Semigroup' * * assert.deepStrictEqual(S.last().concat(1, 2), 2) * * @category instances * @since 2.10.0 */ export const last = (): Semigroup => ({ concat: (_, y) => y }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Given a sequence of `as`, concat them and return the total. * * If `as` is empty, return the provided `startWith` value. * * @example * import { concatAll } from 'fp-ts/Semigroup' * import * as N from 'fp-ts/number' * * const sum = concatAll(N.SemigroupSum)(0) * * assert.deepStrictEqual(sum([1, 2, 3]), 6) * assert.deepStrictEqual(sum([]), 0) * * @since 2.10.0 */ export const concatAll: (S: Semigroup) => (startWith: A) => (as: ReadonlyArray) => A = M.concatAll // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `void` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupVoid: Semigroup = constant(undefined) /** * Use [`getAssignSemigroup`](./struct.ts.html#getAssignSemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getObjectSemigroup = (): Semigroup => ({ concat: (first, second) => Object.assign({}, first, second) }) /** * Use [`last`](#last) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getLastSemigroup = last /** * Use [`first`](#first) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFirstSemigroup = first /** * Use [`tuple`](#tuple) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getTupleSemigroup: >>( ...semigroups: T ) => Semigroup<{ [K in keyof T]: T[K] extends Semigroup ? A : never }> = tuple as any /** * Use [`struct`](#struct) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getStructSemigroup: >(semigroups: { [K in keyof O]: Semigroup }) => Semigroup = struct /** * Use [`reverse`](#reverse) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getDualSemigroup = reverse /** * Use [`max`](#max) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getJoinSemigroup = max /** * Use [`min`](#min) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getMeetSemigroup = min /** * Use [`intercalate`](#intercalate) instead. * * @category zone of death * @since 2.5.0 * @deprecated */ export const getIntercalateSemigroup = intercalate /** * Use [`concatAll`](#concatall) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function fold(S: Semigroup): { (startWith: A): (as: ReadonlyArray) => A (startWith: A, as: ReadonlyArray): A } export function fold(S: Semigroup): (startWith: A, as?: ReadonlyArray) => A | ((as: ReadonlyArray) => A) { const concatAllS = concatAll(S) return (startWith, as?) => (as === undefined ? concatAllS(startWith) : concatAllS(startWith)(as)) } /** * Use [`SemigroupAll`](./boolean.ts.html#SemigroupAll) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupAll: Semigroup = { concat: (x, y) => x && y } /** * Use [`SemigroupAny`](./boolean.ts.html#SemigroupAny) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupAny: Semigroup = { concat: (x, y) => x || y } /** * Use [`getSemigroup`](./function.ts.html#getSemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFunctionSemigroup: (S: Semigroup) => () => Semigroup<(a: A) => S> = getSemigroup /** * Use [`Semigroup`](./string.ts.html#Semigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupString: Semigroup = { concat: (x, y) => x + y } /** * Use [`SemigroupSum`](./number.ts.html#SemigroupSum) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupSum: Semigroup = { concat: (x, y) => x + y } /** * Use [`SemigroupProduct`](./number.ts.html#SemigroupProduct) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const semigroupProduct: Semigroup = { concat: (x, y) => x * y } ================================================ FILE: src/Semigroupoid.ts ================================================ /** * @since 2.0.0 */ import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Semigroupoid { readonly URI: F readonly compose: (bc: HKT2, ab: HKT2) => HKT2 } /** * @category model * @since 2.0.0 */ export interface Semigroupoid2 { readonly URI: F readonly compose: (ab: Kind2, la: Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Semigroupoid2C { readonly URI: F readonly _E: A readonly compose: (ab: Kind2, la: Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Semigroupoid3 { readonly URI: F readonly compose: (ab: Kind3, la: Kind3) => Kind3 } /** * @category model * @since 2.2.0 */ export interface Semigroupoid3C { readonly URI: F readonly _E: A readonly compose: (ab: Kind3, la: Kind3) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Semigroupoid4 { readonly URI: F readonly compose: (ab: Kind4, la: Kind4) => Kind4 } ================================================ FILE: src/Semiring.ts ================================================ /** * The `Semiring` class is for types that support an addition and multiplication operation. * * Instances must satisfy the following laws: * * - Commutative monoid under addition: * - Associativity: `(a + b) + c <-> a + (b + c)` * - Identity: `zero + a = a + zero <-> a` * - Commutative: `a + b <-> b + a` * - Monoid under multiplication: * - Associativity: `(a * b) * c <-> a * (b * c)` * - Identity: `one * a <-> a * one <-> a` * - Multiplication distributes over addition: * - Left distributivity: `a * (b + c) <-> (a * b) + (a * c)` * - Right distributivity: `(a + b) * c <-> (a * c) + (b * c)` * - Annihilation: `zero * a <-> a * zero <-> zero` * * **Note:** The `number` type is not fully law abiding members of this class hierarchy due to the potential * for arithmetic overflows, and the presence of `NaN` and `Infinity` values. The behaviour is * unspecified in these cases. * * @since 2.0.0 */ import { getSemiring } from './function' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Semiring { readonly add: (x: A, y: A) => A readonly zero: A readonly mul: (x: A, y: A) => A readonly one: A } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`getSemiring`](./function.ts.html#getsemiring) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getFunctionSemiring: (S: Semiring) => Semiring<(a: A) => B> = getSemiring ================================================ FILE: src/Separated.ts ================================================ /** * ```ts * interface Separated { * readonly left: E * readonly right: A * } * ``` * * Represents a result of separating a whole into two parts. * * @since 2.10.0 */ import { Bifunctor2 } from './Bifunctor' import { pipe } from './function' import { flap as flap_, Functor2 } from './Functor' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * A `Separated` type which holds `left` and `right` parts. * * @category model * @since 2.10.0 */ export interface Separated { readonly left: E readonly right: A } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.10.0 */ export const separated = (left: E, right: A): Separated => ({ left, right }) const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapLeft(f)) const _bimap: Bifunctor2['bimap'] = (fa, g, f) => pipe(fa, bimap(g, f)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.10.0 */ export const map = (f: (a: A) => B) => (fa: Separated): Separated => separated(left(fa), f(right(fa))) /** * Map a function over the first type argument of a bifunctor. * * @category error handling * @since 2.10.0 */ export const mapLeft = (f: (e: E) => G) => (fa: Separated): Separated => separated(f(left(fa)), right(fa)) /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.10.0 */ export const bimap = (f: (e: E) => G, g: (a: A) => B) => (fa: Separated): Separated => separated(f(left(fa)), g(right(fa))) /** * @category type lambdas * @since 2.10.0 */ export const URI = 'Separated' /** * @category type lambdas * @since 2.10.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Separated } } /** * @category instances * @since 2.10.0 */ export const Bifunctor: Bifunctor2 = { URI, mapLeft: _mapLeft, bimap: _bimap } /** * @category instances * @since 2.10.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export const left = (s: Separated): E => s.left /** * @since 2.10.0 */ export const right = (s: Separated): A => s.right ================================================ FILE: src/Set.ts ================================================ /** * @since 2.0.0 */ import { Either } from './Either' import { Eq } from './Eq' import { identity } from './function' import { Magma } from './Magma' import { Monoid } from './Monoid' import { Option } from './Option' import { Ord } from './Ord' import { Predicate } from './Predicate' import * as RS from './ReadonlySet' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Separated, separated } from './Separated' import { Show } from './Show' /** * @category instances * @since 2.0.0 */ export const getShow: (S: Show) => Show> = RS.getShow /** * @category instances * @since 2.0.0 */ export const getEq: (E: Eq) => Eq> = RS.getEq /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @since 2.0.0 */ export function map(E: Eq): (f: (x: A) => B) => (set: Set) => Set { const elemE = elem(E) return (f) => (set) => { const r = new Set() set.forEach((e) => { const v = f(e) if (!elemE(v, r)) { r.add(v) } }) return r } } /** * Composes computations in sequence, using the return value of one computation to determine the next computation. * * @since 2.0.0 */ export function chain(E: Eq): (f: (x: A) => Set) => (set: Set) => Set { const elemE = elem(E) return (f) => (set) => { const r = new Set() set.forEach((e) => { f(e).forEach((e) => { if (!elemE(e, r)) { r.add(e) } }) }) return r } } type Next = IteratorResult /** * @since 2.0.0 */ export function filter(refinement: Refinement): (set: Set) => Set export function filter(predicate: Predicate): (set: Set) => Set export function filter(predicate: Predicate): (set: Set) => Set export function filter(predicate: Predicate): (set: Set) => Set { return (set: Set) => { const values = set.values() let e: Next const r = new Set() while (!(e = values.next()).done) { const a = e.value if (predicate(a)) { r.add(a) } } return r } } /** * @since 2.0.0 */ export function partition(refinement: Refinement): (set: Set) => Separated, Set> export function partition(predicate: Predicate): (set: Set) => Separated, Set> export function partition(predicate: Predicate): (set: Set) => Separated, Set> export function partition(predicate: Predicate): (set: Set) => Separated, Set> { return (set: Set) => { const values = set.values() let e: Next const right = new Set() const left = new Set() while (!(e = values.next()).done) { const a = e.value if (predicate(a)) { right.add(a) } else { left.add(a) } } return separated(left, right) } } // TODO: remove non-curried overloading in v3 /** * Form the union of two sets * * @since 2.0.0 */ export function union(E: Eq): { (that: Set): (me: Set) => Set (me: Set, that: Set): Set } export function union(E: Eq): (me: Set, that?: Set) => Set | ((me: Set) => Set) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const unionE = union(E) return (that) => unionE(me, that) } if (isEmpty(me)) { return that } if (isEmpty(that)) { return me } const r = new Set(me) that.forEach((e) => { if (!elemE(e, r)) { r.add(e) } }) return r } } // TODO: remove non-curried overloading in v3 /** * The set of elements which are in both the first and second set * * @since 2.0.0 */ export function intersection(E: Eq): { (that: Set): (me: Set) => Set (me: Set, that: Set): Set } export function intersection(E: Eq): (me: Set, that?: Set) => Set | ((that: Set) => Set) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const intersectionE = intersection(E) return (that) => intersectionE(that, me) } if (isEmpty(me) || isEmpty(that)) { return new Set() } const r = new Set() me.forEach((e) => { if (elemE(e, that)) { r.add(e) } }) return r } } /** * @since 2.0.0 */ export function partitionMap( EB: Eq, EC: Eq ): (f: (a: A) => Either) => (set: Set) => Separated, Set> { return (f: (a: A) => Either) => (set: Set) => { const values = set.values() let e: Next const left = new Set() const right = new Set() const hasB = elem(EB) const hasC = elem(EC) while (!(e = values.next()).done) { const v = f(e.value) switch (v._tag) { case 'Left': if (!hasB(v.left, left)) { left.add(v.left) } break case 'Right': if (!hasC(v.right, right)) { right.add(v.right) } break } } return separated(left, right) } } // TODO: remove non-curried overloading in v3 /** * Form the set difference (`x` - `y`) * * @example * import { difference } from 'fp-ts/Set' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(new Set([1, 2]), difference(N.Eq)(new Set([1, 3]))), new Set([2])) * * @since 2.0.0 */ export function difference(E: Eq): { (that: Set): (me: Set) => Set (me: Set, that: Set): Set } export function difference(E: Eq): (me: Set, that?: Set) => Set | ((me: Set) => Set) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const differenceE = difference(E) return (that) => differenceE(that, me) } return filter((a: A) => !elemE(a, that))(me) } } /** * @category instances * @since 2.11.0 */ export const getUnionSemigroup = (E: Eq): Semigroup> => ({ concat: union(E) }) /** * @category instances * @since 2.0.0 */ export const getUnionMonoid = (E: Eq): Monoid> => ({ concat: getUnionSemigroup(E).concat, empty: new Set() }) /** * @category instances * @since 2.0.0 */ export const getIntersectionSemigroup = (E: Eq): Semigroup> => ({ concat: intersection(E) }) /** * @category instances * @since 2.11.0 */ export const getDifferenceMagma = (E: Eq): Magma> => ({ concat: difference(E) }) /** * @category folding * @since 2.0.0 */ export const reduce: (O: Ord) => (b: B, f: (b: B, a: A) => B) => (fa: Set) => B = RS.reduce /** * @category folding * @since 2.0.0 */ export const foldMap: (O: Ord, M: Monoid) => (f: (a: A) => M) => (fa: Set) => M = RS.foldMap /** * @category folding * @since 2.11.0 */ export const reduceRight: (O: Ord) => (b: B, f: (a: A, b: B) => B) => (fa: Set) => B = RS.reduceRight /** * Create a set with one element * * @category constructors * @since 2.0.0 */ export const singleton = (a: A): Set => new Set([a]) /** * Insert a value into a set * * @since 2.0.0 */ export function insert(E: Eq): (a: A) => (set: Set) => Set { const elemE = elem(E) return (a) => (set) => { if (!elemE(a)(set)) { const r = new Set(set) r.add(a) return r } else { return set } } } /** * Delete a value from a set * * @since 2.0.0 */ export const remove = (E: Eq) => (a: A) => (set: Set): Set => filter((ax: A) => !E.equals(a, ax))(set) /** * Checks an element is a member of a set; * If yes, removes the value from the set * If no, inserts the value to the set * * @since 2.5.0 */ export const toggle = (E: Eq): ((a: A) => (set: Set) => Set) => { const elemE = elem(E) const removeE = remove(E) const insertE = insert(E) return (a) => (set) => (elemE(a, set) ? removeE : insertE)(a)(set) } /** * Create a set from an array * * @category conversions * @since 2.0.0 */ export const fromArray = (E: Eq) => (as: Array): Set => { const len = as.length const out = new Set() const has = elem(E) for (let i = 0; i < len; i++) { const a = as[i] if (!has(a, out)) { out.add(a) } } return out } /** * @since 2.0.0 */ export const compact = (E: Eq): ((fa: Set>) => Set) => filterMap(E)(identity) /** * @since 2.0.0 */ export function separate(EE: Eq, EA: Eq): (fa: Set>) => Separated, Set> { return (fa) => { const elemEE = elem(EE) const elemEA = elem(EA) const left: Set = new Set() const right: Set = new Set() fa.forEach((e) => { switch (e._tag) { case 'Left': if (!elemEE(e.left, left)) { left.add(e.left) } break case 'Right': if (!elemEA(e.right, right)) { right.add(e.right) } break } }) return separated(left, right) } } /** * @since 2.0.0 */ export function filterMap(E: Eq): (f: (a: A) => Option) => (fa: Set) => Set { const elemE = elem(E) return (f) => (fa) => { const r: Set = new Set() fa.forEach((a) => { const ob = f(a) if (ob._tag === 'Some' && !elemE(ob.value, r)) { r.add(ob.value) } }) return r } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export const empty: Set = new Set() /** * Test whether a `Set` is empty. * * @since 2.10.0 */ export const isEmpty = (set: Set): boolean => set.size === 0 /** * Calculate the number of elements in a `Set`. * * @since 2.10.0 */ export const size = (set: Set): number => set.size /** * @since 2.0.0 */ export const some: (predicate: Predicate) => (set: Set) => boolean = RS.some /** * @since 2.0.0 */ export const every: { (refinement: Refinement): Refinement, Set> (predicate: Predicate): Predicate> } = RS.every as any /** * @since 2.10.0 */ export const isSubset: (E: Eq) => (that: Set) => (me: Set) => boolean = RS.isSubset // TODO: remove non-curried overloading in v3 /** * Test if a value is a member of a set * * @since 2.0.0 */ export const elem: (E: Eq) => { (a: A): (set: Set) => boolean (a: A, set: Set): boolean } = RS.elem /** * Get a sorted `Array` of the values contained in a `Set`. * * @category conversions * @since 2.0.0 */ export const toArray = (O: Ord) => (set: Set): Array => { const out: Array = [] set.forEach((e) => out.push(e)) return out.sort(O.compare) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`isSubset`](#issubset) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const subset: (E: Eq) => { (that: Set): (me: Set) => boolean (me: Set, that: Set): boolean } = RS.isSubset ================================================ FILE: src/Show.ts ================================================ /** * The `Show` type class represents those types which can be converted into * a human-readable `string` representation. * * While not required, it is recommended that for any expression `x`, the * string `show(x)` be executable TypeScript code which evaluates to the same * value as the expression `x`. * * @since 2.0.0 */ import * as _ from './internal' import { ReadonlyRecord } from './ReadonlyRecord' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Show { readonly show: (a: A) => string } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export const struct = (shows: { [K in keyof A]: Show }): Show<{ readonly [K in keyof A]: A[K] }> => ({ show: (a) => { let s = '{' for (const k in shows) { if (_.has.call(shows, k)) { s += ` ${k}: ${shows[k].show(a[k])},` } } if (s.length > 1) { s = s.slice(0, -1) + ' ' } s += '}' return s } }) /** * @since 2.10.0 */ export const tuple = >( ...shows: { [K in keyof A]: Show } ): Show> => ({ show: (t) => `[${t.map((a, i) => shows[i].show(a)).join(', ')}]` }) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`tuple`](#tuple) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getTupleShow: >>( ...shows: T ) => Show<{ [K in keyof T]: T[K] extends Show ? A : never }> = tuple /** * Use [`struct`](#struct) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getStructShow: >(shows: { [K in keyof O]: Show }) => Show = struct /** * Use [`Show`](./boolean.ts.html#show) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const showBoolean: Show = { show: (a) => JSON.stringify(a) } /** * Use [`Show`](./string.ts.html#show) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const showString: Show = { show: (a) => JSON.stringify(a) } /** * Use [`Show`](./number.ts.html#show) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const showNumber: Show = { show: (a) => JSON.stringify(a) } ================================================ FILE: src/State.ts ================================================ /** * @since 2.0.0 */ import { Applicative2 } from './Applicative' import { apFirst as apFirst_, Apply2, apS as apS_, apSecond as apSecond_ } from './Apply' import * as chainable from './Chain' import { FromState2 } from './FromState' import { dual, identity, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor2, let as let__ } from './Functor' import * as _ from './internal' import { Monad2 } from './Monad' import { NonEmptyArray } from './NonEmptyArray' import { Pointed2 } from './Pointed' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface State { (s: S): [A, S] } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Get the current state * * @category constructors * @since 2.0.0 */ export const get: () => State = () => (s) => [s, s] /** * Set the state * * @category constructors * @since 2.0.0 */ export const put: (s: S) => State = (s) => () => [undefined, s] /** * Modify the state by applying a function to the current state * * @category constructors * @since 2.0.0 */ export const modify: (f: (s: S) => S) => State = (f) => (s) => [undefined, f(s)] /** * Get a value which depends on the current state * * @category constructors * @since 2.0.0 */ export const gets: (f: (s: S) => A) => State = (f) => (s) => [f(s), s] /* istanbul ignore next */ const _map: Monad2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _ap: Monad2['ap'] = (fab, fa) => pipe(fab, ap(fa)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: State) => State = (f) => (fa) => (s1) => { const [a, s2] = fa(s1) return [f(a), s2] } /** * @since 2.0.0 */ export const ap: (fa: State) => (fab: State B>) => State = (fa) => (fab) => (s1) => { const [f, s2] = fab(s1) const [a, s3] = fa(s2) return [f(a), s3] } /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => State = (a) => (s) => [a, s] /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => State): (ma: State) => State (ma: State, f: (a: A) => State): State } = /*#__PURE__*/ dual( 2, (ma: State, f: (a: A) => State): State => (s1) => { const [a, s2] = ma(s1) return f(a)(s2) } ) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: State>) => State = /*#__PURE__*/ flatMap(identity) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'State' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: State } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply2 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative2 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad2 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: State, f: (a: A) => State): State (f: (a: A) => State): (self: State) => State } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * @category instances * @since 2.11.0 */ export const FromState: FromState2 = { URI, fromState: identity } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Run a computation in the `State` monad, discarding the final state * * @since 2.8.0 */ export const evaluate = (s: S) => (ma: State): A => ma(s)[0] /** * Run a computation in the `State` monad discarding the result * * @since 2.8.0 */ export const execute = (s: S) => (ma: State): S => ma(s)[1] // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @since 2.13.0 */ let_ as let } /** * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) // ------------------------------------------------------------------------------------- // pipeable sequence S // ------------------------------------------------------------------------------------- /** * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => State) => (as: ReadonlyNonEmptyArray): State> => (s) => { const [b, s2] = f(0, _.head(as))(s) const bs: NonEmptyArray = [b] let out = s2 for (let i = 1; i < as.length; i++) { const [b, s2] = f(i, as[i])(out) bs.push(b) out = s2 } return [bs, out] } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => State ): ((as: ReadonlyArray) => State>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : of(_.emptyReadonlyArray)) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => State ) => (as: ReadonlyArray) => State> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => State ): ((as: ReadonlyArray) => State>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => State> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => State) => (ma: State) => State = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => State) => (ma: State) => State = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`evaluate`](#evaluate) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const evalState: (ma: State, s: S) => A = (ma, s) => ma(s)[0] /** * Use [`execute`](#execute) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const execState: (ma: State, s: S) => S = (ma, s) => ma(s)[1] /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `S.Functor` instead of `S.state` * (where `S` is from `import S from 'fp-ts/State'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const state: Monad2 = Monad ================================================ FILE: src/StateReaderTaskEither.ts ================================================ /** * @since 2.0.0 */ import { Alt4 } from './Alt' import { Applicative4 } from './Applicative' import { apFirst as apFirst_, Apply4, apS as apS_, apSecond as apSecond_ } from './Apply' import { Bifunctor4 } from './Bifunctor' import * as chainable from './Chain' import * as E from './Either' import { Endomorphism } from './Endomorphism' import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, FromEither4, fromEitherK as fromEitherK_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_, tapEither as tapEither_ } from './FromEither' import { FromIO4, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { ask as ask_, asks as asks_, FromReader4, fromReaderK as fromReaderK_, tapReader as tapReader_ } from './FromReader' import { chainStateK as chainStateK_, FromState4, fromStateK as fromStateK_, get as get_, gets as gets_, modify as modify_, put as put_ } from './FromState' import { FromTask4, fromTaskK as fromTaskK_, tapTask as tapTask_ } from './FromTask' import { dual, flow, identity, LazyArg, pipe } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor4, let as let__ } from './Functor' import * as _ from './internal' import { IO } from './IO' import { IOEither } from './IOEither' import { Monad4 } from './Monad' import { MonadIO4 } from './MonadIO' import { MonadTask4 } from './MonadTask' import { MonadThrow4 } from './MonadThrow' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { Pointed4 } from './Pointed' import { Predicate } from './Predicate' import * as R from './Reader' import { ReaderEither } from './ReaderEither' import * as RTE from './ReaderTaskEither' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { State } from './State' import * as ST from './StateT' import { Task } from './Task' import { TaskEither } from './TaskEither' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- import ReaderTaskEither = RTE.ReaderTaskEither import Either = E.Either import Reader = R.Reader /** * @category model * @since 2.0.0 */ export interface StateReaderTaskEither { (s: S): ReaderTaskEither } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export const left: (e: E) => StateReaderTaskEither = (e) => () => RTE.left(e) /** * @category constructors * @since 2.0.0 */ export const right: (a: A) => StateReaderTaskEither = /*#__PURE__*/ ST.of( RTE.Pointed ) /** * @category constructors * @since 2.0.0 */ export function rightTask(ma: Task): StateReaderTaskEither { return fromReaderTaskEither(RTE.rightTask(ma)) } /** * @category constructors * @since 2.0.0 */ export function leftTask(me: Task): StateReaderTaskEither { return fromReaderTaskEither(RTE.leftTask(me)) } /** * @category constructors * @since 2.0.0 */ export function rightReader(ma: Reader): StateReaderTaskEither { return fromReaderTaskEither(RTE.rightReader(ma)) } /** * @category constructors * @since 2.0.0 */ export function leftReader(me: Reader): StateReaderTaskEither { return fromReaderTaskEither(RTE.leftReader(me)) } /** * @category constructors * @since 2.0.0 */ export function rightIO(ma: IO): StateReaderTaskEither { return fromReaderTaskEither(RTE.rightIO(ma)) } /** * @category constructors * @since 2.0.0 */ export function leftIO(me: IO): StateReaderTaskEither { return fromReaderTaskEither(RTE.leftIO(me)) } /** * @category constructors * @since 2.0.0 */ export const rightState: (ma: State) => StateReaderTaskEither = (sa) => flow(sa, RTE.right) /** * @category constructors * @since 2.0.0 */ export const leftState: (me: State) => StateReaderTaskEither = (me) => (s) => RTE.left(me(s)[0]) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.0.0 */ export const fromEither: (fa: Either) => StateReaderTaskEither = /*#__PURE__*/ E.match((e) => left(e), right) /** * @category conversions * @since 2.11.0 */ export const fromReader: (fa: Reader) => StateReaderTaskEither = rightReader /** * @category conversions * @since 2.7.0 */ export const fromIO: (fa: IO) => StateReaderTaskEither = rightIO /** * @category conversions * @since 2.7.0 */ export const fromTask: (fa: Task) => StateReaderTaskEither = rightTask /** * @category conversions * @since 2.10.0 */ export const fromState: (fa: State) => StateReaderTaskEither = /*#__PURE__*/ ST.fromState(RTE.Pointed) /** * @category conversions * @since 2.0.0 */ export const fromTaskEither: (fa: TaskEither) => StateReaderTaskEither = (ma) => fromReaderTaskEither(RTE.fromTaskEither(ma)) /** * @category conversions * @since 2.0.0 */ export const fromIOEither: (fa: IOEither) => StateReaderTaskEither = (ma) => fromReaderTaskEither(RTE.fromIOEither(ma)) /** * @category conversions * @since 2.0.0 */ export const fromReaderEither: (fa: ReaderEither) => StateReaderTaskEither = (ma) => fromReaderTaskEither(RTE.fromReaderEither(ma)) /** * @category constructors * @since 2.0.0 */ export const fromReaderTaskEither: (fa: ReaderTaskEither) => StateReaderTaskEither = /*#__PURE__*/ ST.fromF(RTE.Functor) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Changes the value of the local context during the execution of the action `ma` (similar to `Contravariant`'s * `contramap`). * * @since 2.11.0 */ export const local = (f: (r2: R2) => R1) => (ma: StateReaderTaskEither): StateReaderTaskEither => flow(ma, R.local(f)) /** * Less strict version of [`asksStateReaderTaskEither`](#asksstatereadertaskeither). * * @category constructors * @since 2.11.0 */ export const asksStateReaderTaskEitherW = (f: (r1: R1) => StateReaderTaskEither): StateReaderTaskEither => (s) => (r) => f(r)(s)(r) /** * Effectfully accesses the environment. * * @category constructors * @since 2.11.0 */ export const asksStateReaderTaskEither: ( f: (r: R) => StateReaderTaskEither ) => StateReaderTaskEither = asksStateReaderTaskEitherW /** * @category lifting * @since 2.4.0 */ export const fromIOEitherK = , B>( f: (...a: A) => IOEither ): ((...a: A) => StateReaderTaskEither) => (...a) => fromIOEither(f(...a)) /** * @category lifting * @since 2.4.0 */ export const fromTaskEitherK = , B>( f: (...a: A) => TaskEither ): ((...a: A) => StateReaderTaskEither) => (...a) => fromTaskEither(f(...a)) /** * @category lifting * @since 2.4.0 */ export const fromReaderTaskEitherK = , B>( f: (...a: A) => ReaderTaskEither ): ((...a: A) => StateReaderTaskEither) => (...a) => fromReaderTaskEither(f(...a)) /** * Alias of `flatMapReaderTaskEither`. * * Less strict version of [`chainReaderTaskEitherK`](#chainreadertaskeitherk). * * @category legacy * @since 2.6.1 */ export const chainReaderTaskEitherKW = (f: (a: A) => ReaderTaskEither) => (ma: StateReaderTaskEither): StateReaderTaskEither => flatMap(ma, fromReaderTaskEitherK(f)) /** * Alias of `flatMapReaderTaskEither`. * * @category legacy * @since 2.4.0 */ export const chainReaderTaskEitherK: ( f: (a: A) => ReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = chainReaderTaskEitherKW /* istanbul ignore next */ const _map: Monad4['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _ap: Monad4['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _alt: ( fa: StateReaderTaskEither, that: LazyArg> ) => StateReaderTaskEither = (fa, that) => (s) => pipe( fa(s), RTE.alt(() => that()(s)) ) const _bimap: ( fea: StateReaderTaskEither, f: (e: E) => G, g: (a: A) => B ) => StateReaderTaskEither = (fea, f, g) => (s) => pipe( fea(s), RTE.bimap(f, ([a, s]) => [g(a), s]) ) const _mapLeft: ( fea: StateReaderTaskEither, f: (e: E) => G ) => StateReaderTaskEither = (fea, f) => (s) => pipe(fea(s), RTE.mapLeft(f)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: ( f: (a: A) => B ) => (fa: StateReaderTaskEither) => StateReaderTaskEither = /*#__PURE__*/ ST.map( RTE.Functor ) /** * Map a pair of functions over the two last type arguments of the bifunctor. * * @category mapping * @since 2.6.2 */ export const bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: StateReaderTaskEither) => StateReaderTaskEither = (f, g) => (fa) => _bimap(fa, f, g) /** * Map a function over the third type argument of a bifunctor. * * @category error handling * @since 2.6.2 */ export const mapLeft: ( f: (e: E) => G ) => (fa: StateReaderTaskEither) => StateReaderTaskEither = (f) => (fa) => _mapLeft(fa, f) /** * @since 2.0.0 */ export const ap: ( fa: StateReaderTaskEither ) => (fab: StateReaderTaskEither B>) => StateReaderTaskEither = /*#__PURE__*/ ST.ap( RTE.Chain ) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.8.0 */ export const apW: ( fa: StateReaderTaskEither ) => (fab: StateReaderTaskEither B>) => StateReaderTaskEither = ap as any /** * @category constructors * @since 2.7.0 */ export const of: (a: A) => StateReaderTaskEither = right /** @internal */ interface StateReaderTaskEitherTypeLambda extends _.TypeLambda { readonly type: StateReaderTaskEither } /** @internal */ const _FromIO: _.FromIO = { fromIO } /** @internal */ const _FromTask: _.FromTask = { fromTask } /** @internal */ const _FromReader: _.FromReader = { fromReader } /** @internal */ const _FromEither: _.FromEither = { fromEither } /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => StateReaderTaskEither): ( ma: StateReaderTaskEither ) => StateReaderTaskEither ( ma: StateReaderTaskEither, f: (a: A) => StateReaderTaskEither ): StateReaderTaskEither } = /*#__PURE__*/ dual(2, ST.flatMap(RTE.Monad)) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** * @category sequencing * @since 2.16.0 */ export const flatMapTaskEither: { (f: (a: A) => TaskEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => TaskEither): StateReaderTaskEither< S, R, E1 | E2, B > } = /*#__PURE__*/ dual( 2, ( self: StateReaderTaskEither, f: (a: A) => TaskEither ): StateReaderTaskEither => flatMap(self, (a: A) => fromTaskEitherK(f)(a)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => IO): StateReaderTaskEither } = /*#__PURE__*/ _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapTask: { (f: (a: A) => Task): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Task): StateReaderTaskEither } = /*#__PURE__*/ _.flatMapTask(_FromTask, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReader: { (f: (a: A) => Reader): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Reader): StateReaderTaskEither< S, R1 & R2, E, B > } = /*#__PURE__*/ _.flatMapReader(_FromReader, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapIOEither: { (f: (a: A) => IOEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => IOEither): StateReaderTaskEither< S, R, E1 | E2, B > } = /*#__PURE__*/ dual( 2, ( self: StateReaderTaskEither, f: (a: A) => IOEither ): StateReaderTaskEither => flatMap(self, (a: A) => fromIOEitherK(f)(a)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapEither: { (f: (a: A) => Either): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Either): StateReaderTaskEither< S, R, E1 | E2, B > } = /*#__PURE__*/ dual(2, _.flatMapEither(_FromEither, _FlatMap)) /** * @category sequencing * @since 2.16.0 */ export const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: StateReaderTaskEither ) => StateReaderTaskEither ( self: StateReaderTaskEither, f: (a: A) => Option, onNone: (a: A) => E2 ): StateReaderTaskEither } = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapReaderTaskEither: { (f: (a: A) => ReaderTaskEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither ( self: StateReaderTaskEither, f: (a: A) => ReaderTaskEither ): StateReaderTaskEither } = /*#__PURE__*/ dual( 2, ( self: StateReaderTaskEither, f: (a: A) => ReaderTaskEither ): StateReaderTaskEither => flatMap(self, (a: A) => fromReaderTaskEitherK(f)(a)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapState: { (f: (a: A) => State): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => State): StateReaderTaskEither } = /*#__PURE__*/ dual( 2, ( self: StateReaderTaskEither, f: (a: A) => State ): StateReaderTaskEither => flatMap(self, fromStateK(f)) ) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: ( mma: StateReaderTaskEither> ) => StateReaderTaskEither = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: ( mma: StateReaderTaskEither> ) => StateReaderTaskEither = flattenW /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the environment, the error and the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW = (that: () => StateReaderTaskEither) => (fa: StateReaderTaskEither): StateReaderTaskEither => (r) => pipe( fa(r), RTE.altW(() => that()(r)) ) /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * @category error handling * @since 2.6.2 */ export const alt: ( that: LazyArg> ) => (fa: StateReaderTaskEither) => StateReaderTaskEither = altW /** * @since 2.7.0 */ export const throwError: MonadThrow4['throwError'] = left /** * @category type lambdas * @since 2.0.0 */ export const URI = 'StateReaderTaskEither' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind4 { readonly [URI]: StateReaderTaskEither } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor4 = { URI, map: _map } /** * Maps the `Right` value of this `StateReaderTaskEither` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, a: A): StateReaderTaskEither } = dual(2, as_(Functor)) /** * Maps the `Right` value of this `StateReaderTaskEither` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: StateReaderTaskEither) => StateReaderTaskEither = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed4 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply4 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Less strict version of [`apFirst`](#apfirst). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.12.0 */ export const apFirstW: ( second: StateReaderTaskEither ) => (first: StateReaderTaskEither) => StateReaderTaskEither = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * Less strict version of [`apSecond`](#apsecond). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.12.0 */ export const apSecondW: ( second: StateReaderTaskEither ) => (first: StateReaderTaskEither) => StateReaderTaskEither = apSecond as any /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative4 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain4 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.11.0 */ export const FromState: FromState4 = { URI, fromState } /** * Get the current state * * @category constructors * @since 2.0.0 */ export const get: () => StateReaderTaskEither = /*#__PURE__*/ get_(FromState) /** * Set the state * * @category constructors * @since 2.0.0 */ export const put: (s: S) => StateReaderTaskEither = /*#__PURE__*/ put_(FromState) /** * Modify the state by applying a function to the current state * * @category constructors * @since 2.0.0 */ export const modify: (f: Endomorphism) => StateReaderTaskEither = /*#__PURE__*/ modify_(FromState) /** * Get a value which depends on the current state * * @category constructors * @since 2.0.0 */ export const gets: (f: (s: S) => A) => StateReaderTaskEither = /*#__PURE__*/ gets_(FromState) /** * @category lifting * @since 2.11.0 */ export const fromStateK: , S, B>( f: (...a: A) => State ) => (...a: A) => StateReaderTaskEither = /*#__PURE__*/ fromStateK_(FromState) /** * Alias of `flatMapState`. * * @category legacy * @since 2.11.0 */ export const chainStateK: ( f: (a: A) => State ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = /*#__PURE__*/ chainStateK_( FromState, Chain ) /** * @category instances * @since 2.10.0 */ export const Monad: Monad4 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const MonadIO: MonadIO4 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO } /** * @category instances * @since 2.10.0 */ export const MonadTask: MonadTask4 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO, fromTask } /** * @category instances * @since 2.10.0 */ export const MonadThrow: MonadThrow4 = { URI, map: _map, ap: _ap, of, chain: flatMap, throwError } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither4 = { URI, fromEither } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO4 = { URI, fromIO } /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask4 = { URI, fromIO, fromTask } /** * @category instances * @since 2.11.0 */ export const FromReader: FromReader4 = { URI, fromReader } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { ( self: StateReaderTaskEither, f: (a: A) => StateReaderTaskEither ): StateReaderTaskEither (f: (a: A) => StateReaderTaskEither): ( self: StateReaderTaskEither ) => StateReaderTaskEither } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Either): StateReaderTaskEither< S, R1, E1 | E2, A > } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => IO<_>): StateReaderTaskEither } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapTask: { (f: (a: A) => Task<_>): (self: StateReaderTaskEither) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Task<_>): StateReaderTaskEither } = /*#__PURE__*/ dual(2, tapTask_(FromTask, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.16.0 */ export const tapReader: { (f: (a: A) => Reader): ( self: StateReaderTaskEither ) => StateReaderTaskEither (self: StateReaderTaskEither, f: (a: A) => Reader): StateReaderTaskEither< S, R1 & R2, E, A > } = /*#__PURE__*/ dual(2, tapReader_(FromReader, Chain)) /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor4 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * @category instances * @since 2.7.0 */ export const Alt: Alt4 = { URI, map: _map, alt: _alt } /** * Reads the current context. * * @category constructors * @since 2.11.0 */ export const ask: () => StateReaderTaskEither = /*#__PURE__*/ ask_(FromReader) /** * Projects a value from the global context in a `ReaderEither`. * * @category constructors * @since 2.11.0 */ export const asks: (f: (r: R) => A) => StateReaderTaskEither = /*#__PURE__*/ asks_(FromReader) /** * @category lifting * @since 2.11.0 */ export const fromReaderK: , R, B>( f: (...a: A) => Reader ) => (...a: A) => StateReaderTaskEither = /*#__PURE__*/ fromReaderK_(FromReader) /** * Alias of `flatMapReader`. * * @category legacy * @since 2.11.0 */ export const chainReaderK: ( f: (a: A) => Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapReader /** * Alias of `flatMapReader`. * * Less strict version of [`chainReaderK`](#chainReaderK). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainReaderKW: ( f: (a: A) => Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapReader /** * Alias of `tapReader`. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderK: ( f: (a: A) => Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = tapReader /** * Alias of `tapReader`. * * Less strict version of [`chainFirstReaderK`](#chainFirstReaderK). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.11.0 */ export const chainFirstReaderKW: ( f: (a: A) => Reader ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = tapReader /** * @category conversions * @since 2.0.0 */ export const fromOption: ( onNone: LazyArg ) => (fa: Option) => StateReaderTaskEither = /*#__PURE__*/ fromOption_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>( f: (...a: A) => Option ) => (...a: A) => StateReaderTaskEither = /*#__PURE__*/ fromOptionK_(FromEither) /** * Use `flatMapOption`. * * @category legacy * @since 2.10.0 */ export const chainOptionK: ( onNone: LazyArg ) => ( f: (a: A) => Option ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = /*#__PURE__*/ chainOptionK_( FromEither, Chain ) /** * Use `flatMapOption`. * * Less strict version of [`chainOptionK`](#chainoptionk). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category legacy * @since 2.13.2 */ export const chainOptionKW: ( onNone: LazyArg ) => ( f: (a: A) => Option ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = chainOptionK as any /** * Alias of `flatMapEither`. * * @category legacy * @since 2.4.0 */ export const chainEitherK: ( f: (a: A) => E.Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapEither /** * Alias of `flatMapEither`. * * Less strict version of [`chainEitherK`](#chaineitherk). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.6.1 */ export const chainEitherKW: ( f: (a: A) => Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapEither /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: ( f: (a: A) => E.Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = tapEither /** * Alias of `tapEither`. * * Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherKW: ( f: (a: A) => Either ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = tapEither /** * @category lifting * @since 2.4.4 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): ( a: A ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( b: B ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => StateReaderTaskEither } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category filtering * @since 2.4.4 */ export const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( mb: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E): ( ma: StateReaderTaskEither ) => StateReaderTaskEither } = /*#__PURE__*/ filterOrElse_(FromEither, Chain) /** * Less strict version of [`filterOrElse`](#filterorelse). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category filtering * @since 2.9.0 */ export const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: StateReaderTaskEither ) => StateReaderTaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( ma: StateReaderTaskEither ) => StateReaderTaskEither } = filterOrElse /** * @category lifting * @since 2.4.0 */ export const fromEitherK: , B>( f: (...a: A) => E.Either ) => (...a: A) => StateReaderTaskEither = /*#__PURE__*/ fromEitherK_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromIOK: , B>( f: (...a: A) => IO ) => (...a: A) => StateReaderTaskEither = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.10.0 */ export const chainIOK: ( f: (a: A) => IO ) => (first: StateReaderTaskEither) => StateReaderTaskEither = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: ( f: (a: A) => IO ) => (first: StateReaderTaskEither) => StateReaderTaskEither = tapIO /** * Alias of `flatMapTaskEither`. * * Less strict version of [`chainTaskEitherK`](#chaintaskeitherk). * * @category legacy * @since 2.6.1 */ export const chainTaskEitherKW: ( f: (a: A) => TaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapTaskEither /** * Alias of `flatMapTaskEither`. * * @category legacy * @since 2.4.0 */ export const chainTaskEitherK: ( f: (a: A) => TaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapTaskEither /** * Alias of `flatMapIOEither`. * * Less strict version of [`chainIOEitherK`](#chainioeitherk). * * @category legacy * @since 2.6.1 */ export const chainIOEitherKW: ( f: (a: A) => IOEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapIOEither /** * Alias of `flatMapIOEither`. * * @category legacy * @since 2.4.0 */ export const chainIOEitherK: ( f: (a: A) => IOEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMapIOEither /** * @category lifting * @since 2.10.0 */ export const fromTaskK: , B>( f: (...a: A) => Task ) => (...a: A) => StateReaderTaskEither = /*#__PURE__*/ fromTaskK_(FromTask) /** * Alias of `flatMapTask`. * * @category legacy * @since 2.10.0 */ export const chainTaskK: ( f: (a: A) => Task ) => (first: StateReaderTaskEither) => StateReaderTaskEither = flatMapTask /** * Alias of `tapTask`. * @category legacy * @since 2.10.0 */ export const chainFirstTaskK: ( f: (a: A) => Task ) => (first: StateReaderTaskEither) => StateReaderTaskEither = tapTask // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Run a computation in the `StateReaderTaskEither` monad, discarding the final state * * @since 2.8.0 */ export const evaluate: (s: S) => (ma: StateReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ST.evaluate(RTE.Functor) /** * Run a computation in the `StateReaderTaskEither` monad discarding the result * * @since 2.8.0 */ export const execute: (s: S) => (ma: StateReaderTaskEither) => ReaderTaskEither = /*#__PURE__*/ ST.execute(RTE.Functor) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @since 2.13.0 */ let_ as let } /** * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => StateReaderTaskEither ) => ( fa: StateReaderTaskEither ) => StateReaderTaskEither = bind as any // ------------------------------------------------------------------------------------- // pipeable sequence S // ------------------------------------------------------------------------------------- /** * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the environment types and the error types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: StateReaderTaskEither ) => ( fa: StateReaderTaskEither ) => StateReaderTaskEither = apS as any // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => StateReaderTaskEither) => (as: ReadonlyNonEmptyArray): StateReaderTaskEither> => (s) => (r) => () => _.tail(as).reduce, S]>>>( (acc, a, i) => acc.then((ebs) => _.isLeft(ebs) ? acc : f( i + 1, a )(ebs.right[1])(r)().then((eb) => { if (_.isLeft(eb)) { return eb } const [b, s] = eb.right ebs.right[0].push(b) ebs.right[1] = s return ebs }) ), f(0, _.head(as))(s)(r)().then(E.map(([b, s]) => [[b], s])) ) /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => StateReaderTaskEither ): ((as: ReadonlyArray) => StateReaderTaskEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : of(_.emptyReadonlyArray)) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => StateReaderTaskEither ) => (as: ReadonlyArray) => StateReaderTaskEither> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => StateReaderTaskEither ): ((as: ReadonlyArray) => StateReaderTaskEither>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: ( arr: ReadonlyArray> ) => StateReaderTaskEither> = /*#__PURE__*/ traverseArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = tap /** * Alias of `tap`. * * @category legacy * @since 2.8.0 */ export const chainFirstW: ( f: (a: A) => StateReaderTaskEither ) => (ma: StateReaderTaskEither) => StateReaderTaskEither = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `SRTE.Functor` instead of `SRTE.stateReaderTaskEither` * (where `SRTE` is from `import SRTE from 'fp-ts/StateReaderTaskEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const stateReaderTaskEither: Monad4 & Bifunctor4 & Alt4 & MonadTask4 & MonadThrow4 = { URI, map: _map, of, ap: _ap, chain: flatMap, bimap: _bimap, mapLeft: _mapLeft, alt: _alt, fromIO, fromTask, throwError } /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `SRTE.Functor` instead of `SRTE.stateReaderTaskEitherSeq` * (where `SRTE` is from `import SRTE from 'fp-ts/StateReaderTaskEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const stateReaderTaskEitherSeq: typeof stateReaderTaskEither = { URI, map: _map, of, ap: _ap, chain: flatMap, bimap: _bimap, mapLeft: _mapLeft, alt: _alt, fromIO, fromTask, throwError } /** * Use [`evaluate`](#evaluate) instead * * @category zone of death * @since 2.0.0 * @deprecated */ /* istanbul ignore next */ export const evalState: (ma: StateReaderTaskEither, s: S) => ReaderTaskEither = ( fsa, s ) => pipe( fsa(s), RTE.map(([a]) => a) ) /** * Use [`execute`](#execute) instead * * @category zone of death * @since 2.0.0 * @deprecated */ /* istanbul ignore next */ export const execState: (ma: StateReaderTaskEither, s: S) => ReaderTaskEither = ( fsa, s ) => pipe( fsa(s), RTE.map(([_, s]) => s) ) /** * @category zone of death * @since 2.0.0 * @deprecated */ /* istanbul ignore next */ export function run(ma: StateReaderTaskEither, s: S, r: R): Promise> { return ma(s)(r)() } ================================================ FILE: src/StateT.ts ================================================ /** * The state monad transformer. It can be used to add state to other monads. * * The `of` function leaves the state unchanged, while `chain` uses the final state of the first computation * as the initial state of the second. * * @since 2.0.0 */ import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C } from './Chain' import { pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C } from './Functor' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C } from './Monad' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C } from './Pointed' import { snd } from './ReadonlyTuple' import { State } from './State' /** * @category model * @since 2.0.0 */ export interface StateT { (s: S): HKT } /** * @category model * @since 2.0.0 */ export interface StateT1 { (s: S): Kind } /** * @category model * @since 2.0.0 */ export interface StateT2 { (s: S): Kind2 } /** * @category model * @since 2.0.0 */ export interface StateT3 { (s: S): Kind3 } /** * @since 2.10.0 */ export function of(F: Pointed3): (a: A) => StateT3 export function of(F: Pointed3C): (a: A) => StateT3 export function of(F: Pointed2): (a: A) => StateT2 export function of(F: Pointed2C): (a: A) => StateT2 export function of(F: Pointed1): (a: A) => StateT1 export function of(F: Pointed): (a: A) => StateT export function of(F: Pointed): (a: A) => StateT { return (a) => (s) => F.of([a, s]) } /** * @since 2.10.0 */ export function map( F: Functor3 ): (f: (a: A) => B) => (fa: StateT3) => StateT3 export function map( F: Functor3C ): (f: (a: A) => B) => (fa: StateT3) => StateT3 export function map( F: Functor2 ): (f: (a: A) => B) => (fa: StateT2) => StateT2 export function map( F: Functor2C ): (f: (a: A) => B) => (fa: StateT2) => StateT2 export function map( F: Functor1 ): (f: (a: A) => B) => (fa: StateT1) => StateT1 export function map(F: Functor): (f: (a: A) => B) => (fa: StateT) => StateT export function map(F: Functor): (f: (a: A) => B) => (fa: StateT) => StateT { return (f) => (fa) => (s) => F.map(fa(s), ([a, s1]) => [f(a), s1]) } /** * @since 2.10.0 */ export function ap( M: Chain3 ): (fa: StateT3) => (fab: StateT3 B>) => StateT3 export function ap( M: Chain3C ): (fa: StateT3) => (fab: StateT3 B>) => StateT3 export function ap( M: Chain2 ): (fa: StateT2) => (fab: StateT2 B>) => StateT2 export function ap( M: Chain2C ): (fa: StateT2) => (fab: StateT2 B>) => StateT2 export function ap( M: Chain1 ): (fa: StateT1) => (fab: StateT1 B>) => StateT1 export function ap( M: Chain ): (fa: StateT) => (fab: StateT B>) => StateT export function ap( M: Chain ): (fa: StateT) => (fab: StateT B>) => StateT { return (fa) => (fab) => (s) => M.chain(fab(s), ([f, s]) => M.map(fa(s), ([a, s]) => [f(a), s])) } /** * @since 2.10.0 */ export function chain( M: Chain3 ): (f: (a: A) => StateT3) => (ma: StateT3) => StateT3 export function chain( M: Chain3C ): (f: (a: A) => StateT3) => (ma: StateT3) => StateT3 export function chain( M: Chain2 ): (f: (a: A) => StateT2) => (ma: StateT2) => StateT2 export function chain( M: Chain2C ): (f: (a: A) => StateT2) => (ma: StateT2) => StateT2 export function chain( M: Chain1 ): (f: (a: A) => StateT1) => (ma: StateT1) => StateT1 export function chain( M: Chain ): (f: (a: A) => StateT) => (ma: StateT) => StateT export function chain( M: Chain ): (f: (a: A) => StateT) => (ma: StateT) => StateT { const flatMapM = flatMap(M) return (f) => (ma) => flatMapM(ma, f) } /** @internal */ export function flatMap( M: Chain3 ): (ma: StateT3, f: (a: A) => StateT3) => StateT /** @internal */ export function flatMap(M: Chain): (ma: StateT, f: (a: A) => StateT) => StateT /** @internal */ export function flatMap( M: Chain ): (ma: StateT, f: (a: A) => StateT) => StateT { return (ma, f) => (s) => M.chain(ma(s), ([a, s1]) => f(a)(s1)) } /** * @since 2.10.0 */ export function fromState(F: Pointed3): (sa: State) => StateT3 export function fromState(F: Pointed3C): (sa: State) => StateT3 export function fromState(F: Pointed2): (sa: State) => StateT2 export function fromState(F: Pointed2C): (sa: State) => StateT2 export function fromState(F: Pointed1): (sa: State) => StateT1 export function fromState(F: Pointed): (sa: State) => StateT export function fromState(F: Pointed): (sa: State) => StateT { return (sa) => (s) => F.of(sa(s)) } /** * @since 2.10.0 */ export function fromF(F: Functor3): (ma: Kind3) => StateT3 export function fromF( F: Functor3C ): (ma: Kind3) => StateT3 export function fromF(F: Functor2): (ma: Kind2) => StateT2 export function fromF(F: Functor2C): (ma: Kind2) => StateT2 export function fromF(F: Functor1): (ma: Kind) => StateT1 export function fromF(F: Functor): (ma: HKT) => StateT export function fromF(F: Functor): (ma: HKT) => StateT { return (ma) => (s) => F.map(ma, (a) => [a, s]) } /** * @since 2.10.0 */ export function evaluate( F: Functor3 ): (s: S) => (ma: StateT3) => Kind3 export function evaluate( F: Functor3C ): (s: S) => (ma: StateT3) => Kind3 export function evaluate( F: Functor2 ): (s: S) => (ma: StateT2) => Kind2 export function evaluate( F: Functor2C ): (s: S) => (ma: StateT2) => Kind2 export function evaluate(F: Functor1): (s: S) => (ma: StateT1) => Kind export function evaluate(F: Functor): (s: S) => (ma: StateT) => HKT export function evaluate(F: Functor): (s: S) => (ma: StateT) => HKT { return (s) => (ma) => F.map(ma(s), ([a]) => a) } /** * @since 2.10.0 */ export function execute( F: Functor3 ): (s: S) => (ma: StateT3) => Kind3 export function execute( F: Functor3C ): (s: S) => (ma: StateT3) => Kind3 export function execute(F: Functor2): (s: S) => (ma: StateT2) => Kind2 export function execute( F: Functor2C ): (s: S) => (ma: StateT2) => Kind2 export function execute(F: Functor1): (s: S) => (ma: StateT1) => Kind export function execute(F: Functor): (s: S) => (ma: StateT) => HKT export function execute(F: Functor): (s: S) => (ma: StateT) => HKT { return (s) => (ma) => F.map(ma(s), snd) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface StateM { readonly map: (fa: StateT, f: (a: A) => B) => StateT readonly of: (a: A) => StateT readonly ap: (fab: StateT B>, fa: StateT) => StateT readonly chain: (fa: StateT, f: (a: A) => StateT) => StateT readonly get: () => StateT readonly put: (s: S) => StateT readonly modify: (f: (s: S) => S) => StateT readonly gets: (f: (s: S) => A) => StateT readonly fromState: (fa: State) => StateT readonly fromM: (ma: HKT) => StateT readonly evalState: (ma: StateT, s: S) => HKT readonly execState: (ma: StateT, s: S) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface StateM1 { readonly map: (fa: StateT1, f: (a: A) => B) => StateT1 readonly of: (a: A) => StateT1 readonly ap: (fab: StateT1 B>, fa: StateT1) => StateT1 readonly chain: (fa: StateT1, f: (a: A) => StateT1) => StateT1 readonly get: () => StateT1 readonly put: (s: S) => StateT1 readonly modify: (f: (s: S) => S) => StateT1 readonly gets: (f: (s: S) => A) => StateT1 readonly fromState: (fa: State) => StateT1 readonly fromM: (ma: Kind) => StateT1 readonly evalState: (ma: StateT1, s: S) => Kind readonly execState: (ma: StateT1, s: S) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface StateM2 { readonly map: (fa: StateT2, f: (a: A) => B) => StateT2 readonly of: (a: A) => StateT2 readonly ap: (fab: StateT2 B>, fa: StateT2) => StateT2 readonly chain: (fa: StateT2, f: (a: A) => StateT2) => StateT2 readonly get: () => StateT2 readonly put: (s: S) => StateT2 readonly modify: (f: (s: S) => S) => StateT2 readonly gets: (f: (s: S) => A) => StateT2 readonly fromState: (fa: State) => StateT2 readonly fromM: (ma: Kind2) => StateT2 readonly evalState: (ma: StateT2, s: S) => Kind2 readonly execState: (ma: StateT2, s: S) => Kind2 } /** * @category zone of death * @since 2.5.4 * @deprecated */ export interface StateM2C { readonly map: (fa: StateT2, f: (a: A) => B) => StateT2 readonly of: (a: A) => StateT2 readonly ap: (fab: StateT2 B>, fa: StateT2) => StateT2 readonly chain: (fa: StateT2, f: (a: A) => StateT2) => StateT2 readonly get: () => StateT2 readonly put: (s: S) => StateT2 readonly modify: (f: (s: S) => S) => StateT2 readonly gets: (f: (s: S) => A) => StateT2 readonly fromState: (fa: State) => StateT2 readonly fromM: (ma: Kind2) => StateT2 readonly evalState: (ma: StateT2, s: S) => Kind2 readonly execState: (ma: StateT2, s: S) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface StateM3 { readonly map: (fa: StateT3, f: (a: A) => B) => StateT3 readonly of: (a: A) => StateT3 readonly ap: ( fab: StateT3 B>, fa: StateT3 ) => StateT3 readonly chain: ( fa: StateT3, f: (a: A) => StateT3 ) => StateT3 readonly get: () => StateT3 readonly put: (s: S) => StateT3 readonly modify: (f: (s: S) => S) => StateT3 readonly gets: (f: (s: S) => A) => StateT3 readonly fromState: (fa: State) => StateT3 readonly fromM: (ma: Kind3) => StateT3 readonly evalState: (ma: StateT3, s: S) => Kind3 readonly execState: (ma: StateT3, s: S) => Kind3 } /** * @category zone of death * @since 2.5.4 * @deprecated */ export interface StateM3C { readonly map: (fa: StateT3, f: (a: A) => B) => StateT3 readonly of: (a: A) => StateT3 readonly ap: (fab: StateT3 B>, fa: StateT3) => StateT3 readonly chain: ( fa: StateT3, f: (a: A) => StateT3 ) => StateT3 readonly get: () => StateT3 readonly put: (s: S) => StateT3 readonly modify: (f: (s: S) => S) => StateT3 readonly gets: (f: (s: S) => A) => StateT3 readonly fromState: (fa: State) => StateT3 readonly fromM: (ma: Kind3) => StateT3 readonly evalState: (ma: StateT3, s: S) => Kind3 readonly execState: (ma: StateT3, s: S) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export function getStateM(M: Monad3): StateM3 /** @deprecated */ export function getStateM(M: Monad3C): StateM3C /** @deprecated */ export function getStateM(M: Monad2): StateM2 /** @deprecated */ export function getStateM(M: Monad2C): StateM2C /** @deprecated */ export function getStateM(M: Monad1): StateM1 /** @deprecated */ export function getStateM(M: Monad): StateM /** @deprecated */ /* istanbul ignore next */ export function getStateM(M: Monad): StateM { const _ap = ap(M) const _map = map(M) const _chain = chain(M) const _evaluate = evaluate(M) const _execute = execute(M) return { map: (fa, f) => pipe(fa, _map(f)), ap: (fab, fa) => pipe(fab, _ap(fa)), of: of(M), chain: (ma, f) => pipe(ma, _chain(f)), get: () => (s) => M.of([s, s]), put: (s) => () => M.of([undefined, s]), modify: (f) => (s) => M.of([undefined, f(s)]), gets: (f) => (s) => M.of([f(s), s]), fromState: fromState(M), fromM: fromF(M), evalState: (fa, s) => pipe(fa, _evaluate(s)), execState: (fa, s) => pipe(fa, _execute(s)) } } ================================================ FILE: src/Store.ts ================================================ /** * @since 2.0.0 */ import { Comonad2 } from './Comonad' import { Endomorphism } from './Endomorphism' import { Extend2 } from './Extend' import { identity, pipe } from './function' import { flap as flap_, Functor as FunctorHKT, Functor1, Functor2, Functor2C, Functor3, Functor3C } from './Functor' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Store { readonly peek: (s: S) => A readonly pos: S } /** * Reposition the focus at the specified position * * @since 2.0.0 */ export function seek(s: S): (wa: Store) => Store { return (wa) => ({ peek: wa.peek, pos: s }) } /** * Reposition the focus at the specified position, which depends on the current position * * @since 2.0.0 */ export function seeks(f: Endomorphism): (wa: Store) => Store { return (wa) => ({ peek: wa.peek, pos: f(wa.pos) }) } /** * Extract a value from a position which depends on the current position * * @since 2.0.0 */ export function peeks(f: Endomorphism): (wa: Store) => A { return (wa) => wa.peek(f(wa.pos)) } /** * Extract a collection of values from positions which depend on the current position * * @since 2.0.0 */ export function experiment( F: Functor3 ): (f: (s: S) => Kind3) => (wa: Store) => Kind3 export function experiment( F: Functor3C ): (f: (s: S) => Kind3) => (wa: Store) => Kind3 export function experiment( F: Functor2 ): (f: (s: S) => Kind2) => (wa: Store) => Kind2 export function experiment( F: Functor2C ): (f: (s: S) => Kind2) => (wa: Store) => Kind2 export function experiment( F: Functor1 ): (f: (s: S) => Kind) => (wa: Store) => Kind export function experiment(F: FunctorHKT): (f: (s: S) => HKT) => (wa: Store) => HKT export function experiment(F: FunctorHKT): (f: (s: S) => HKT) => (wa: Store) => HKT { return (f) => (wa) => F.map(f(wa.pos), (s) => wa.peek(s)) } /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _extend: Extend2['extend'] = (wa, f) => pipe(wa, extend(f)) /** * @since 2.0.0 */ export const extend: (f: (wa: Store) => B) => (wa: Store) => Store = (f) => (wa) => ({ peek: (s) => f({ peek: wa.peek, pos: s }), pos: wa.pos }) /** * @category Extract * @since 2.6.2 */ export const extract: (wa: Store) => A = (wa) => wa.peek(wa.pos) /** * @since 2.0.0 */ export const duplicate: (wa: Store) => Store> = /*#__PURE__*/ extend(identity) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Store) => Store = (f) => (fa) => ({ peek: (s) => f(fa.peek(s)), pos: fa.pos }) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Store' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Store } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad2 = { URI, map: _map, extend: _extend, extract } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Comonad` instance, pass `S.Comonad` instead of `S.store` * (where `S` is from `import S from 'fp-ts/Store'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const store: Comonad2 = Comonad ================================================ FILE: src/Strong.ts ================================================ /** * The `Strong` class extends `Profunctor` with combinators for working with product types. * * `first` and `second` lift values in a `Profunctor` to act on the first and second components of a tuple, * respectively. * * Another way to think about Strong is to piggyback on the intuition of * inputs and outputs. Rewriting the type signature in this light then yields: * * ```purescript * first :: forall input output a. p input output -> p (Tuple input a) (Tuple output a) * second :: forall input output a. p input output -> p (Tuple a input) (Tuple a output) * ``` * * If we specialize the profunctor p to the function arrow, we get the following type * signatures, which may look a bit more familiar: * * ```purescript * first :: forall input output a. (input -> output) -> (Tuple input a) -> (Tuple output a) * second :: forall input output a. (input -> output) -> (Tuple a input) -> (Tuple a output) * ``` * * So, when the `profunctor` is `Function` application, `first` essentially applies your function * to the first element of a tuple, and `second` applies it to the second element (same as `map` would do). * * Adapted from https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Strong.purs * * @since 2.0.0 */ import { Category, Category2, Category3, Category4 } from './Category' import { identity } from './function' import { HKT2, Kind2, Kind3, Kind4, URIS2, URIS3, URIS4 } from './HKT' import { Profunctor, Profunctor2, Profunctor3, Profunctor4 } from './Profunctor' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Strong extends Profunctor { readonly first: (pab: HKT2) => HKT2 readonly second: (pab: HKT2) => HKT2 } /** * @category model * @since 2.0.0 */ export interface Strong2 extends Profunctor2 { readonly first: (pab: Kind2) => Kind2 readonly second: (pab: Kind2) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Strong3 extends Profunctor3 { readonly first: (pab: Kind3) => Kind3 readonly second: (pab: Kind3) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Strong4 extends Profunctor4 { readonly first: (pab: Kind4) => Kind4 readonly second: (pab: Kind4) => Kind4 } /** * Compose a value acting on a tuple from two values, each acting on one of the components of the tuple. * * Specializing `split` to function application would look like this: * * ```purescript * split :: forall a b c d. (a -> b) -> (c -> d) -> (Tuple a c) -> (Tuple b d) * ``` * * We take two functions, `f` and `g`, and we transform them into a single function which takes a tuple and maps `f` * over the first element and `g` over the second. Just like `bi-map` would do for the `bi-functor` instance of tuple. * * @since 2.10.0 */ export function split( S: Strong4, C: Category4 ): (pab: Kind4, pcd: Kind4) => Kind4 export function split( S: Strong3, C: Category3 ): (pab: Kind3, pcd: Kind3) => Kind3 export function split( S: Strong2, C: Category2 ): (pab: Kind2, pcd: Kind2) => Kind2 export function split( S: Strong, C: Category ): (pab: HKT2, pcd: HKT2) => HKT2 export function split( S: Strong, C: Category ): (pab: HKT2, pcd: HKT2) => HKT2 { return (pab: HKT2, pcd: HKT2) => C.compose(S.second(pcd), S.first(pab)) } /** * Compose a value which introduces a tuple from two values, each introducing one side of the tuple. * * This combinator is useful when assembling values from smaller components, because it provides a way to support two * different types of output. * * Specializing `fanOut` to function application would look like this: * * ```purescript * fanOut :: forall a b c. (a -> b) -> (a -> c) -> (a -> (Tuple b c)) * ``` * * We take two functions, `f` and `g`, with the same parameter type and we transform them into a single function which * takes one parameter and returns a tuple of the results of running `f` and `g` on the parameter, respectively. This * allows us to run two parallel computations on the same input and return both results in a tuple. * * @since 2.10.0 */ export function fanOut( S: Strong4, C: Category4 ): (pab: Kind4, pac: Kind4) => Kind4 export function fanOut( S: Strong3, C: Category3 ): (pab: Kind3, pac: Kind3) => Kind3 export function fanOut( S: Strong2, C: Category2 ): (pab: Kind2, pac: Kind2) => Kind2 export function fanOut( S: Strong, C: Category ): (pab: HKT2, pac: HKT2) => HKT2 export function fanOut( S: Strong, C: Category ): (pab: HKT2, pac: HKT2) => HKT2 { const splitSC = split(S, C) return (pab: HKT2, pac: HKT2): HKT2 => C.compose( splitSC(pab, pac), S.promap(C.id(), identity, (a) => [a, a]) ) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`split`](#split) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function splitStrong( F: Category4 & Strong4 ): (pab: Kind4, pcd: Kind4) => Kind4 /** @deprecated */ export function splitStrong( F: Category3 & Strong3 ): (pab: Kind3, pcd: Kind3) => Kind3 /** @deprecated */ export function splitStrong( F: Category2 & Strong2 ): (pab: Kind2, pcd: Kind2) => Kind2 /** @deprecated */ export function splitStrong( F: Category & Strong ): (pab: HKT2, pcd: HKT2) => HKT2 export function splitStrong( F: Category & Strong ): (pab: HKT2, pcd: HKT2) => HKT2 { return split(F, F) } /** * Use [`fanOut`](#fanout) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function fanout( F: Category4 & Strong4 ): (pab: Kind4, pac: Kind4) => Kind4 /** @deprecated */ export function fanout( F: Category3 & Strong3 ): (pab: Kind3, pac: Kind3) => Kind3 /** @deprecated */ export function fanout( F: Category2 & Strong2 ): (pab: Kind2, pac: Kind2) => Kind2 /** @deprecated */ export function fanout( F: Category & Strong ): (pab: HKT2, pac: HKT2) => HKT2 export function fanout( F: Category & Strong ): (pab: HKT2, pac: HKT2) => HKT2 { return fanOut(F, F) } ================================================ FILE: src/Task.ts ================================================ /** * ```ts * interface Task { * (): Promise * } * ``` * * `Task` represents an asynchronous computation that yields a value of type `A` and **never fails**. * If you want to represent an asynchronous computation that may fail, please see `TaskEither`. * * @since 2.0.0 */ import { Applicative1, getApplicativeMonoid } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import * as chainable from './Chain' import { FromIO1, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { FromTask1 } from './FromTask' import { dual, identity, pipe } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import * as _ from './internal' import { IO } from './IO' import { Monad1 } from './Monad' import { MonadIO1 } from './MonadIO' import { MonadTask1 } from './MonadTask' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Pointed1 } from './Pointed' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Task { (): Promise } // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.0.0 */ export const fromIO: (fa: IO) => Task = (ma) => () => Promise.resolve().then(ma) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Creates a task that will complete after a time delay * * @example * import { sequenceT } from 'fp-ts/Apply' * import * as T from 'fp-ts/Task' * import { takeRight } from 'fp-ts/Array' * * async function test() { * const log: Array = [] * const append = (message: string): T.Task => * T.fromIO(() => { * log.push(message) * }) * const fa = append('a') * const fb = T.delay(20)(append('b')) * const fc = T.delay(10)(append('c')) * const fd = append('d') * await sequenceT(T.ApplyPar)(fa, fb, fc, fd)() * assert.deepStrictEqual(takeRight(2)(log), ['c', 'b']) * } * * test() * * @since 2.0.0 */ export function delay(millis: number): (ma: Task) => Task { return (ma) => () => new Promise((resolve) => { setTimeout(() => { Promise.resolve().then(ma).then(resolve) }, millis) }) } const _map: Functor1['map'] = (fa, f) => pipe(fa, map(f)) const _apPar: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _apSeq: Apply1['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Task) => Task = (f) => (fa) => () => Promise.resolve().then(fa).then(f) /** * @since 2.0.0 */ export const ap: (fa: Task) => (fab: Task<(a: A) => B>) => Task = (fa) => (fab) => () => Promise.all([Promise.resolve().then(fab), Promise.resolve().then(fa)]).then(([f, a]) => f(a)) /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => Task = (a) => () => Promise.resolve(a) /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => Task): (ma: Task) => Task (ma: Task, f: (a: A) => Task): Task } = /*#__PURE__*/ dual( 2, (ma: Task, f: (a: A) => Task): Task => () => Promise.resolve() .then(ma) .then((a) => f(a)()) ) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: Task>) => Task = /*#__PURE__*/ flatMap(identity) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Task' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Task } } /** * Monoid returning the first completed task. * * Note: uses `Promise.race` internally. * * @example * import * as T from 'fp-ts/Task' * * async function test() { * const S = T.getRaceMonoid() * const fa = T.delay(20)(T.of('a')) * const fb = T.delay(10)(T.of('b')) * assert.deepStrictEqual(await S.concat(fa, fb)(), 'b') * } * * test() * * @category instances * @since 2.0.0 */ export function getRaceMonoid(): Monoid> { return { concat: (x, y) => () => Promise.race([Promise.resolve().then(x), Promise.resolve().then(y)]), empty: never } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Maps the value to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): <_>(self: Task<_>) => Task <_, A>(self: Task<_>, a: A): Task } = dual(2, as_(Functor)) /** * Maps the value to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: <_>(self: Task<_>) => Task = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplyPar: Apply1 = { URI, map: _map, ap: _apPar } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(ApplyPar) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(ApplyPar) /** * Runs computations in parallel. * * @category instances * @since 2.7.0 */ export const ApplicativePar: Applicative1 = { URI, map: _map, ap: _apPar, of } /** * Runs computations sequentially. * * @category instances * @since 2.10.0 */ export const ApplySeq: Apply1 = { URI, map: _map, ap: _apSeq } /** * Runs computations sequentially. * * @category instances * @since 2.7.0 */ export const ApplicativeSeq: Applicative1 = { URI, map: _map, ap: _apSeq, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain1 = { URI, map: _map, ap: _apPar, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const Monad: Monad1 = { URI, map: _map, of, ap: _apPar, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const MonadIO: MonadIO1 = { URI, map: _map, of, ap: _apPar, chain: flatMap, fromIO } /** * @category zone of death * @since 2.7.0 * @deprecated */ export const fromTask: (fa: Task) => Task = identity /** * @category instances * @since 2.10.0 */ export const MonadTask: MonadTask1 = { URI, map: _map, of, ap: _apPar, chain: flatMap, fromIO, fromTask } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO1 = { URI, fromIO } /** @internal */ interface TaskTypeLambda extends _.TypeLambda { readonly type: Task } /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** @internal */ const _FromIO: _.FromIO = { fromIO: FromIO.fromIO } /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: Task) => Task (self: Task, f: (a: A) => IO): Task } = _.flatMapIO(_FromIO, _FlatMap) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: Task, f: (a: A) => Task<_>): Task (f: (a: A) => Task<_>): (self: Task) => Task } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as T from 'fp-ts/Task' * import * as Console from 'fp-ts/Console' * * // Will produce `Hello, fp-ts` to the stdout * const effect = pipe( * T.of('fp-ts'), * T.tapIO((value) => Console.log(`Hello, ${value}`)), * ) * * async function test() { * assert.deepStrictEqual(await effect(), 'fp-ts') * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: Task) => Task (self: Task, f: (a: A) => IO<_>): Task } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * @category lifting * @since 2.4.0 */ export const fromIOK: , B>(f: (...a: A) => IO) => (...a: A) => Task = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.4.0 */ export const chainIOK: (f: (a: A) => IO) => (first: Task) => Task = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: (f: (a: A) => IO) => (first: Task) => Task = tapIO /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask1 = { URI, fromIO, fromTask } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * A `Task` that never completes. * * @since 2.0.0 */ export const never: Task = () => new Promise((_) => undefined) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: Task<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(ApplyPar) /** * @since 2.11.0 */ export const ApT: Task = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (f: (index: number, a: A) => Task) => (as: ReadonlyNonEmptyArray): Task> => () => Promise.all(as.map((a, i) => Promise.resolve().then(() => f(i, a)()))) as any /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => Task ): ((as: ReadonlyArray) => Task>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = (f: (index: number, a: A) => Task) => (as: ReadonlyNonEmptyArray): Task> => () => _.tail(as).reduce>>( (acc, a, i) => acc.then((bs) => Promise.resolve() .then(f(i + 1, a)) .then((b) => { bs.push(b) return bs }) ), Promise.resolve() .then(f(0, _.head(as))) .then(_.singleton) ) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = ( f: (index: number, a: A) => Task ): ((as: ReadonlyArray) => Task>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => Task ) => (as: ReadonlyArray) => Task> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = (f: (a: A) => Task): ((as: ReadonlyArray) => Task>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => Task> = /*#__PURE__*/ traverseArray(identity) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => Task ) => (as: ReadonlyArray) => Task> = traverseReadonlyArrayWithIndexSeq /** * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArray = (f: (a: A) => Task): ((as: ReadonlyArray) => Task>) => traverseReadonlyArrayWithIndexSeq((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const sequenceSeqArray: (arr: ReadonlyArray>) => Task> = /*#__PURE__*/ traverseSeqArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Task) => (ma: Task) => Task = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => Task) => (first: Task) => Task = tap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.task` * (where `T` is from `import T from 'fp-ts/Task'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const task: Monad1 & MonadTask1 = { URI, map: _map, of, ap: _apPar, chain: flatMap, fromIO, fromTask } /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.taskSeq` * (where `T` is from `import T from 'fp-ts/Task'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const taskSeq: Monad1 & MonadTask1 = { URI, map: _map, of, ap: _apSeq, chain: flatMap, fromIO, fromTask } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(ApplySeq) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * Lift a monoid into 'Task', the inner values are concatenated using the provided `Monoid`. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(ApplicativeSeq) ================================================ FILE: src/TaskEither.ts ================================================ /** * ```ts * interface TaskEither extends Task> {} * ``` * * `TaskEither` represents an asynchronous computation that either yields a value of type `A` or fails yielding an * error of type `E`. If you want to represent an asynchronous computation that never fails, please see `Task`. * * @since 2.0.0 */ import { Alt2, Alt2C } from './Alt' import { Applicative2, Applicative2C, getApplicativeMonoid } from './Applicative' import { ap as ap_, apFirst as apFirst_, Apply1, Apply2, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply' import { Bifunctor2 } from './Bifunctor' import * as chainable from './Chain' import { compact as compact_, Compactable2C, separate as separate_ } from './Compactable' import * as E from './Either' import * as ET from './EitherT' import { filter as filter_, Filterable2C, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable' import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, FromEither2, fromEitherK as fromEitherK_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_, tapEither as tapEither_ } from './FromEither' import { FromIO2, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { FromTask2, fromTaskK as fromTaskK_, tapTask as tapTask_ } from './FromTask' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor2, let as let__ } from './Functor' import * as _ from './internal' import { IO } from './IO' import { IOEither } from './IOEither' import { Monad2, Monad2C } from './Monad' import { MonadIO2 } from './MonadIO' import { MonadTask2, MonadTask2C } from './MonadTask' import { MonadThrow2, MonadThrow2C } from './MonadThrow' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { Pointed2 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import * as T from './Task' import { TaskOption } from './TaskOption' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- import Either = E.Either import Task = T.Task /** * @category model * @since 2.0.0 */ export interface TaskEither extends Task> {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export const left: (e: E) => TaskEither = /*#__PURE__*/ ET.left(T.Pointed) /** * @category constructors * @since 2.0.0 */ export const right: (a: A) => TaskEither = /*#__PURE__*/ ET.right(T.Pointed) /** * @category constructors * @since 2.0.0 */ export const rightTask: (ma: Task) => TaskEither = /*#__PURE__*/ ET.rightF(T.Functor) /** * @category constructors * @since 2.0.0 */ export const leftTask: (me: Task) => TaskEither = /*#__PURE__*/ ET.leftF(T.Functor) /** * @category constructors * @since 2.0.0 */ export const rightIO: (ma: IO) => TaskEither = /*#__PURE__*/ flow(T.fromIO, rightTask) /** * @category constructors * @since 2.0.0 */ export const leftIO: (me: IO) => TaskEither = /*#__PURE__*/ flow(T.fromIO, leftTask) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.7.0 */ export const fromIO: (fa: IO) => TaskEither = rightIO /** * @category conversions * @since 2.7.0 */ export const fromTask: (fa: Task) => TaskEither = rightTask /** * @category conversions * @since 2.0.0 */ export const fromEither: (fa: Either) => TaskEither = T.of /** * @category conversions * @since 2.0.0 */ export const fromIOEither: (fa: IOEither) => TaskEither = T.fromIO /** * @category conversions * @since 2.11.0 */ export const fromTaskOption: (onNone: LazyArg) => (fa: TaskOption) => TaskEither = (onNone) => T.map(E.fromOption(onNone)) /** * @category pattern matching * @since 2.10.0 */ export const match: (onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: TaskEither) => Task = /*#__PURE__*/ ET.match(T.Functor) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW: (onLeft: (e: E) => B, onRight: (a: A) => C) => (ma: TaskEither) => Task = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`). * * @category pattern matching * @since 2.10.0 */ export const matchE: ( onLeft: (e: E) => Task, onRight: (a: A) => Task ) => (ma: TaskEither) => Task = /*#__PURE__*/ ET.matchE(T.Monad) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.0.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchEW: ( onLeft: (e: E) => Task, onRight: (a: A) => Task ) => (ma: TaskEither) => Task = matchE as any /** * Alias of [`matchEW`](#matchew). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchEW /** * @category error handling * @since 2.0.0 */ export const getOrElse: (onLeft: (e: E) => Task) => (ma: TaskEither) => Task = /*#__PURE__*/ ET.getOrElse(T.Monad) /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.6.0 */ export const getOrElseW: (onLeft: (e: E) => Task) => (ma: TaskEither) => Task = getOrElse as any /** * Transforms a `Promise` that may reject to a `Promise` that never rejects and returns an `Either` instead. * * See also [`tryCatchK`](#trycatchk). * * @example * import { left, right } from 'fp-ts/Either' * import { tryCatch } from 'fp-ts/TaskEither' * * tryCatch(() => Promise.resolve(1), String)().then(result => { * assert.deepStrictEqual(result, right(1)) * }) * tryCatch(() => Promise.reject('error'), String)().then(result => { * assert.deepStrictEqual(result, left('error')) * }) * * @category interop * @since 2.0.0 */ export const tryCatch = (f: LazyArg>, onRejected: (reason: unknown) => E): TaskEither => async () => { try { return await f().then(_.right) } catch (reason) { return _.left(onRejected(reason)) } } /** * Converts a function returning a `Promise` to one returning a `TaskEither`. * * @category interop * @since 2.5.0 */ export const tryCatchK = , B>( f: (...a: A) => Promise, onRejected: (reason: unknown) => E ): ((...a: A) => TaskEither) => (...a) => tryCatch(() => f(...a), onRejected) /** * @category conversions * @since 2.10.0 */ export const toUnion: (fa: TaskEither) => Task = /*#__PURE__*/ ET.toUnion(T.Functor) /** * @category conversions * @since 2.12.0 */ export const fromNullable: (e: E) => (a: A) => TaskEither> = /*#__PURE__*/ ET.fromNullable( T.Pointed ) /** * Use `liftNullable`. * * @category legacy * @since 2.12.0 */ export const fromNullableK: ( e: E ) => , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => TaskEither> = /*#__PURE__*/ ET.fromNullableK(T.Pointed) /** * Use `flatMapNullable`. * * @category legacy * @since 2.12.0 */ export const chainNullableK: ( e: E ) => (f: (a: A) => B | null | undefined) => (ma: TaskEither) => TaskEither> = /*#__PURE__*/ ET.chainNullableK(T.Monad) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Returns `ma` if is a `Right` or the value returned by `onLeft` otherwise. * * See also [alt](#alt). * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as TE from 'fp-ts/TaskEither' * * async function test() { * const errorHandler = TE.orElse((error: string) => TE.right(`recovering from ${error}...`)) * assert.deepStrictEqual(await pipe(TE.right('ok'), errorHandler)(), E.right('ok')) * assert.deepStrictEqual(await pipe(TE.left('ko'), errorHandler)(), E.right('recovering from ko...')) * } * * test() * * @category error handling * @since 2.0.0 */ export const orElse: (onLeft: (e: E1) => TaskEither) => (ma: TaskEither) => TaskEither = /*#__PURE__*/ ET.orElse(T.Monad) /** * Less strict version of [`orElse`](#orelse). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category error handling * @since 2.10.0 */ export const orElseW: ( onLeft: (e: E1) => TaskEither ) => (ma: TaskEither) => TaskEither = orElse as any /** * Returns an effect that effectfully "peeks" at the failure of this effect. * * @category error handling * @since 2.15.0 */ export const tapError: { (onLeft: (e: E1) => TaskEither): (self: TaskEither) => TaskEither (self: TaskEither, onLeft: (e: E1) => TaskEither): TaskEither } = /*#__PURE__*/ dual(2, ET.tapError(T.Monad)) /** * @category error handling * @since 2.12.0 */ export const orElseFirstIOK: (onLeft: (e: E) => IO) => (ma: TaskEither) => TaskEither = ( onLeft ) => tapError(fromIOK(onLeft)) /** * @category error handling * @since 2.12.0 */ export const orElseFirstTaskK: (onLeft: (e: E) => Task) => (ma: TaskEither) => TaskEither = ( onLeft ) => tapError(fromTaskK(onLeft)) /** * @category error handling * @since 2.11.0 */ export const orLeft: (onLeft: (e: E1) => Task) => (fa: TaskEither) => TaskEither = /*#__PURE__*/ ET.orLeft(T.Monad) /** * @since 2.0.0 */ export const swap: (ma: TaskEither) => TaskEither = /*#__PURE__*/ ET.swap(T.Functor) /** * @category lifting * @since 2.11.0 */ export const fromTaskOptionK = ( onNone: LazyArg ): (, B>(f: (...a: A) => TaskOption) => (...a: A) => TaskEither) => { const from = fromTaskOption(onNone) return (f) => flow(f, from) } /** * Use `flatMapTaskOption`. * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category legacy * @since 2.12.3 */ export const chainTaskOptionKW = (onNone: LazyArg) => (f: (a: A) => TaskOption) => (ma: TaskEither): TaskEither => flatMap(ma, fromTaskOptionK(onNone)(f)) /** * Use `flatMapTaskOption`. * * @category legacy * @since 2.11.0 */ export const chainTaskOptionK: ( onNone: LazyArg ) => (f: (a: A) => TaskOption) => (ma: TaskEither) => TaskEither = chainTaskOptionKW /** * @category lifting * @since 2.4.0 */ export const fromIOEitherK = , B>( f: (...a: A) => IOEither ): ((...a: A) => TaskEither) => flow(f, fromIOEither) const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) const _apPar: Apply2['ap'] = (fab, fa) => pipe(fab, ap(fa)) const _apSeq: Apply2['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /* istanbul ignore next */ const _alt: Alt2['alt'] = (fa, that) => pipe(fa, alt(that)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: TaskEither) => TaskEither = /*#__PURE__*/ ET.map( T.Functor ) /** * Returns a `TaskEither` whose failure and success channels have been mapped by the specified pair of functions, `f` and `g`. * * @example * import * as TaskEither from 'fp-ts/TaskEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * const g = (n: number) => n * 2 * * async function test() { * assert.deepStrictEqual(await TaskEither.mapBoth(TaskEither.right(1), f, g)(), Either.right(2)) * assert.deepStrictEqual(await TaskEither.mapBoth(TaskEither.left('err'), f, g)(), Either.left(new Error('err'))) * } * * test() * * @category error handling * @since 2.16.0 */ export const mapBoth: { (f: (e: E) => G, g: (a: A) => B): (self: TaskEither) => TaskEither (self: TaskEither, f: (e: E) => G, g: (a: A) => B): TaskEither } = /*#__PURE__*/ dual(3, ET.mapBoth(T.Functor)) /** * Alias of `mapBoth`. * * @category legacy * @since 2.0.0 */ export const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: TaskEither) => TaskEither = mapBoth /** * Returns a `TaskEither` with its error channel mapped using the specified function. * * @example * import * as TaskEither from 'fp-ts/TaskEither' * import * as Either from 'fp-ts/Either' * * const f = (s: string) => new Error(s) * * async function test() { * assert.deepStrictEqual(await TaskEither.mapError(TaskEither.right(1), f)(), Either.right(1)) * assert.deepStrictEqual(await TaskEither.mapError(TaskEither.left('err'), f)(), Either.left(new Error('err'))) * } * * test() * * @category error handling * @since 2.16.0 */ export const mapError: { (f: (e: E) => G): (self: TaskEither) => TaskEither (self: TaskEither, f: (e: E) => G): TaskEither } = /*#__PURE__*/ dual(2, ET.mapError(T.Functor)) /** * Alias of `mapError`. * * @category legacy * @since 2.0.0 */ export const mapLeft: (f: (e: E) => G) => (fa: TaskEither) => TaskEither = mapError /** * @since 2.0.0 */ export const ap: (fa: TaskEither) => (fab: TaskEither B>) => TaskEither = /*#__PURE__*/ ET.ap(T.ApplyPar) /** * Less strict version of [`ap`](#ap). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.8.0 */ export const apW: ( fa: TaskEither ) => (fab: TaskEither B>) => TaskEither = ap as any /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => TaskEither): (ma: TaskEither) => TaskEither (ma: TaskEither, f: (a: A) => TaskEither): TaskEither } = /*#__PURE__*/ dual(2, ET.flatMap(T.Monad)) /** * Less strict version of [`flatten`](#flatten). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category sequencing * @since 2.11.0 */ export const flattenW: (mma: TaskEither>) => TaskEither = /*#__PURE__*/ flatMap(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: TaskEither>) => TaskEither = flattenW /** * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to * types of kind `* -> *`. * * In case of `TaskEither` returns `fa` if is a `Right` or the value returned by `that` otherwise. * * See also [orElse](#orelse). * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as TE from 'fp-ts/TaskEither' * * async function test() { * assert.deepStrictEqual( * await pipe( * TE.right(1), * TE.alt(() => TE.right(2)) * )(), * E.right(1) * ) * assert.deepStrictEqual( * await pipe( * TE.left('a'), * TE.alt(() => TE.right(2)) * )(), * E.right(2) * ) * assert.deepStrictEqual( * await pipe( * TE.left('a'), * TE.alt(() => TE.left('b')) * )(), * E.left('b') * ) * } * * test() * * @category error handling * @since 2.0.0 */ export const alt: (that: LazyArg>) => (fa: TaskEither) => TaskEither = /*#__PURE__*/ ET.alt(T.Monad) /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the error and the return types will be merged. * * @category error handling * @since 2.9.0 */ export const altW: ( that: LazyArg> ) => (fa: TaskEither) => TaskEither = alt as any /** * @category constructors * @since 2.0.0 */ export const of: (a: A) => TaskEither = right /** * @since 2.7.0 */ export const throwError: MonadThrow2['throwError'] = left /** * @category type lambdas * @since 2.0.0 */ export const URI = 'TaskEither' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: TaskEither } } /** * The default [`ApplicativePar`](#applicativepar) instance returns the first error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as RA from 'fp-ts/ReadonlyArray' * import * as S from 'fp-ts/Semigroup' * import * as string from 'fp-ts/string' * import * as T from 'fp-ts/Task' * import * as TE from 'fp-ts/TaskEither' * * interface User { * readonly id: string * readonly name: string * } * * const remoteDatabase: ReadonlyArray = [ * { id: 'id1', name: 'John' }, * { id: 'id2', name: 'Mary' }, * { id: 'id3', name: 'Joey' } * ] * * const fetchUser = (id: string): TE.TaskEither => * pipe( * remoteDatabase, * RA.findFirst((user) => user.id === id), * TE.fromOption(() => `${id} not found`) * ) * * async function test() { * assert.deepStrictEqual( * await pipe(['id4', 'id5'], RA.traverse(TE.ApplicativePar)(fetchUser))(), * E.left('id4 not found') // <= first error * ) * * const Applicative = TE.getApplicativeTaskValidation( * T.ApplyPar, * pipe(string.Semigroup, S.intercalate(', ')) * ) * * assert.deepStrictEqual( * await pipe(['id4', 'id5'], RA.traverse(Applicative)(fetchUser))(), * E.left('id4 not found, id5 not found') // <= all errors * ) * } * * test() * * @category error handling * @since 2.7.0 */ export function getApplicativeTaskValidation(A: Apply1, S: Semigroup): Applicative2C { const ap = ap_(A, E.getApplicativeValidation(S)) return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => pipe(fab, ap(fa)), of } } /** * The default [`Alt`](#alt) instance returns the last error, if you want to * get all errors you need to provide a way to concatenate them via a `Semigroup`. * * See [`getAltValidation`](./Either.ts.html#getaltvalidation). * * @category error handling * @since 2.7.0 */ export function getAltTaskValidation(S: Semigroup): Alt2C { const alt = ET.altValidation(T.Monad, S) return { URI, _E: undefined as any, map: _map, alt: (fa, that) => pipe(fa, alt(that)) } } /** * @category filtering * @since 2.10.0 */ export const getCompactable = (M: Monoid): Compactable2C => { const C = E.getCompactable(M) return { URI, _E: undefined as any, compact: compact_(T.Functor, C), separate: separate_(T.Functor, C, E.Functor) } } /** * @category filtering * @since 2.1.0 */ export function getFilterable(M: Monoid): Filterable2C { const F = E.getFilterable(M) const C = getCompactable(M) const filter = filter_(T.Functor, F) const filterMap = filterMap_(T.Functor, F) const partition = partition_(T.Functor, F) const partitionMap = partitionMap_(T.Functor, F) return { URI, _E: undefined as any, map: _map, compact: C.compact, separate: C.separate, filter: (fa: TaskEither, predicate: Predicate) => pipe(fa, filter(predicate)), filterMap: (fa, f) => pipe(fa, filterMap(f)), partition: (fa: TaskEither, predicate: Predicate) => pipe(fa, partition(predicate)), partitionMap: (fa, f) => pipe(fa, partitionMap(f)) } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * Maps the `Right` value of this `TaskEither` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): (self: TaskEither) => TaskEither (self: TaskEither, a: A): TaskEither } = dual(2, as_(Functor)) /** * Maps the `Right` value of this `TaskEither` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: (self: TaskEither) => TaskEither = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplyPar: Apply2 = { URI, map: _map, ap: _apPar } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(ApplyPar) /** * Less strict version of [`apFirst`](#apfirst). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const apFirstW: ( second: TaskEither ) => (first: TaskEither) => TaskEither = apFirst as any /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(ApplyPar) /** * Less strict version of [`apSecond`](#apsecond). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const apSecondW: ( second: TaskEither ) => (first: TaskEither) => TaskEither = apSecond as any /** * Runs computations in parallel. * * @category instances * @since 2.7.0 */ export const ApplicativePar: Applicative2 = { URI, map: _map, ap: _apPar, of } /** * Runs computations sequentially. * * @category instances * @since 2.10.0 */ export const ApplySeq: Apply2 = { URI, map: _map, ap: _apSeq } /** * Runs computations sequentially. * * @category instances * @since 2.7.0 */ export const ApplicativeSeq: Applicative2 = { URI, map: _map, ap: _apSeq, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain2 = { URI, map: _map, ap: _apPar, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const Monad: Monad2 = { URI, map: _map, ap: _apPar, chain: flatMap, of } /** * @category instances * @since 2.10.0 */ export const MonadIO: MonadIO2 = { URI, map: _map, ap: _apPar, chain: flatMap, of, fromIO } /** * @category instances * @since 2.10.0 */ export const MonadTask: MonadTask2 = { URI, map: _map, ap: _apPar, chain: flatMap, of, fromIO, fromTask } /** * @category instances * @since 2.10.0 */ export const MonadThrow: MonadThrow2 = { URI, map: _map, ap: _apPar, chain: flatMap, of, throwError } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither2 = { URI, fromEither } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO2 = { URI, fromIO } /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask2 = { URI, fromIO, fromTask } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: TaskEither, f: (a: A) => TaskEither): TaskEither (f: (a: A) => TaskEither): (self: TaskEither) => TaskEither } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as E from 'fp-ts/Either' * import { pipe } from 'fp-ts/function' * import * as TE from 'fp-ts/TaskEither' * * const checkString = (value: string) => pipe( * TE.of(value), * TE.tapEither(() => value.length > 0 ? E.right('ok') : E.left('error')) * ) * * async function test() { * assert.deepStrictEqual(await checkString('')(), E.left('error')) * assert.deepStrictEqual(await checkString('fp-ts')(), E.right('fp-ts')) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => Either): TaskEither } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as TE from 'fp-ts/TaskEither' * import * as E from 'fp-ts/Either' * import * as Console from 'fp-ts/Console' * * * // Will produce `Hello, fp-ts` to the stdout * const effectA = TE.tapIO( * TE.of(1), * (value) => Console.log(`Hello, ${value}`) * ) * * // No output to the stdout * const effectB = pipe( * TE.left('error'), * TE.tapIO((value) => Console.log(`Hello, ${value}`)) * ) * * async function test() { * assert.deepStrictEqual(await effectA(), E.of(1)) * assert.deepStrictEqual(await effectB(), E.left('error')) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => IO<_>): TaskEither } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as TE from 'fp-ts/TaskEither' * import * as T from 'fp-ts/Task' * import * as E from 'fp-ts/Either' * * * const effect = TE.tapIO( * TE.of(1), * (value) => T.of(value + 1) * ) * * async function test() { * assert.deepStrictEqual(await effect(), E.of(1)) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapTask: { (f: (a: A) => Task<_>): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => Task<_>): TaskEither } = /*#__PURE__*/ dual(2, tapTask_(FromTask, Chain)) /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: mapBoth, mapLeft: mapError } /** * @category instances * @since 2.7.0 */ export const Alt: Alt2 = { URI, map: _map, alt: _alt } /** * @category conversions * @since 2.0.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => TaskEither = /*#__PURE__*/ fromOption_(FromEither) /** * Use `liftOption`. * * @category legacy * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => TaskEither = /*#__PURE__*/ fromOptionK_(FromEither) /** * Use `flatMapOption`. * * @category legacy * @since 2.10.0 */ export const chainOptionK: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: TaskEither) => TaskEither = /*#__PURE__*/ chainOptionK_( FromEither, Chain ) /** * Use `flatMapOption`. * * @category legacy * @since 2.13.2 */ export const chainOptionKW: ( onNone: LazyArg ) => (f: (a: A) => Option) => (ma: TaskEither) => TaskEither = chainOptionK as any /** @internal */ interface TaskEitherTypeLambda extends _.TypeLambda { readonly type: TaskEither } /** @internal */ const _FromEither: _.FromEither = { fromEither: FromEither.fromEither } /** * @category lifting * @since 2.15.0 */ export const liftNullable: , B, E>( f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E ) => (...a: A) => TaskEither> = /*#__PURE__*/ _.liftNullable(_FromEither) /** * @category lifting * @since 2.15.0 */ export const liftOption: , B, E>( f: (...a: A) => Option, onNone: (...a: A) => E ) => (...a: A) => TaskEither = /*#__PURE__*/ _.liftOption(_FromEither) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** @internal */ const _FromIO: _.FromIO = { fromIO: FromIO.fromIO } /** @internal */ const _FromTask: _.FromTask = { fromTask } /** * @category sequencing * @since 2.15.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: TaskEither ) => TaskEither> (self: TaskEither, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): TaskEither< E1 | E2, NonNullable > } = /*#__PURE__*/ _.flatMapNullable(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapOption: { (f: (a: A) => Option, onNone: (a: A) => E2): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => Option, onNone: (a: A) => E2): TaskEither } = /*#__PURE__*/ _.flatMapOption(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapEither: { (f: (a: A) => E.Either): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => E.Either): TaskEither } = /*#__PURE__*/ _.flatMapEither(_FromEither, _FlatMap) /** * @category sequencing * @since 2.15.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => IO): TaskEither } = /*#__PURE__*/ _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapTask: { (f: (a: A) => Task): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => Task): TaskEither } = /*#__PURE__*/ _.flatMapTask(_FromTask, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapIOEither: { (f: (a: A) => IOEither): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => IOEither): TaskEither } = /*#__PURE__*/ dual( 2, (self: TaskEither, f: (a: A) => IOEither): TaskEither => flatMap(self, fromIOEitherK(f)) ) /** * @category sequencing * @since 2.16.0 */ export const flatMapTaskOption: { (f: (a: A) => TaskOption, onNone: (a: A) => E2): (self: TaskEither) => TaskEither (self: TaskEither, f: (a: A) => TaskOption, onNone: (a: A) => E2): TaskEither } = /*#__PURE__*/ dual( 3, (self: TaskEither, f: (a: A) => TaskOption, onNone: (a: A) => E2): TaskEither => flatMap(self, (a) => fromTaskOption(() => onNone(a))(f(a))) ) /** * Alias of `flatMapEither`. * * @category legacy * @since 2.4.0 */ export const chainEitherK: (f: (a: A) => E.Either) => (ma: TaskEither) => TaskEither = flatMapEither /** * Alias of `flatMapEither`. * * @category legacy * @since 2.6.1 */ export const chainEitherKW: ( f: (a: A) => Either ) => (ma: TaskEither) => TaskEither = flatMapEither /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: (f: (a: A) => E.Either) => (ma: TaskEither) => TaskEither = tapEither /** * Alias of `tapEither`. * * Less strict version of [`chainFirstEitherK`](#chainfirsteitherk). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherKW: ( f: (a: A) => E.Either ) => (ma: TaskEither) => TaskEither = tapEither /** * @category lifting * @since 2.0.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (b: B) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (a: A) => TaskEither } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category filtering * @since 2.0.0 */ export const filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: TaskEither) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (mb: TaskEither) => TaskEither (predicate: Predicate, onFalse: (a: A) => E): (ma: TaskEither) => TaskEither } = /*#__PURE__*/ filterOrElse_(FromEither, Chain) /** * Less strict version of [`filterOrElse`](#filterorelse). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category filtering * @since 2.9.0 */ export const filterOrElseW: { (refinement: Refinement, onFalse: (a: A) => E2): ( ma: TaskEither ) => TaskEither (predicate: Predicate, onFalse: (a: A) => E2): ( mb: TaskEither ) => TaskEither (predicate: Predicate, onFalse: (a: A) => E2): (ma: TaskEither) => TaskEither } = filterOrElse /** * @category lifting * @since 2.4.0 */ export const fromEitherK: , B>( f: (...a: A) => E.Either ) => (...a: A) => TaskEither = /*#__PURE__*/ fromEitherK_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromIOK: , B>( f: (...a: A) => IO ) => (...a: A) => TaskEither = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.10.0 */ export const chainIOK: (f: (a: A) => IO) => (first: TaskEither) => TaskEither = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: (f: (a: A) => IO) => (first: TaskEither) => TaskEither = tapIO /** * @category lifting * @since 2.10.0 */ export const fromTaskK: , B>( f: (...a: A) => T.Task ) => (...a: A) => TaskEither = /*#__PURE__*/ fromTaskK_(FromTask) /** * Alias of `flatMapTask`. * * @category legacy * @since 2.10.0 */ export const chainTaskK: (f: (a: A) => T.Task) => (first: TaskEither) => TaskEither = flatMapTask /** * Alias of `tapTask`. * * @category legacy * @since 2.10.0 */ export const chainFirstTaskK: (f: (a: A) => T.Task) => (first: TaskEither) => TaskEither = tapTask /** * Alias of `flatMapIOEither`. * * Less strict version of [`chainIOEitherK`](#chainioeitherk). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category legacy * @since 2.6.1 */ export const chainIOEitherKW: ( f: (a: A) => IOEither ) => (ma: TaskEither) => TaskEither = flatMapIOEither /** * Alias of `flatMapIOEither`. * * @category legacy * @since 2.4.0 */ export const chainIOEitherK: (f: (a: A) => IOEither) => (ma: TaskEither) => TaskEither = flatMapIOEither // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Convert a node style callback function to one returning a `TaskEither` * * **Note**. If the function `f` admits multiple overloadings, `taskify` will pick last one. If you want a different * behaviour, add an explicit type annotation * * ```ts * // readFile admits multiple overloadings * * // const readFile: (a: string) => TaskEither * const readFile = taskify(fs.readFile) * * const readFile2: (filename: string, encoding: string) => TaskEither = taskify( * fs.readFile * ) * ``` * * @example * import { taskify } from 'fp-ts/TaskEither' * import * as fs from 'fs' * * // const stat: (a: string | Buffer) => TaskEither * const stat = taskify(fs.stat) * assert.strictEqual(stat.length, 0) * * @category interop * @since 2.0.0 */ export function taskify(f: (cb: (e: L | null | undefined, r?: R) => void) => void): () => TaskEither export function taskify( f: (a: A, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A) => TaskEither export function taskify( f: (a: A, b: B, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B) => TaskEither export function taskify( f: (a: A, b: B, c: C, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B, c: C) => TaskEither export function taskify( f: (a: A, b: B, c: C, d: D, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B, c: C, d: D) => TaskEither export function taskify( f: (a: A, b: B, c: C, d: D, e: E, cb: (e: L | null | undefined, r?: R) => void) => void ): (a: A, b: B, c: C, d: D, e: E) => TaskEither export function taskify(f: Function): () => TaskEither { return function () { const args = Array.prototype.slice.call(arguments) return () => new Promise((resolve) => { const cbResolver = (e: L, r: R) => (e != null ? resolve(_.left(e)) : resolve(_.right(r))) f.apply(null, args.concat(cbResolver)) }) } } /** * Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of * whether the body action throws (\*) or returns. * * (\*) i.e. returns a `Left` * * @since 2.0.0 */ export const bracket = ( acquire: TaskEither, use: (a: A) => TaskEither, release: (a: A, e: Either) => TaskEither ): TaskEither => bracketW(acquire, use, release) /** * Less strict version of [`bracket`](#bracket). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @since 2.12.0 */ export const bracketW: ( acquire: TaskEither, use: (a: A) => TaskEither, release: (a: A, e: E.Either) => TaskEither ) => TaskEither = (acquire, use, release) => flatMap(acquire, (a) => T.flatMap(use(a), (e) => flatMap(release(a, e), () => T.of(e)))) // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: TaskEither = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category do notation * @since 2.8.0 */ export const bindW: ( name: Exclude, f: (a: A) => TaskEither ) => (fa: TaskEither) => TaskEither = bind as any /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(ApplyPar) /** * Less strict version of [`apS`](#aps). * * The `W` suffix (short for **W**idening) means that the error types will be merged. * * @category do notation * @since 2.8.0 */ export const apSW: ( name: Exclude, fb: TaskEither ) => (fa: TaskEither) => TaskEither = apS as any /** * @since 2.11.0 */ export const ApT: TaskEither = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => TaskEither ): ((as: ReadonlyNonEmptyArray) => TaskEither>) => flow(T.traverseReadonlyNonEmptyArrayWithIndex(f), T.map(E.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => TaskEither ): ((as: ReadonlyArray) => TaskEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = (f: (index: number, a: A) => TaskEither) => (as: ReadonlyNonEmptyArray): TaskEither> => () => _.tail(as).reduce>>>( (acc, a, i) => acc.then((ebs) => _.isLeft(ebs) ? acc : f(i + 1, a)().then((eb) => { if (_.isLeft(eb)) { return eb } ebs.right.push(eb.right) return ebs }) ), f(0, _.head(as))().then(E.map(_.singleton)) ) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = ( f: (index: number, a: A) => TaskEither ): ((as: ReadonlyArray) => TaskEither>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => TaskEither ) => (as: ReadonlyArray) => TaskEither> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.9.0 */ export const traverseArray = ( f: (a: A) => TaskEither ): ((as: ReadonlyArray) => TaskEither>) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.9.0 */ export const sequenceArray: (arr: ReadonlyArray>) => TaskEither> = /*#__PURE__*/ traverseArray(identity) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => TaskEither ) => (as: ReadonlyArray) => TaskEither> = traverseReadonlyArrayWithIndexSeq /** * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const traverseSeqArray = ( f: (a: A) => TaskEither ): ((as: ReadonlyArray) => TaskEither>) => traverseReadonlyArrayWithIndexSeq((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. * * @category traversing * @since 2.9.0 */ export const sequenceSeqArray: (arr: ReadonlyArray>) => TaskEither> = /*#__PURE__*/ traverseSeqArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => TaskEither) => (ma: TaskEither) => TaskEither = flatMap /** * Alias of `flatMap`. * * @category legacy * @since 2.6.0 */ export const chainW: ( f: (a: A) => TaskEither ) => (ma: TaskEither) => TaskEither = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.0.0 */ export const chainFirst: (f: (a: A) => TaskEither) => (ma: TaskEither) => TaskEither = tap /** * Alias of `tap`. * * @category legacy * @since 2.8.0 */ export const chainFirstW: ( f: (a: A) => TaskEither ) => (ma: TaskEither) => TaskEither = tap /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirst: (onLeft: (e: E) => TaskEither) => (ma: TaskEither) => TaskEither = tapError /** * Alias of `tapError`. * * @category legacy * @since 2.11.0 */ export const orElseFirstW: ( onLeft: (e: E1) => TaskEither ) => (ma: TaskEither) => TaskEither = tapError // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `TE.Functor` instead of `TE.taskEither` * (where `TE` is from `import TE from 'fp-ts/TaskEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const taskEither: Monad2 & Bifunctor2 & Alt2 & MonadTask2 & MonadThrow2 = { URI, bimap: mapBoth, mapLeft: mapError, map: _map, of, ap: _apPar, chain: flatMap, alt: _alt, fromIO, fromTask, throwError } /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `TE.Functor` instead of `TE.taskEitherSeq` * (where `TE` is from `import TE from 'fp-ts/TaskEither'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const taskEitherSeq: typeof taskEither = { URI, bimap: mapBoth, mapLeft: mapError, map: _map, of, ap: _apSeq, chain: flatMap, alt: _alt, fromIO, fromTask, throwError } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplySemigroup: (S: Semigroup) => Semigroup> = /*#__PURE__*/ getApplySemigroup_(ApplySeq) /** * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getApplyMonoid: (M: Monoid) => Monoid> = /*#__PURE__*/ getApplicativeMonoid(ApplicativeSeq) /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const getSemigroup = (S: Semigroup): Semigroup> => getApplySemigroup_(T.ApplySeq)(E.getSemigroup(S)) /** * Use [`getApplicativeTaskValidation`](#getapplicativetaskvalidation) and [`getAltTaskValidation`](#getalttaskvalidation) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getTaskValidation( SE: Semigroup ): Monad2C & Bifunctor2 & Alt2C & MonadTask2C & MonadThrow2C { const applicativeTaskValidation = getApplicativeTaskValidation(T.ApplicativePar, SE) const altTaskValidation = getAltTaskValidation(SE) return { URI, _E: undefined as any, map: _map, ap: applicativeTaskValidation.ap, of, chain: flatMap, bimap: mapBoth, mapLeft: mapError, alt: altTaskValidation.alt, fromIO, fromTask, throwError } } ================================================ FILE: src/TaskOption.ts ================================================ /** * @since 2.10.0 */ import { Alt1 } from './Alt' import { Alternative1 } from './Alternative' import { Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import * as chainable from './Chain' import { compact as compact_, Compactable1, separate as separate_ } from './Compactable' import { Either } from './Either' import { filter as filter_, Filterable1, filterMap as filterMap_, partition as partition_, partitionMap as partitionMap_ } from './Filterable' import { chainEitherK as chainEitherK_, FromEither1, fromEitherK as fromEitherK_, tapEither as tapEither_ } from './FromEither' import { FromIO1, fromIOK as fromIOK_, tapIO as tapIO_ } from './FromIO' import { FromTask1, fromTaskK as fromTaskK_, tapTask as tapTask_ } from './FromTask' import { dual, flow, identity, LazyArg, pipe, SK } from './function' import { as as as_, asUnit as asUnit_, bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import * as _ from './internal' import { IO } from './IO' import { Monad1 } from './Monad' import { MonadIO1 } from './MonadIO' import { MonadTask1 } from './MonadTask' import { NonEmptyArray } from './NonEmptyArray' import * as O from './Option' import * as OT from './OptionT' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Separated } from './Separated' import * as T from './Task' import { TaskEither } from './TaskEither' import { guard as guard_, Zero1 } from './Zero' import Task = T.Task import Option = O.Option // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.10.0 */ export interface TaskOption extends Task> {} // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.10.0 */ export const some: (a: A) => TaskOption = /*#__PURE__*/ OT.some(T.Pointed) /** * @category lifting * @since 2.10.0 */ export const fromPredicate: { (refinement: Refinement): (a: A) => TaskOption (predicate: Predicate): (b: B) => TaskOption (predicate: Predicate): (a: A) => TaskOption } = /*#__PURE__*/ OT.fromPredicate(T.Pointed) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.10.0 */ export const fromOption: (fa: Option) => TaskOption = T.of /** * @category conversions * @since 2.10.0 */ export const fromEither: (fa: Either) => TaskOption = /*#__PURE__*/ OT.fromEither(T.Pointed) /** * @category conversions * @since 2.10.0 */ export const fromIO: (fa: IO) => TaskOption = (ma) => fromTask(T.fromIO(ma)) /** * @category conversions * @since 2.10.0 */ export const fromTask: (fa: Task) => TaskOption = /*#__PURE__*/ OT.fromF(T.Functor) /** * @category conversions * @since 2.11.0 */ export const fromTaskEither: (fa: TaskEither) => TaskOption = /*#__PURE__*/ T.map(O.fromEither) /** * @category pattern matching * @since 2.10.0 */ export const match: (onNone: () => B, onSome: (a: A) => B) => (ma: TaskOption) => Task = /*#__PURE__*/ OT.match(T.Functor) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW: (onNone: () => B, onSome: (a: A) => C) => (ma: TaskOption) => Task = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`). * * @category pattern matching * @since 2.10.0 */ export const matchE: (onNone: () => Task, onSome: (a: A) => Task) => (ma: TaskOption) => Task = /*#__PURE__*/ OT.matchE(T.Chain) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.10.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchEW: ( onNone: () => Task, onSome: (a: A) => Task ) => (ma: TaskOption) => Task = matchE as any /** * Alias of [`matchEW`](#matchew). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchEW /** * @category error handling * @since 2.10.0 */ export const getOrElse: (onNone: LazyArg>) => (fa: TaskOption) => Task = /*#__PURE__*/ OT.getOrElse( T.Monad ) /** * Less strict version of [`getOrElse`](#getorelse). * * The `W` suffix (short for **W**idening) means that the handler return type will be merged. * * @category error handling * @since 2.10.0 */ export const getOrElseW: (onNone: LazyArg>) => (ma: TaskOption) => Task = getOrElse as any /** * @category conversions * @since 2.10.0 */ export const fromNullable: (a: A) => TaskOption> = /*#__PURE__*/ OT.fromNullable(T.Pointed) /** * Transforms a `Promise` that may reject to a `Promise` that never rejects and returns an `Option` instead. * * See also [`tryCatchK`](#trycatchk). * * @category interop * @since 2.10.0 */ export const tryCatch = (f: LazyArg>): TaskOption => async () => { try { return await f().then(_.some) } catch (reason) { return _.none } } /** * Converts a function returning a `Promise` to one returning a `TaskOption`. * * @category interop * @since 2.10.0 */ export const tryCatchK = , B>(f: (...a: A) => Promise): ((...a: A) => TaskOption) => (...a) => tryCatch(() => f(...a)) /** * @category lifting * @since 2.10.0 */ export const fromNullableK: , B>( f: (...a: A) => B | null | undefined ) => (...a: A) => TaskOption> = /*#__PURE__*/ OT.fromNullableK(T.Pointed) /** * @category sequencing * @since 2.10.0 */ export const chainNullableK: ( f: (a: A) => B | null | undefined ) => (ma: TaskOption) => TaskOption> = /*#__PURE__*/ OT.chainNullableK(T.Monad) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category lifting * @since 2.10.0 */ export const fromOptionK: , B>( f: (...a: A) => Option ) => (...a: A) => TaskOption = /*#__PURE__*/ OT.fromOptionK(T.Pointed) /** * @category sequencing * @since 2.10.0 */ export const chainOptionK: (f: (a: A) => Option) => (ma: TaskOption) => TaskOption = /*#__PURE__*/ OT.chainOptionK(T.Monad) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.10.0 */ export const map: (f: (a: A) => B) => (fa: TaskOption) => TaskOption = /*#__PURE__*/ OT.map(T.Functor) /** * @since 2.10.0 */ export const ap: (fa: TaskOption) => (fab: TaskOption<(a: A) => B>) => TaskOption = /*#__PURE__*/ OT.ap( T.ApplyPar ) /** * @category constructors * @since 2.10.0 */ export const of: (a: A) => TaskOption = some /** @internal */ interface TaskOptionTypeLambda extends _.TypeLambda { readonly type: TaskOption } /** @internal */ const _FromIO: _.FromIO = { fromIO } /** @internal */ const _FromTask: _.FromTask = { fromTask } /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => TaskOption): (ma: TaskOption) => TaskOption (ma: TaskOption, f: (a: A) => TaskOption): TaskOption } = /*#__PURE__*/ dual(2, OT.flatMap(T.Monad)) /** @internal */ const _FlatMap: _.FlatMap = { flatMap } /** * @category sequencing * @since 2.16.0 */ export const flatMapIO: { (f: (a: A) => IO): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => IO): TaskOption } = /*#__PURE__*/ _.flatMapIO(_FromIO, _FlatMap) /** * @category sequencing * @since 2.16.0 */ export const flatMapTask: { (f: (a: A) => Task): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => Task): TaskOption } = /*#__PURE__*/ _.flatMapTask(_FromTask, _FlatMap) /** * @category sequencing * @since 2.10.0 */ export const flatten: (mma: TaskOption>) => TaskOption = /*#__PURE__*/ flatMap(identity) /** * @category error handling * @since 2.10.0 */ export const alt: (second: LazyArg>) => (first: TaskOption) => TaskOption = /*#__PURE__*/ OT.alt( T.Monad ) /** * Less strict version of [`alt`](#alt). * * The `W` suffix (short for **W**idening) means that the return types will be merged. * * @category error handling * @since 2.10.0 */ export const altW: (second: LazyArg>) => (first: TaskOption) => TaskOption = alt as any /** * @since 2.10.0 */ export const zero: () => TaskOption = /*#__PURE__*/ OT.zero(T.Pointed) /** * @category constructors * @since 2.10.0 */ export const none: TaskOption = /*#__PURE__*/ zero() /** * @category filtering * @since 2.10.0 */ export const compact: Compactable1['compact'] = /*#__PURE__*/ compact_(T.Functor, O.Compactable) /** * @category filtering * @since 2.10.0 */ export const separate: Compactable1['separate'] = /*#__PURE__*/ separate_(T.Functor, O.Compactable, O.Functor) /** * @category filtering * @since 2.10.0 */ export const filter: { (refinement: Refinement): (fb: TaskOption) => TaskOption (predicate: Predicate): (fb: TaskOption) => TaskOption (predicate: Predicate): (fa: TaskOption) => TaskOption } = /*#__PURE__*/ filter_(T.Functor, O.Filterable) /** * @category filtering * @since 2.10.0 */ export const filterMap: (f: (a: A) => Option) => (fga: TaskOption) => TaskOption = /*#__PURE__*/ filterMap_(T.Functor, O.Filterable) /** * @category filtering * @since 2.10.0 */ export const partition: { (refinement: Refinement): (fb: TaskOption) => Separated, TaskOption> (predicate: Predicate): (fb: TaskOption) => Separated, TaskOption> (predicate: Predicate): (fa: TaskOption) => Separated, TaskOption> } = /*#__PURE__*/ partition_(T.Functor, O.Filterable) /** * @category filtering * @since 2.10.0 */ export const partitionMap: ( f: (a: A) => Either ) => (fa: TaskOption) => Separated, TaskOption> = /*#__PURE__*/ partitionMap_( T.Functor, O.Filterable ) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- const _map: Functor1['map'] = (fa, f) => pipe(fa, map(f)) const _ap: Apply1['ap'] = (fab, fa) => pipe(fab, ap(fa)) /* istanbul ignore next */ const _alt: Alt1['alt'] = (fa, that) => pipe(fa, alt(that)) /* istanbul ignore next */ const _filter: Filterable1['filter'] = (fa: TaskOption, predicate: Predicate) => pipe(fa, filter(predicate)) /* istanbul ignore next */ const _filterMap: Filterable1['filterMap'] = (fa, f) => pipe(fa, filterMap(f)) /* istanbul ignore next */ const _partition: Filterable1['partition'] = (fa: TaskOption, predicate: Predicate) => pipe(fa, partition(predicate)) /* istanbul ignore next */ const _partitionMap: Filterable1['partitionMap'] = (fa, f) => pipe(fa, partitionMap(f)) /** * @category type lambdas * @since 2.10.0 */ export const URI = 'TaskOption' /** * @category type lambdas * @since 2.10.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: TaskOption } } /** * @category instances * @since 2.10.0 */ export const Functor: Functor1 = { URI, map: _map } /** * Maps the `Some` value of this `TaskOption` to the specified constant value. * * @category mapping * @since 2.16.0 */ export const as: { (a: A): <_>(self: TaskOption<_>) => TaskOption <_, A>(self: TaskOption<_>, a: A): TaskOption } = dual(2, as_(Functor)) /** * Maps the `Some` value of this `TaskOption` to the void constant value. * * @category mapping * @since 2.16.0 */ export const asUnit: <_>(self: TaskOption<_>) => TaskOption = asUnit_(Functor) /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplyPar: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.10.0 */ export const apFirst = /*#__PURE__*/ apFirst_(ApplyPar) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.10.0 */ export const apSecond = /*#__PURE__*/ apSecond_(ApplyPar) /** * Runs computations in parallel. * * @category instances * @since 2.10.0 */ export const ApplicativePar: Applicative1 = { URI, map: _map, ap: _ap, of } const _apSeq: Apply1['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /** * Runs computations sequentially. * * @category instances * @since 2.10.0 */ export const ApplySeq: Apply1 = { URI, map: _map, ap: _apSeq } /** * Runs computations sequentially. * * @category instances * @since 2.10.0 */ export const ApplicativeSeq: Applicative1 = { URI, map: _map, ap: _apSeq, of } /** * @category instances * @since 2.10.0 */ export const Chain: chainable.Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.11.0 */ export const FromEither: FromEither1 = { URI, fromEither } /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO1 = { URI, fromIO } /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask1 = { URI, fromIO, fromTask } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @category combinators * @since 2.15.0 */ export const tap: { (self: TaskOption, f: (a: A) => TaskOption<_>): TaskOption (f: (a: A) => TaskOption<_>): (self: TaskOption) => TaskOption } = /*#__PURE__*/ dual(2, chainable.tap(Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as TO from 'fp-ts/TaskOption' * import * as O from 'fp-ts/Option' * import * as E from 'fp-ts/Either' * * const compute = (value: number) => pipe( * TO.of(value), * TO.tapEither((value) => value > 0 ? E.right('ok') : E.left('error')), * ) * * async function test() { * assert.deepStrictEqual(await compute(1)(), O.of(1)) * assert.deepStrictEqual(await compute(-1)(), O.none) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapEither: { (f: (a: A) => Either): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => Either): TaskOption } = /*#__PURE__*/ dual(2, tapEither_(FromEither, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import { pipe } from 'fp-ts/function' * import * as TO from 'fp-ts/TaskOption' * import * as O from 'fp-ts/Option' * import * as Console from 'fp-ts/Console' * * * // Will produce `Hello, fp-ts` to the stdout * const effectA = TO.tapIO( * TO.of(1), * (value) => Console.log(`Hello, ${value}`) * ) * * // No output to the stdout * const effectB = pipe( * TO.none as TO.TaskOption, * TO.tapIO((value) => Console.log(`Hello, ${value}`)) * ) * * async function test() { * assert.deepStrictEqual(await effectA(), O.of(1)) * assert.deepStrictEqual(await effectB(), O.none) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapIO: { (f: (a: A) => IO<_>): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => IO<_>): TaskOption } = /*#__PURE__*/ dual(2, tapIO_(FromIO, Chain)) /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @example * import * as TO from 'fp-ts/TaskOption' * import * as O from 'fp-ts/Option' * import * as T from 'fp-ts/Task' * * const effect = TO.tapIO( * TO.of(1), * (value) => T.of(value + 1) * ) * * async function test() { * assert.deepStrictEqual(await effect(), O.of(1)) * } * * test() * * @category combinators * @since 2.16.0 */ export const tapTask: { (f: (a: A) => Task<_>): (self: TaskOption) => TaskOption (self: TaskOption, f: (a: A) => Task<_>): TaskOption } = /*#__PURE__*/ dual(2, tapTask_(FromTask, Chain)) /** * @category instances * @since 2.10.0 */ export const Alt: Alt1 = { URI, map: _map, alt: _alt } /** * @category instances * @since 2.11.0 */ export const Zero: Zero1 = { URI, zero } /** * @category do notation * @since 2.11.0 */ export const guard = /*#__PURE__*/ guard_(Zero, Pointed) /** * @category instances * @since 2.10.0 */ export const Alternative: Alternative1 = { URI, map: _map, ap: _ap, of, alt: _alt, zero } /** * @category instances * @since 2.10.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * @category instances * @since 2.10.0 */ export const MonadIO: MonadIO1 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO } /** * @category instances * @since 2.10.0 */ export const MonadTask: MonadTask1 = { URI, map: _map, ap: _ap, of, chain: flatMap, fromIO, fromTask } /** * @category instances * @since 2.10.0 */ export const Compactable: Compactable1 = { URI, compact, separate } /** * @category instances * @since 2.10.0 */ export const Filterable: Filterable1 = { URI, map: _map, compact, separate, filter: _filter, filterMap: _filterMap, partition: _partition, partitionMap: _partitionMap } /** * @category lifting * @since 2.10.0 */ export const fromIOK: , B>(f: (...a: A) => IO) => (...a: A) => TaskOption = /*#__PURE__*/ fromIOK_(FromIO) /** * Alias of `flatMapIO`. * * @category legacy * @since 2.10.0 */ export const chainIOK: (f: (a: A) => IO) => (first: TaskOption) => TaskOption = flatMapIO /** * Alias of `tapIO`. * * @category legacy * @since 2.10.0 */ export const chainFirstIOK: (f: (a: A) => IO) => (first: TaskOption) => TaskOption = tapIO /** * @category lifting * @since 2.12.0 */ export const fromEitherK: , B>( f: (...a: A) => Either ) => (...a: A) => TaskOption = /*#__PURE__*/ fromEitherK_(FromEither) /** * @category sequencing * @since 2.12.0 */ export const chainEitherK: (f: (a: A) => Either) => (ma: TaskOption) => TaskOption = /*#__PURE__*/ chainEitherK_(FromEither, Chain) /** * Alias of `tapEither`. * * @category legacy * @since 2.12.0 */ export const chainFirstEitherK: (f: (a: A) => Either) => (ma: TaskOption) => TaskOption = tapEither /** * @category lifting * @since 2.10.0 */ export const fromTaskK: , B>(f: (...a: A) => T.Task) => (...a: A) => TaskOption = /*#__PURE__*/ fromTaskK_(FromTask) /** * Alias of `flatMapTask`. * * @category legacy * @since 2.10.0 */ export const chainTaskK: (f: (a: A) => T.Task) => (first: TaskOption) => TaskOption = flatMapTask /** * Alias of `tapTask`. * * @category legacy * @since 2.10.0 */ export const chainFirstTaskK: (f: (a: A) => T.Task) => (first: TaskOption) => TaskOption = tapTask // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.10.0 */ export const Do: TaskOption<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.10.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.10.0 */ export const bind = /*#__PURE__*/ chainable.bind(Chain) /** * @category do notation * @since 2.10.0 */ export const apS = /*#__PURE__*/ apS_(ApplyPar) /** * @since 2.11.0 */ export const ApT: TaskOption = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( f: (index: number, a: A) => TaskOption ): ((as: ReadonlyNonEmptyArray) => TaskOption>) => flow(T.traverseReadonlyNonEmptyArrayWithIndex(f), T.map(O.traverseReadonlyNonEmptyArrayWithIndex(SK))) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativePar)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = ( f: (index: number, a: A) => TaskOption ): ((as: ReadonlyArray) => TaskOption>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = (f: (index: number, a: A) => TaskOption) => (as: ReadonlyNonEmptyArray): TaskOption> => () => _.tail(as).reduce>>>( (acc, a, i) => acc.then((obs) => _.isNone(obs) ? acc : f(i + 1, a)().then((ob) => { if (_.isNone(ob)) { return ob } obs.value.push(ob.value) return obs }) ), f(0, _.head(as))().then(O.map(_.singleton)) ) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = ( f: (index: number, a: A) => TaskOption ): ((as: ReadonlyArray) => TaskOption>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`. * * @category traversing * @since 2.10.0 */ export const traverseArrayWithIndex: ( f: (index: number, a: A) => TaskOption ) => (as: ReadonlyArray) => TaskOption> = traverseReadonlyArrayWithIndex /** * Equivalent to `ReadonlyArray#traverse(Applicative)`. * * @category traversing * @since 2.10.0 */ export const traverseArray: ( f: (a: A) => TaskOption ) => (as: ReadonlyArray) => TaskOption> = (f) => traverseReadonlyArrayWithIndex((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(Applicative)`. * * @category traversing * @since 2.10.0 */ export const sequenceArray: (as: ReadonlyArray>) => TaskOption> = /*#__PURE__*/ traverseArray(identity) /** * Equivalent to `ReadonlyArray#traverseWithIndex(ApplicativeSeq)`. * * @category traversing * @since 2.10.0 */ export const traverseSeqArrayWithIndex: ( f: (index: number, a: A) => TaskOption ) => (as: ReadonlyArray) => TaskOption> = traverseReadonlyArrayWithIndexSeq /** * Equivalent to `ReadonlyArray#traverse(ApplicativeSeq)`. * * @category traversing * @since 2.10.0 */ export const traverseSeqArray: ( f: (a: A) => TaskOption ) => (as: ReadonlyArray) => TaskOption> = (f) => traverseReadonlyArrayWithIndexSeq((_, a) => f(a)) /** * Equivalent to `ReadonlyArray#sequence(ApplicativeSeq)`. * * @category traversing * @since 2.10.0 */ export const sequenceSeqArray: (as: ReadonlyArray>) => TaskOption> = /*#__PURE__*/ traverseSeqArray(identity) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.10.0 */ export const chain: (f: (a: A) => TaskOption) => (ma: TaskOption) => TaskOption = flatMap /** * Alias of `tap`. * * @category legacy * @since 2.10.0 */ export const chainFirst: (f: (a: A) => TaskOption) => (first: TaskOption) => TaskOption = tap ================================================ FILE: src/TaskThese.ts ================================================ /** * @since 2.4.0 */ import { Applicative2C } from './Applicative' import { Apply1, Apply2C, getApplySemigroup } from './Apply' import { Bifunctor2 } from './Bifunctor' import { Chain2C } from './Chain' import { Either } from './Either' import { FromEither2, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_ } from './FromEither' import { FromIO2, fromIOK as fromIOK_ } from './FromIO' import { FromTask2, fromTaskK as fromTaskK_ } from './FromTask' import { FromThese2, fromTheseK as fromTheseK_ } from './FromThese' import { flow, LazyArg, pipe, SK } from './function' import { flap as flap_, Functor2 } from './Functor' import * as _ from './internal' import { IO } from './IO' import { IOEither } from './IOEither' import { Monad2C } from './Monad' import { MonadTask2C } from './MonadTask' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { Pointed2 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import * as T from './Task' import * as TH from './These' import * as TT from './TheseT' import These = TH.These import Task = T.Task // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.4.0 */ export interface TaskThese extends Task> {} /** * @category constructors * @since 2.4.0 */ export const left: (e: E) => TaskThese = /*#__PURE__*/ TT.left(T.Pointed) /** * @category constructors * @since 2.4.0 */ export const right: (a: A) => TaskThese = /*#__PURE__*/ TT.right(T.Pointed) /** * @category constructors * @since 2.4.0 */ export const both: (e: E, a: A) => TaskThese = /*#__PURE__*/ TT.both(T.Pointed) /** * @category constructors * @since 2.4.0 */ export const rightTask: (ma: Task) => TaskThese = /*#__PURE__*/ TT.rightF(T.Functor) /** * @category constructors * @since 2.4.0 */ export const leftTask: (me: Task) => TaskThese = /*#__PURE__*/ TT.leftF(T.Functor) /** * @category constructors * @since 2.4.0 */ export const rightIO: (ma: IO) => TaskThese = /*#__PURE__*/ flow(T.fromIO, rightTask) /** * @category constructors * @since 2.4.0 */ export const leftIO: (me: IO) => TaskThese = /*#__PURE__*/ flow(T.fromIO, leftTask) // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * @category conversions * @since 2.10.0 */ export const fromEither: (fa: Either) => TaskThese = T.of /** * @category conversions * @since 2.11.0 */ export const fromThese: (fa: These) => TaskThese = T.of /** * @category conversions * @since 2.7.0 */ export const fromIO: (fa: IO) => TaskThese = rightIO /** * @category conversions * @since 2.4.0 */ export const fromIOEither: (fa: IOEither) => TaskThese = T.fromIO /** * @category conversions * @since 2.7.0 */ export const fromTask: (fa: Task) => TaskThese = rightTask /** * @category pattern matching * @since 2.10.0 */ export const match: ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (fa: TaskThese) => Task = /*#__PURE__*/ TT.match(T.Functor) /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW: ( onLeft: (e: E) => B, onRight: (a: A) => C, onBoth: (e: E, a: A) => D ) => (ma: TaskThese) => T.Task = match as any /** * The `E` suffix (short for **E**ffect) means that the handlers return an effect (`Task`). * * @category pattern matching * @since 2.10.0 */ export const matchE: ( onLeft: (e: E) => Task, onRight: (a: A) => Task, onBoth: (e: E, a: A) => Task ) => (fa: TaskThese) => Task = /*#__PURE__*/ TT.matchE(T.Monad) /** * Alias of [`matchE`](#matche). * * @category pattern matching * @since 2.4.0 */ export const fold = matchE /** * Less strict version of [`matchE`](#matche). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchEW: ( onLeft: (e: E) => Task, onRight: (a: A) => Task, onBoth: (e: E, a: A) => Task ) => (fa: TaskThese) => Task = fold as any /** * Alias of [`matchEW`](#matchew). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchEW /** * @since 2.4.0 */ export const swap: (fa: TaskThese) => TaskThese = /*#__PURE__*/ TT.swap(T.Functor) const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _bimap: Bifunctor2['bimap'] = (fa, f, g) => pipe(fa, bimap(f, g)) /* istanbul ignore next */ const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapLeft(f)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.4.0 */ export const map: (f: (a: A) => B) => (fa: TaskThese) => TaskThese = /*#__PURE__*/ TT.map( T.Functor ) /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.4.0 */ export const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: TaskThese) => TaskThese = /*#__PURE__*/ TT.bimap(T.Functor) /** * Map a function over the first type argument of a bifunctor. * * @category error handling * @since 2.4.0 */ export const mapLeft: (f: (e: E) => G) => (fa: TaskThese) => TaskThese = /*#__PURE__*/ TT.mapLeft( T.Functor ) /** * @category constructors * @since 2.7.0 */ export const of: (a: A) => TaskThese = right /** * @category type lambdas * @since 2.4.0 */ export const URI = 'TaskThese' /** * @category type lambdas * @since 2.4.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: TaskThese } } /** * @category instances * @since 2.10.0 */ export const getApply = (A: Apply1, S: Semigroup): Apply2C => { const ap = TT.ap(A, S) return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => pipe(fab, ap(fa)) } } /** * @category instances * @since 2.7.0 */ export function getApplicative(A: Apply1, S: Semigroup): Applicative2C { const { ap } = getApply(A, S) return { URI, _E: undefined as any, map: _map, ap, of } } /** * @category instances * @since 2.10.0 */ export function getChain(S: Semigroup): Chain2C { const A = getApply(T.ApplicativePar, S) const chain = TT.chain(T.Monad, S) return { URI, _E: undefined as any, map: _map, ap: A.ap, chain: (ma, f) => pipe(ma, chain(f)) } } /** * @category instances * @since 2.4.0 */ export function getMonad(S: Semigroup): Monad2C & MonadTask2C { const A = getApplicative(T.ApplicativePar, S) const C = getChain(S) return { URI, _E: undefined as any, map: _map, ap: A.ap, of, chain: C.chain, fromIO, fromTask } } /** * @category instances * @since 2.10.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither2 = { URI, fromEither } /** * @category conversions * @since 2.10.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => TaskThese = /*#__PURE__*/ fromOption_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => TaskThese = /*#__PURE__*/ fromOptionK_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => TaskThese (predicate: Predicate, onFalse: (a: A) => E): (b: B) => TaskThese (predicate: Predicate, onFalse: (a: A) => E): (a: A) => TaskThese } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category instances * @since 2.11.0 */ export const FromThese: FromThese2 = { URI, fromThese } /** * @category lifting * @since 2.11.0 */ export const fromTheseK: , E, B>( f: (...a: A) => TH.These ) => (...a: A) => TaskThese = /*#__PURE__*/ fromTheseK_(FromThese) /** * @category instances * @since 2.10.0 */ export const FromIO: FromIO2 = { URI, fromIO } /** * @category lifting * @since 2.10.0 */ export const fromIOK: , B>( f: (...a: A) => IO ) => (...a: A) => TaskThese = /*#__PURE__*/ fromIOK_(FromIO) /** * @category instances * @since 2.10.0 */ export const FromTask: FromTask2 = { URI, fromIO, fromTask } /** * @category lifting * @since 2.10.0 */ export const fromTaskK: , B>( f: (...a: A) => T.Task ) => (...a: A) => TaskThese = /*#__PURE__*/ fromTaskK_(FromTask) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.10.0 */ export const toTuple2: (e: LazyArg, a: LazyArg) => (fa: TaskThese) => Task = /*#__PURE__*/ TT.toTuple2(T.Functor) /** * @since 2.11.0 */ export const ApT: TaskThese = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(getApplicative(T.ApplicativePar, S))`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = ( S: Semigroup ): (( f: (index: number, a: A) => TaskThese ) => (as: ReadonlyNonEmptyArray) => TaskThese>) => { const g = TH.traverseReadonlyNonEmptyArrayWithIndex(S) return (f) => flow(T.traverseReadonlyNonEmptyArrayWithIndex(f), T.map(g(SK))) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(getApplicative(T.ApplicativePar, S))`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = (S: Semigroup) => (f: (index: number, a: A) => TaskThese): ((as: ReadonlyArray) => TaskThese>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(S)(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(getApplicative(T.ApplicativeSeq, S))`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndexSeq = (S: Semigroup) => (f: (index: number, a: A) => TaskThese) => (as: ReadonlyNonEmptyArray): TaskThese> => () => _.tail(as).reduce>>>( (acc, a, i) => acc.then((ebs) => TH.isLeft(ebs) ? acc : f(i + 1, a)().then((eb) => { if (TH.isLeft(eb)) { return eb } if (TH.isBoth(eb)) { const right = ebs.right right.push(eb.right) return TH.isBoth(ebs) ? TH.both(S.concat(ebs.left, eb.left), right) : TH.both(eb.left, right) } ebs.right.push(eb.right) return ebs }) ), f(0, _.head(as))().then(TH.map(_.singleton)) ) /** * Equivalent to `ReadonlyArray#traverseWithIndex(getApplicative(T.ApplicativeSeq, S))`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndexSeq = (S: Semigroup) => (f: (index: number, a: A) => TaskThese): ((as: ReadonlyArray) => TaskThese>) => { const g = traverseReadonlyNonEmptyArrayWithIndexSeq(S)(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`Functor`](#functor) instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const functorTaskThese: Functor2 = { URI, map: _map } /** * Use [`Bifunctor`](#bifunctor) instead. * * @category zone of death * @since 2.7.0 * @deprecated */ export const bifunctorTaskThese: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * Use [`toTuple2`](#totuple2) instead. * * @category zone of death * @since 2.4.0 * @deprecated */ export const toTuple = (e: E, a: A): ((fa: TaskThese) => Task<[E, A]>) => toTuple2( () => e, () => a ) as any /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `TT.Functor` instead of `TT.taskThese` * (where `TT` is from `import TT from 'fp-ts/TaskThese'`) * * @category zone of death * @since 2.4.0 * @deprecated */ export const taskThese: Functor2 & Bifunctor2 = { URI, map: _map, bimap: _bimap, mapLeft: _mapLeft } /** * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead. * * @category zone of death * @since 2.4.0 * @deprecated */ export const getSemigroup = (SE: Semigroup, SA: Semigroup): Semigroup> => getApplySemigroup(T.ApplySeq)(TH.getSemigroup(SE, SA)) ================================================ FILE: src/These.ts ================================================ /** * A data structure providing "inclusive-or" as opposed to `Either`'s "exclusive-or". * * If you interpret `Either` as suggesting the computation may either fail or succeed (exclusively), then * `These` may fail, succeed, or do both at the same time. * * There are a few ways to interpret the both case: * * - You can think of a computation that has a non-fatal error. * - You can think of a computation that went as far as it could before erroring. * - You can think of a computation that keeps track of errors as it completes. * * Another way you can think of `These` is saying that we want to handle `E` kind of data, `A` kind of data, or * both `E` and `A` kind of data at the same time. This is particularly useful when it comes to displaying UI's. * * (description adapted from https://package.elm-lang.org/packages/joneshf/elm-these) * * Adapted from https://github.com/purescript-contrib/purescript-these * * @since 2.0.0 */ import { Applicative, Applicative2C } from './Applicative' import { Apply2C } from './Apply' import { Bifunctor2 } from './Bifunctor' import { Chain2C } from './Chain' import { Either, Left, Right } from './Either' import { Eq, fromEquals } from './Eq' import { Foldable2 } from './Foldable' import { FromEither2, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_ } from './FromEither' import { FromThese2 } from './FromThese' import { identity, LazyArg, pipe } from './function' import { flap as flap_, Functor2 } from './Functor' import { HKT } from './HKT' import * as _ from './internal' import { Monad2C } from './Monad' import { MonadThrow2C } from './MonadThrow' import { Monoid } from './Monoid' import { NonEmptyArray } from './NonEmptyArray' import { Option } from './Option' import { Pointed2 } from './Pointed' import { Predicate } from './Predicate' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { Show } from './Show' import { PipeableTraverse2, Traversable2 } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Both { readonly _tag: 'Both' readonly left: E readonly right: A } /** * @category model * @since 2.0.0 */ export type These = Either | Both // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * Returns `true` if the these is an instance of `Left`, `false` otherwise * * @category refinements * @since 2.0.0 */ export const isLeft = (fa: These): fa is Left => fa._tag === 'Left' /** * Returns `true` if the these is an instance of `Right`, `false` otherwise * * @category refinements * @since 2.0.0 */ export const isRight = (fa: These): fa is Right => fa._tag === 'Right' /** * Returns `true` if the these is an instance of `Both`, `false` otherwise * * @category refinements * @since 2.0.0 */ export function isBoth(fa: These): fa is Both { return fa._tag === 'Both' } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.0.0 */ export function left(left: E): These { return { _tag: 'Left', left } } /** * @category constructors * @since 2.0.0 */ export function right(right: A): These { return { _tag: 'Right', right } } /** * @category constructors * @since 2.0.0 */ export function both(left: E, right: A): These { return { _tag: 'Both', left, right } } /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW = (onLeft: (e: E) => B, onRight: (a: A) => C, onBoth: (e: E, a: A) => D) => (fa: These): B | C | D => { switch (fa._tag) { case 'Left': return onLeft(fa.left) case 'Right': return onRight(fa.right) case 'Both': return onBoth(fa.left, fa.right) } } /** * Alias of [`matchW`](#matchw). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchW /** * @category pattern matching * @since 2.10.0 */ export const match: ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (fa: These) => B = matchW /** * Alias of [`match`](#match). * * @category pattern matching * @since 2.0.0 */ export const fold = match /** * @since 2.4.0 */ export const swap: (fa: These) => These = match(right, left, (e, a) => both(a, e)) /** * @category instances * @since 2.0.0 */ export function getShow(SE: Show, SA: Show): Show> { return { show: match( (l) => `left(${SE.show(l)})`, (a) => `right(${SA.show(a)})`, (l, a) => `both(${SE.show(l)}, ${SA.show(a)})` ) } } /** * @category instances * @since 2.0.0 */ export function getEq(EE: Eq, EA: Eq): Eq> { return fromEquals((x, y) => isLeft(x) ? isLeft(y) && EE.equals(x.left, y.left) : isRight(x) ? isRight(y) && EA.equals(x.right, y.right) : isBoth(y) && EE.equals(x.left, y.left) && EA.equals(x.right, y.right) ) } /** * @category instances * @since 2.0.0 */ export function getSemigroup(SE: Semigroup, SA: Semigroup): Semigroup> { return { concat: (x, y) => isLeft(x) ? isLeft(y) ? left(SE.concat(x.left, y.left)) : isRight(y) ? both(x.left, y.right) : both(SE.concat(x.left, y.left), y.right) : isRight(x) ? isLeft(y) ? both(y.left, x.right) : isRight(y) ? right(SA.concat(x.right, y.right)) : both(y.left, SA.concat(x.right, y.right)) : isLeft(y) ? both(SE.concat(x.left, y.left), x.right) : isRight(y) ? both(x.left, SA.concat(x.right, y.right)) : both(SE.concat(x.left, y.left), SA.concat(x.right, y.right)) } } /** * @category instances * @since 2.10.0 */ export const getApply = (S: Semigroup): Apply2C => ({ URI, _E: undefined as any, map: _map, ap: (fab, fa) => isLeft(fab) ? isLeft(fa) ? left(S.concat(fab.left, fa.left)) : isRight(fa) ? left(fab.left) : left(S.concat(fab.left, fa.left)) : isRight(fab) ? isLeft(fa) ? left(fa.left) : isRight(fa) ? right(fab.right(fa.right)) : both(fa.left, fab.right(fa.right)) : isLeft(fa) ? left(S.concat(fab.left, fa.left)) : isRight(fa) ? both(fab.left, fab.right(fa.right)) : both(S.concat(fab.left, fa.left), fab.right(fa.right)) }) /** * @category instances * @since 2.7.0 */ export function getApplicative(S: Semigroup): Applicative2C { const A = getApply(S) return { URI, _E: undefined as any, map: _map, ap: A.ap, of } } /** * @category instances * @since 2.10.0 */ export function getChain(S: Semigroup): Chain2C { const A = getApply(S) const chain = (ma: These, f: (a: A) => These): These => { if (isLeft(ma)) { return ma } if (isRight(ma)) { return f(ma.right) } const fb = f(ma.right) return isLeft(fb) ? left(S.concat(ma.left, fb.left)) : isRight(fb) ? both(ma.left, fb.right) : both(S.concat(ma.left, fb.left), fb.right) } return { URI, _E: undefined as any, map: _map, ap: A.ap, chain } } /** * @category instances * @since 2.0.0 */ export function getMonad(S: Semigroup): Monad2C & MonadThrow2C { const C = getChain(S) return { URI, _E: undefined as any, map: _map, of, ap: C.ap, chain: C.chain, throwError: left } } /** * Returns an `E` value if possible * * @example * import { getLeft, left, right, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(getLeft(left('a')), some('a')) * assert.deepStrictEqual(getLeft(right(1)), none) * assert.deepStrictEqual(getLeft(both('a', 1)), some('a')) * * @category conversions * @since 2.0.0 */ export function getLeft(fa: These): Option { return isLeft(fa) ? _.some(fa.left) : isRight(fa) ? _.none : _.some(fa.left) } /** * Returns an `A` value if possible * * @example * import { getRight, left, right, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(getRight(left('a')), none) * assert.deepStrictEqual(getRight(right(1)), some(1)) * assert.deepStrictEqual(getRight(both('a', 1)), some(1)) * * @category conversions * @since 2.0.0 */ export function getRight(fa: These): Option { return isLeft(fa) ? _.none : isRight(fa) ? _.some(fa.right) : _.some(fa.right) } // TODO: make lazy in v3 /** * @example * import { leftOrBoth, left, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(leftOrBoth('a')(none), left('a')) * assert.deepStrictEqual(leftOrBoth('a')(some(1)), both('a', 1)) * * @category constructors * @since 2.0.0 */ export function leftOrBoth(e: E): (ma: Option) => These { return (ma) => (_.isNone(ma) ? left(e) : both(e, ma.value)) } // TODO: make lazy in v3 /** * @example * import { rightOrBoth, right, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(rightOrBoth(1)(none), right(1)) * assert.deepStrictEqual(rightOrBoth(1)(some('a')), both('a', 1)) * * @category constructors * @since 2.0.0 */ export function rightOrBoth(a: A): (me: Option) => These { return (me) => (_.isNone(me) ? right(a) : both(me.value, a)) } /** * Returns the `E` value if and only if the value is constructed with `Left` * * @example * import { getLeftOnly, left, right, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(getLeftOnly(left('a')), some('a')) * assert.deepStrictEqual(getLeftOnly(right(1)), none) * assert.deepStrictEqual(getLeftOnly(both('a', 1)), none) * * @category conversions * @since 2.0.0 */ export function getLeftOnly(fa: These): Option { return isLeft(fa) ? _.some(fa.left) : _.none } /** * Returns the `A` value if and only if the value is constructed with `Right` * * @example * import { getRightOnly, left, right, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(getRightOnly(left('a')), none) * assert.deepStrictEqual(getRightOnly(right(1)), some(1)) * assert.deepStrictEqual(getRightOnly(both('a', 1)), none) * * @category conversions * @since 2.0.0 */ export function getRightOnly(fa: These): Option { return isRight(fa) ? _.some(fa.right) : _.none } /** * Takes a pair of `Option`s and attempts to create a `These` from them * * @example * import { fromOptions, left, right, both } from 'fp-ts/These' * import { none, some } from 'fp-ts/Option' * * assert.deepStrictEqual(fromOptions(none, none), none) * assert.deepStrictEqual(fromOptions(some('a'), none), some(left('a'))) * assert.deepStrictEqual(fromOptions(none, some(1)), some(right(1))) * assert.deepStrictEqual(fromOptions(some('a'), some(1)), some(both('a', 1))) * * @category conversions * @since 2.0.0 */ export const fromOptions = (fe: Option, fa: Option): Option> => _.isNone(fe) ? _.isNone(fa) ? _.none : _.some(right(fa.value)) : _.isNone(fa) ? _.some(left(fe.value)) : _.some(both(fe.value, fa.value)) const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /* istanbul ignore next */ const _bimap: Bifunctor2['bimap'] = (fa, f, g) => pipe(fa, bimap(f, g)) /* istanbul ignore next */ const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapLeft(f)) /* istanbul ignore next */ const _reduce: Foldable2['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable2['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable2['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _traverse = ( F: Applicative ): ((ta: These, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.0.0 */ export const bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: These) => These = (f, g) => (fa) => isLeft(fa) ? left(f(fa.left)) : isRight(fa) ? right(g(fa.right)) : both(f(fa.left), g(fa.right)) /** * Map a function over the first type argument of a bifunctor. * * @category error handling * @since 2.0.0 */ export const mapLeft: (f: (e: E) => G) => (fa: These) => These = (f) => (fa) => isLeft(fa) ? left(f(fa.left)) : isBoth(fa) ? both(f(fa.left), fa.right) : fa /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: These) => These = (f) => (fa) => isLeft(fa) ? fa : isRight(fa) ? right(f(fa.right)) : both(fa.left, f(fa.right)) /** * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: These) => B = (b, f) => (fa) => isLeft(fa) ? b : f(b, fa.right) /** * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: These) => M = (M) => (f) => (fa) => isLeft(fa) ? M.empty : f(fa.right) /** * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: These) => B = (b, f) => (fa) => isLeft(fa) ? b : f(fa.right, b) /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse2 = (F: Applicative): ((f: (a: A) => HKT) => (ta: These) => HKT>) => (f) => (ta) => isLeft(ta) ? F.of(ta) : isRight(ta) ? F.map(f(ta.right), right) : F.map(f(ta.right), (b) => both(ta.left, b)) /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable2['sequence'] = (F: Applicative) => (ta: These>): HKT> => { return isLeft(ta) ? F.of(ta) : isRight(ta) ? F.map(ta.right, right) : F.map(ta.right, (b) => both(ta.left, b)) } /** * @category constructors * @since 2.0.0 */ export const of: (right: A) => These = right /** * @category type lambdas * @since 2.0.0 */ export const URI = 'These' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: These } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed2 = { URI, of } /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * @category instances * @since 2.11.0 */ export const FromThese: FromThese2 = { URI, fromThese: identity } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable2 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable2 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.10.0 */ export const FromEither: FromEither2 = { URI, fromEither: identity } /** * @category lifting * @since 2.13.0 */ export const fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => These (predicate: Predicate, onFalse: (a: A) => E): (b: B) => These (predicate: Predicate, onFalse: (a: A) => E): (a: A) => These } = /*#__PURE__*/ fromPredicate_(FromEither) /** * @category conversions * @since 2.10.0 */ export const fromOption: (onNone: LazyArg) => (fa: Option) => These = /*#__PURE__*/ fromOption_(FromEither) /** * @category lifting * @since 2.10.0 */ export const fromOptionK: ( onNone: LazyArg ) => , B>(f: (...a: A) => Option) => (...a: A) => These = /*#__PURE__*/ fromOptionK_(FromEither) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const elem = (E: Eq) => (a: A) => (ma: These): boolean => isLeft(ma) ? false : E.equals(a, ma.right) /** * @since 2.11.0 */ export const exists = (predicate: Predicate) => (ma: These): boolean => isLeft(ma) ? false : predicate(ma.right) /** * @example * import { toTuple2, left, right, both } from 'fp-ts/These' * * assert.deepStrictEqual(toTuple2(() => 'a', () => 1)(left('b')), ['b', 1]) * assert.deepStrictEqual(toTuple2(() => 'a', () => 1)(right(2)), ['a', 2]) * assert.deepStrictEqual(toTuple2(() => 'a', () => 1)(both('b', 2)), ['b', 2]) * * @category conversions * @since 2.10.0 */ export const toTuple2 = (e: LazyArg, a: LazyArg) => (fa: These): readonly [E, A] => isLeft(fa) ? [fa.left, a()] : isRight(fa) ? [e(), fa.right] : [fa.left, fa.right] // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`toTuple2`](#totuple2) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const toTuple = (e: E, a: A): ((fa: These) => [E, A]) => toTuple2( () => e, () => a ) as any /** * @since 2.11.0 */ export const ApT: These = /*#__PURE__*/ of(_.emptyReadonlyArray) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- /** * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(getApplicative(S))`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyNonEmptyArrayWithIndex = (S: Semigroup) => (f: (index: number, a: A) => These) => (as: ReadonlyNonEmptyArray): These> => { let e: Option = _.none const t = f(0, _.head(as)) if (isLeft(t)) { return t } if (isBoth(t)) { e = _.some(t.left) } const out: NonEmptyArray = [t.right] for (let i = 1; i < as.length; i++) { const t = f(i, as[i]) if (isLeft(t)) { return t } if (isBoth(t)) { e = _.isNone(e) ? _.some(t.left) : _.some(S.concat(e.value, t.left)) } out.push(t.right) } return _.isNone(e) ? right(out) : both(e.value, out) } /** * Equivalent to `ReadonlyArray#traverseWithIndex(getApplicative(S))`. * * @category traversing * @since 2.11.0 */ export const traverseReadonlyArrayWithIndex = (S: Semigroup) => (f: (index: number, a: A) => These): ((as: ReadonlyArray) => These>) => { const g = traverseReadonlyNonEmptyArrayWithIndex(S)(f) return (as) => (_.isNonEmpty(as) ? g(as) : ApT) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.these` * (where `T` is from `import T from 'fp-ts/These'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const these: Functor2 & Bifunctor2 & Foldable2 & Traversable2 = { URI, map: _map, bimap: _bimap, mapLeft: _mapLeft, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } ================================================ FILE: src/TheseT.ts ================================================ /** * @since 2.4.0 */ import { ap as ap_, Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C } from './Apply' import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C } from './Chain' import { flow, LazyArg, pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, map as map_ } from './Functor' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3, Monad3C } from './Monad' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C } from './Pointed' import { Semigroup } from './Semigroup' import * as T from './These' import These = T.These /** * @since 2.10.0 */ export function right(F: Pointed3): (a: A) => Kind3> export function right(F: Pointed3C): (a: A) => Kind3> export function right(F: Pointed2): (a: A) => Kind2> export function right(F: Pointed2C): (a: A) => Kind2> export function right(F: Pointed1): (a: A) => Kind> export function right(F: Pointed): (a: A) => HKT> export function right(F: Pointed): (a: A) => HKT> { return flow(T.right, F.of) } /** * @since 2.10.0 */ export function left(F: Pointed3): (e: E) => Kind3> export function left(F: Pointed3C): (e: E) => Kind3> export function left(F: Pointed2): (e: E) => Kind2> export function left(F: Pointed2C): (e: E) => Kind2> export function left(F: Pointed1): (e: E) => Kind> export function left(F: Pointed): (e: E) => HKT> export function left(F: Pointed): (e: E) => HKT> { return flow(T.left, F.of) } /** * @since 2.10.0 */ export function both(F: Pointed3): (e: E, a: A) => Kind3> export function both(F: Pointed3C): (e: E, a: A) => Kind3> export function both(F: Pointed2): (e: E, a: A) => Kind2> export function both(F: Pointed2C): (e: E, a: A) => Kind2> export function both(F: Pointed1): (e: E, a: A) => Kind> export function both(F: Pointed): (e: E, a: A) => HKT> export function both(F: Pointed): (e: E, a: A) => HKT> { return flow(T.both, F.of) } /** * @since 2.10.0 */ export function rightF( F: Functor3 ): (fa: Kind3) => Kind3> export function rightF( F: Functor3C ): (fa: Kind3) => Kind3> export function rightF( F: Functor2 ): (fa: Kind2) => Kind2> export function rightF( F: Functor2C ): (fa: Kind2) => Kind2> export function rightF(F: Functor1): (fa: Kind) => Kind> export function rightF(F: Functor): (fa: HKT) => HKT> export function rightF(F: Functor): (fa: HKT) => HKT> { return (fa) => F.map(fa, T.right) } /** * @since 2.10.0 */ export function leftF( F: Functor3 ): (fe: Kind3) => Kind3> export function leftF( F: Functor3C ): (fe: Kind3) => Kind3> export function leftF( F: Functor2 ): (fe: Kind2) => Kind2> export function leftF( F: Functor2C ): (fe: Kind2) => Kind2> export function leftF(F: Functor1): (fe: Kind) => Kind> export function leftF(F: Functor): (fe: HKT) => HKT> export function leftF(F: Functor): (fe: HKT) => HKT> { return (fe) => F.map(fe, T.left) } /** * @since 2.10.0 */ export function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3>) => Kind3> export function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2>) => Kind2> export function map( F: Functor1 ): (f: (a: A) => B) => (fa: Kind>) => Kind> export function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> export function map(F: Functor): (f: (a: A) => B) => (fa: HKT>) => HKT> { return map_(F, T.Functor) } /** * @since 2.10.0 */ export function ap( F: Apply3, S: Semigroup ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply3C, S: Semigroup ): ( fa: Kind3> ) => (fab: Kind3 B>>) => Kind3> export function ap( F: Apply2, S: Semigroup ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply2C, S: Semigroup ): (fa: Kind2>) => (fab: Kind2 B>>) => Kind2> export function ap( F: Apply1, S: Semigroup ): (fa: Kind>) => (fab: Kind B>>) => Kind> export function ap( F: Apply, S: Semigroup ): (fa: HKT>) => (fab: HKT B>>) => HKT> export function ap( F: Apply, S: Semigroup ): (fa: HKT>) => (fab: HKT B>>) => HKT> { return ap_(F, T.getApply(S)) } /** * @since 2.10.0 */ export function chain( M: Monad3, S: Semigroup ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export function chain( M: Monad3C, S: Semigroup ): ( f: (a: A) => Kind3> ) => (ma: Kind3>) => Kind3> export function chain( M: Monad2, S: Semigroup ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export function chain( M: Monad2C, S: Semigroup ): (f: (a: A) => Kind2>) => (ma: Kind2>) => Kind2> export function chain( M: Monad1, S: Semigroup ): (f: (a: A) => Kind>) => (ma: Kind>) => Kind> export function chain( M: Monad, S: Semigroup ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> export function chain( M: Monad, S: Semigroup ): (f: (a: A) => HKT>) => (ma: HKT>) => HKT> { const _left = left(M) return (f) => (ma) => M.chain( ma, T.match(_left, f, (e1, a) => M.map( f(a), T.match( (e2) => T.left(S.concat(e1, e2)), (b) => T.both(e1, b), (e2, b) => T.both(S.concat(e1, e2), b) ) ) ) ) } /** * @since 2.10.0 */ export function bimap( F: Functor3 ): ( f: (e: E) => G, g: (a: A) => B ) => (fea: Kind3>) => Kind3> export function bimap( F: Functor3C ): ( f: (e: E) => G, g: (a: A) => B ) => (fea: Kind3>) => Kind3> export function bimap( F: Functor2 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2>) => Kind2> export function bimap( F: Functor2C ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2>) => Kind2> export function bimap( F: Functor1 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind>) => Kind> export function bimap( F: Functor ): (f: (e: E) => G, g: (a: A) => B) => (fea: HKT>) => HKT> export function bimap( F: Functor ): (f: (e: E) => G, g: (a: A) => B) => (fea: HKT>) => HKT> { return (f, g) => (fea) => F.map(fea, T.bimap(f, g)) } /** * @since 2.10.0 */ export function mapLeft( F: Functor3 ): (f: (e: E) => G) => (fea: Kind3>) => Kind3> export function mapLeft( F: Functor3C ): (f: (e: E) => G) => (fea: Kind3>) => Kind3> export function mapLeft( F: Functor2 ): (f: (e: E) => G) => (fea: Kind2>) => Kind2> export function mapLeft( F: Functor2C ): (f: (e: E) => G) => (fea: Kind2>) => Kind2> export function mapLeft( F: Functor1 ): (f: (e: E) => G) => (fea: Kind>) => Kind> export function mapLeft( F: Functor ): (f: (e: E) => G) => (fea: HKT>) => HKT> export function mapLeft( F: Functor ): (f: (e: E) => G) => (fea: HKT>) => HKT> { return (f) => (fea) => F.map(fea, T.mapLeft(f)) } /** * @since 2.10.0 */ export function match( F: Functor3 ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind3>) => Kind3 export function match( F: Functor3C ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind3>) => Kind3 export function match( F: Functor2 ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind2>) => Kind2 export function match( F: Functor2C ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind2>) => Kind2 export function match( F: Functor1 ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: Kind>) => Kind export function match( F: Functor ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: HKT>) => HKT export function match( F: Functor ): ( onLeft: (e: E) => B, onRight: (a: A) => B, onBoth: (e: E, a: A) => B ) => (ma: HKT>) => HKT { return (onLeft, onRight, onBoth) => (ma) => F.map(ma, T.match(onLeft, onRight, onBoth)) } /** * @since 2.10.0 */ export function matchE( M: Chain3 ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3, onBoth: (e: E, a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export function matchE( M: Chain3C ): ( onLeft: (e: E) => Kind3, onRight: (a: A) => Kind3, onBoth: (e: E, a: A) => Kind3 ) => (ma: Kind3>) => Kind3 export function matchE( M: Chain2 ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2, onBoth: (e: E, a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export function matchE( M: Chain2C ): ( onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2, onBoth: (e: E, a: A) => Kind2 ) => (ma: Kind2>) => Kind2 export function matchE( M: Chain1 ): ( onLeft: (e: E) => Kind, onRight: (a: A) => Kind, onBoth: (e: E, a: A) => Kind ) => (ma: Kind>) => Kind export function matchE( M: Chain ): ( onLeft: (e: E) => HKT, onRight: (a: A) => HKT, onBoth: (e: E, a: A) => HKT ) => (ma: HKT>) => HKT export function matchE( M: Chain ): ( onLeft: (e: E) => HKT, onRight: (a: A) => HKT, onBoth: (e: E, a: A) => HKT ) => (ma: HKT>) => HKT { return (onLeft, onRight, onBoth) => (ma) => M.chain(ma, T.match(onLeft, onRight, onBoth)) } /** * @since 2.10.0 */ export function swap( F: Functor3 ): (ma: Kind3>) => Kind3> export function swap( F: Functor3C ): (ma: Kind3>) => Kind3> export function swap( F: Functor2 ): (ma: Kind2>) => Kind2> export function swap( F: Functor2C ): (ma: Kind2>) => Kind2> export function swap(F: Functor1): (ma: Kind>) => Kind> export function swap(F: Functor): (ma: HKT>) => HKT> export function swap(F: Functor): (ma: HKT>) => HKT> { return (ma) => F.map(ma, T.swap) } /** * @since 2.10.0 */ export function toTuple2( F: Functor3 ): (e: LazyArg, a: LazyArg) => (fa: Kind3>) => Kind3 export function toTuple2( F: Functor3C ): (e: LazyArg, a: LazyArg) => (fa: Kind3>) => Kind3 export function toTuple2( F: Functor2 ): (e: LazyArg, a: LazyArg) => (fa: Kind2>) => Kind2 export function toTuple2( F: Functor2C ): (e: LazyArg, a: LazyArg) => (fa: Kind2>) => Kind2 export function toTuple2( F: Functor1 ): (e: LazyArg, a: LazyArg) => (fa: Kind>) => Kind export function toTuple2( F: Functor ): (e: LazyArg, a: LazyArg) => (fa: HKT>) => HKT export function toTuple2( F: Functor ): (e: LazyArg, a: LazyArg) => (fa: HKT>) => HKT { return (e, a) => (fa) => F.map(fa, T.toTuple2(e, a)) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.4.0 * @deprecated */ export interface TheseT extends HKT> {} /** * @category zone of death * @since 2.4.0 * @deprecated */ export interface TheseM { readonly map: (fa: TheseT, f: (a: A) => B) => TheseT readonly bimap: (fa: TheseT, f: (e: E) => N, g: (a: A) => B) => TheseT readonly mapLeft: (fa: TheseT, f: (e: E) => N) => TheseT readonly fold: ( fa: TheseT, onLeft: (e: E) => HKT, onRight: (a: A) => HKT, onBoth: (e: E, a: A) => HKT ) => HKT readonly swap: (fa: TheseT) => TheseT readonly rightM: (ma: HKT) => TheseT readonly leftM: (me: HKT) => TheseT readonly left: (e: E) => TheseT readonly right: (a: A) => TheseT readonly both: (e: E, a: A) => TheseT readonly toTuple: (fa: TheseT, e: E, a: A) => HKT readonly getMonad: (S: Semigroup) => { readonly _E: E readonly map: (ma: TheseT, f: (a: A) => B) => TheseT readonly of: (a: A) => TheseT readonly ap: (mab: TheseT B>, ma: TheseT) => TheseT readonly chain: (ma: TheseT, f: (a: A) => TheseT) => TheseT } } /** * @category zone of death * @since 2.4.0 * @deprecated */ export type TheseT1 = Kind> /** * @category zone of death * @since 2.4.0 * @deprecated */ export interface TheseM1 { readonly map: (fa: TheseT1, f: (a: A) => B) => TheseT1 readonly bimap: (fa: TheseT1, f: (e: E) => N, g: (a: A) => B) => TheseT1 readonly mapLeft: (fa: TheseT1, f: (e: E) => N) => TheseT1 readonly fold: ( fa: TheseT1, onLeft: (e: E) => Kind, onRight: (a: A) => Kind, onBoth: (e: E, a: A) => Kind ) => Kind readonly swap: (fa: TheseT1) => TheseT1 readonly rightM: (ma: Kind) => TheseT1 readonly leftM: (me: Kind) => TheseT1 readonly left: (e: E) => TheseT1 readonly right: (a: A) => TheseT1 readonly both: (e: E, a: A) => TheseT1 readonly toTuple: (fa: TheseT1, e: E, a: A) => Kind readonly getMonad: (S: Semigroup) => { readonly _E: E readonly map: (ma: TheseT1, f: (a: A) => B) => TheseT1 readonly of: (a: A) => TheseT1 readonly ap: (mab: TheseT1 B>, ma: TheseT1) => TheseT1 readonly chain: (ma: TheseT1, f: (a: A) => TheseT1) => TheseT1 } } /** * @category zone of death * @since 2.4.0 * @deprecated */ export type TheseT2 = Kind2> /** * @category zone of death * @since 2.4.0 * @deprecated */ export interface TheseM2 { readonly map: (fa: TheseT2, f: (a: A) => B) => TheseT2 readonly bimap: (fa: TheseT2, f: (e: E) => N, g: (a: A) => B) => TheseT2 readonly mapLeft: (fa: TheseT2, f: (e: E) => N) => TheseT2 readonly fold: ( fa: TheseT2, onLeft: (e: E) => Kind2, onRight: (a: A) => Kind2, onBoth: (e: E, a: A) => Kind2 ) => Kind2 readonly swap: (fa: TheseT2) => TheseT2 readonly rightM: (ma: Kind2) => TheseT2 readonly leftM: (me: Kind2) => TheseT2 readonly left: (e: E) => TheseT2 readonly right: (a: A) => TheseT2 readonly both: (e: E, a: A) => TheseT2 readonly toTuple: (fa: TheseT2, e: E, a: A) => Kind2 readonly getMonad: (S: Semigroup) => { readonly _E: E readonly map: (ma: TheseT2, f: (a: A) => B) => TheseT2 readonly of: (a: A) => TheseT2 readonly ap: (mab: TheseT2 B>, ma: TheseT2) => TheseT2 readonly chain: (ma: TheseT2, f: (a: A) => TheseT2) => TheseT2 } } /** * @category zone of death * @since 2.4.0 * @deprecated */ export function getTheseM(M: Monad2): TheseM2 /** @deprecated */ export function getTheseM(M: Monad1): TheseM1 /** @deprecated */ export function getTheseM(M: Monad): TheseM /** @deprecated */ /* istanbul ignore next */ export function getTheseM(M: Monad): TheseM { const _map = map(M) const _bimap = bimap(M) const _mapLeft = mapLeft(M) const _fold = matchE(M) const _toTuple2: (e: LazyArg, a: LazyArg) => (fa: HKT>) => HKT = toTuple2( M ) as any const of = right(M) const mapT = (fa: TheseT, f: (a: A) => B): TheseT => pipe(fa, _map(f)) return { map: mapT, bimap: (fea, f, g) => pipe(fea, _bimap(f, g)), mapLeft: (fea, f) => pipe(fea, _mapLeft(f)), fold: (fa, onLeft, onRight, onBoth) => pipe(fa, _fold(onLeft, onRight, onBoth)), swap: swap(M), rightM: rightF(M), leftM: leftF(M), left: left(M), right: right(M), both: both(M), toTuple: (fa, e, a) => pipe( fa, _toTuple2( () => e, () => a ) ), getMonad: (S) => { const _ap = ap(M, S) const _chain = chain(M, S) return { _E: undefined as any, map: mapT, of, ap: (fab, fa) => pipe(fab, _ap(fa)), chain: (ma, f) => pipe(ma, _chain(f)) } } } } ================================================ FILE: src/Traced.ts ================================================ /** * @since 2.0.0 */ import { Comonad2C } from './Comonad' import { pipe } from './function' import { flap as flap_, Functor2 } from './Functor' import { Monoid } from './Monoid' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Traced { (p: P): A } // TODO: curry in v3 /** * Extracts a value at a relative position which depends on the current value. * * @since 2.0.0 */ export function tracks(M: Monoid

, f: (a: A) => P): (wa: Traced) => A { return (wa) => wa(f(wa(M.empty))) } /** * Get the current position * * @since 2.0.0 */ export function listen(wa: Traced): Traced { return (e) => [wa(e), e] } /** * Get a value which depends on the current position * * @since 2.0.0 */ export function listens(f: (p: P) => B): (wa: Traced) => Traced { return (wa) => (e) => [wa(e), f(e)] } /** * Apply a function to the current position * * @since 2.0.0 */ export function censor

(f: (p: P) => P): (wa: Traced) => Traced { return (wa) => (e) => wa(f(e)) } /** * @category instances * @since 2.0.0 */ export function getComonad

(monoid: Monoid

): Comonad2C { function extend(wa: Traced, f: (wa: Traced) => B): Traced { return (p1) => f((p2) => wa(monoid.concat(p1, p2))) } function extract(wa: Traced): A { return wa(monoid.empty) } return { URI, _E: undefined as any, map: _map, extend, extract } } /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Traced) => Traced = (f) => (fa) => (p) => f(fa(p)) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Traced' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Traced } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`Functor`](#functor) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const traced: Functor2 = Functor ================================================ FILE: src/Traversable.ts ================================================ /** * `Traversable` represents data structures which can be _traversed_ accumulating results and effects in some * `Applicative` functor. * * - `traverse` runs an action for every element in a data structure, and accumulates the results. * - `sequence` runs the actions _contained_ in a data structure, and accumulates the results. * * The `traverse` and `sequence` functions should be compatible in the following sense: * * - `traverse(A)(xs, f) <-> sequence(A)(A.map(xs, f))` * - `sequence(A)(xs) <-> traverse(A)(xs, identity)` * * where `A` is an `Applicative` instance * * `Traversable` instances should also be compatible with the corresponding `Foldable` instances, in the following sense: * * ```ts * import { getApplicative, make } from 'fp-ts/Const' * * const A = getApplicative(M) * * foldMap(M)(xs, f) = traverse(A)(xs, a => make(f(a))) * ``` * * where `M` is a `Monoid` instance * * @since 2.0.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C, Applicative4 } from './Applicative' import { Foldable, Foldable1, Foldable2, Foldable2C, Foldable3, FoldableComposition, FoldableComposition11, getFoldableComposition } from './Foldable' import { pipe } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, FunctorComposition, FunctorComposition11, getFunctorComposition } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Traversable extends Functor, Foldable { /** * Runs an action for every element in a data structure and accumulates the results */ readonly traverse: Traverse readonly sequence: Sequence } /** * @category model * @since 2.0.0 */ export interface Traversable1 extends Functor1, Foldable1 { readonly traverse: Traverse1 readonly sequence: Sequence1 } /** * @category model * @since 2.0.0 */ export interface Traversable2 extends Functor2, Foldable2 { readonly traverse: Traverse2 readonly sequence: Sequence2 } /** * @category model * @since 2.0.0 */ export interface Traversable2C extends Functor2C, Foldable2C { readonly traverse: Traverse2C readonly sequence: Sequence2C } /** * @category model * @since 2.0.0 */ export interface Traversable3 extends Functor3, Foldable3 { readonly traverse: Traverse3 readonly sequence: Sequence3 } /** * @since 2.0.0 */ export interface Traverse { (F: Applicative4): ( ta: HKT, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: HKT, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: HKT, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): (ta: HKT, f: (a: A) => Kind2) => Kind2> (F: Applicative2C): ( ta: HKT, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: HKT, f: (a: A) => Kind) => Kind> (F: Applicative): (ta: HKT, f: (a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface Traverse1 { (F: Applicative4): ( ta: Kind, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: Kind, f: (a: A) => Kind) => Kind> (F: Applicative): (ta: Kind, f: (a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface Traverse2 { (F: Applicative4): ( ta: Kind2, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface Traverse2C { (F: Applicative4): ( ta: Kind2, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind2, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: Kind2, f: (a: A) => Kind) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface Traverse3 { (F: Applicative4): ( ta: Kind3, f: (a: A) => Kind4 ) => Kind4> (F: Applicative3): ( ta: Kind3, f: (a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind3, f: (a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind3, f: (a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind3, f: (a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind3, f: (a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind3, f: (a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface Sequence { (F: Applicative4): (ta: HKT>) => Kind4> (F: Applicative3): (ta: HKT>) => Kind3> (F: Applicative3C): (ta: HKT>) => Kind3> (F: Applicative2): (ta: HKT>) => Kind2> (F: Applicative2C): (ta: HKT>) => Kind2> (F: Applicative1): (ta: HKT>) => Kind> (F: Applicative): (ta: HKT>) => HKT> } /** * @since 2.0.0 */ export interface Sequence1 { (F: Applicative4): ( ta: Kind> ) => Kind4> (F: Applicative3): (ta: Kind>) => Kind3> (F: Applicative3C): (ta: Kind>) => Kind3> (F: Applicative2): (ta: Kind>) => Kind2> (F: Applicative2C): (ta: Kind>) => Kind2> (F: Applicative1): (ta: Kind>) => Kind> (F: Applicative): (ta: Kind>) => HKT> } /** * @since 2.0.0 */ export interface Sequence2 { (F: Applicative4): ( ta: Kind2> ) => Kind4> (F: Applicative3): ( ta: Kind2> ) => Kind3> (F: Applicative3C): ( ta: Kind2> ) => Kind3> (F: Applicative2): (ta: Kind2>) => Kind2> (F: Applicative2C): ( ta: Kind2> ) => Kind2> (F: Applicative1): (ta: Kind2>) => Kind> (F: Applicative): (ta: Kind2>) => HKT> } /** * @since 2.0.0 */ export interface Sequence2C { (F: Applicative4): ( ta: Kind2> ) => Kind4> (F: Applicative3): ( ta: Kind2> ) => Kind3> (F: Applicative3C): ( ta: Kind2> ) => Kind3> (F: Applicative2): (ta: Kind2>) => Kind2> (F: Applicative2C): (ta: Kind2>) => Kind2> (F: Applicative1): (ta: Kind2>) => Kind> (F: Applicative): (ta: Kind2>) => HKT> } /** * @since 2.0.0 */ export interface Sequence3 { (F: Applicative4): ( ta: Kind3> ) => Kind4> (F: Applicative3): ( ta: Kind3> ) => Kind3> (F: Applicative3C): ( ta: Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind3> ) => Kind2> (F: Applicative2C): ( ta: Kind3> ) => Kind2> (F: Applicative1): (ta: Kind3>) => Kind> (F: Applicative): (ta: Kind3>) => HKT> } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * `traverse` composition. * * @since 2.10.0 */ export function traverse( T: Traversable1, G: Traversable2 ): { (F: Applicative4): ( f: (a: A) => Kind4 ) => (tga: Kind>) => Kind4>> (F: Applicative3): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative3C): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative2): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative1): ( f: (a: A) => Kind ) => (tga: Kind>) => Kind>> (F: Applicative): ( f: (a: A) => HKT ) => (tga: Kind>) => HKT>> } export function traverse( T: Traversable1, G: Traversable1 ): { (F: Applicative4): ( f: (a: A) => Kind4 ) => (tga: Kind>) => Kind4>> (F: Applicative3): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative3C): ( f: (a: A) => Kind3 ) => (tga: Kind>) => Kind3>> (F: Applicative2): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (tga: Kind>) => Kind2>> (F: Applicative1): ( f: (a: A) => Kind ) => (tga: Kind>) => Kind>> (F: Applicative): (f: (a: A) => HKT) => (tga: Kind>) => HKT>> } export function traverse( T: Traversable, G: Traversable ): (F: Applicative) => (f: (a: A) => HKT) => (tga: HKT>) => HKT>> export function traverse( T: Traversable, G: Traversable ): (F: Applicative) => (f: (a: A) => HKT) => (tga: HKT>) => HKT>> { return (F) => { const traverseT = T.traverse(F) const traverseG = G.traverse(F) return (f) => (fga) => traverseT(fga, (ga) => traverseG(ga, f)) } } /** * `sequence` composition. * * @since 2.10.0 */ export function sequence( T: Traversable1, G: Traversable2 ): { (F: Applicative4): ( tgfa: Kind>> ) => Kind4>> (F: Applicative3): ( tgfa: Kind>> ) => Kind3>> (F: Applicative3C): ( tgfa: Kind>> ) => Kind3>> (F: Applicative2): ( tgfa: Kind>> ) => Kind2>> (F: Applicative2C): ( tgfa: Kind>> ) => Kind2>> (F: Applicative1): ( tgfa: Kind>> ) => Kind>> (F: Applicative): (tgfa: HKT>>) => HKT>> } export function sequence( T: Traversable1, G: Traversable1 ): { (F: Applicative4): ( tgfa: Kind>> ) => Kind4>> (F: Applicative3): ( tgfa: Kind>> ) => Kind3>> (F: Applicative3C): ( tgfa: Kind>> ) => Kind3>> (F: Applicative2): ( tgfa: Kind>> ) => Kind2>> (F: Applicative2C): ( tgfa: Kind>> ) => Kind2>> (F: Applicative1): (tgfa: Kind>>) => Kind>> (F: Applicative): (tgfa: HKT>>) => HKT>> } export function sequence( T: Traversable, G: Traversable ): (F: Applicative) => (tgfa: HKT>>) => HKT>> export function sequence( T: Traversable, G: Traversable ): (F: Applicative) => (tgfa: HKT>>) => HKT>> { return (F) => { const sequenceT = T.sequence(F) const sequenceG = G.sequence(F) return (fgha) => sequenceT(T.map(fgha, sequenceG)) } } // // pipeable `Traverse` // /** * @since 2.6.3 */ export interface PipeableTraverse1 { (F: Applicative3): ( f: (a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative3C): ( f: (a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative1): (f: (a: A) => Kind) => (ta: Kind) => Kind> (F: Applicative): (f: (a: A) => HKT) => (ta: Kind) => HKT> } /** * @since 2.6.3 */ export interface PipeableTraverse2 { (F: Applicative3): ( f: (a: A) => Kind3 ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (a: A) => Kind ) => (ta: Kind2) => Kind> (F: Applicative): (f: (a: A) => HKT) => (ta: Kind2) => HKT> } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface TraversableComposition extends FoldableComposition, FunctorComposition { readonly traverse: ( H: Applicative ) => (fga: HKT>, f: (a: A) => HKT) => HKT>> readonly sequence: (H: Applicative) => (fga: HKT>>) => HKT>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface TraverseComposition11 { (H: Applicative3): ( fga: Kind>, f: (a: A) => Kind3 ) => Kind3>> (H: Applicative2): ( fga: Kind>, f: (a: A) => Kind2 ) => Kind2>> (H: Applicative2C): ( fga: Kind>, f: (a: A) => Kind2 ) => Kind2>> (H: Applicative1): ( fga: Kind>, f: (a: A) => Kind ) => Kind>> (H: Applicative): (fga: Kind>, f: (a: A) => HKT) => HKT>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface SequenceComposition11 { (H: Applicative3): ( fga: Kind>> ) => Kind3>> (H: Applicative2): ( fga: Kind>> ) => Kind2>> (H: Applicative2C): ( fga: Kind>> ) => Kind2>> (H: Applicative1): (fga: Kind>>) => Kind>> (H: Applicative): (fga: Kind>>) => HKT>> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface TraversableComposition11 extends FoldableComposition11, FunctorComposition11 { readonly traverse: TraverseComposition11 readonly sequence: SequenceComposition11 } /** * Use * - [`traverse`](#traverse) * - [`sequence`](#sequence) * * instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getTraversableComposition( F: Traversable1, G: Traversable1 ): TraversableComposition11 /** @deprecated */ export function getTraversableComposition(F: Traversable, G: Traversable): TraversableComposition /** @deprecated */ export function getTraversableComposition(F: Traversable, G: Traversable): TraversableComposition { const map = getFunctorComposition(F, G).map const FC = getFoldableComposition(F, G) const _traverse = traverse(F, G) const _sequence = sequence(F, G) return { map, reduce: FC.reduce, foldMap: FC.foldMap, reduceRight: FC.reduceRight, traverse: (H) => { const traverseH = _traverse(H) return (fga, f) => pipe(fga, traverseH(f)) }, sequence: (H) => { const sequenceH = _sequence(H) return (fgha) => pipe(fgha, sequenceH) } } } ================================================ FILE: src/TraversableWithIndex.ts ================================================ /** * A `Traversable` with an additional index. * A `TraversableWithIndex` instance must be compatible with its `Traversable` instance * * ```ts * traverse(F)(ta, f) = traverseWithIndex(F)(ta, (_, a) => f(a)) * ``` * * with its `FoldableWithIndex` instance * * ```ts * foldMapWithIndex(M)(ta, f) = traverseWithIndex(getApplicative(M))(ta, (i, a) => new Const(f(i, a))).value * ``` * * and with its `FunctorWithIndex` instance * * ```purescript * mapWithIndex(ta, f) = traverseWithIndex(identity)(ta, (i, a) => new Identity(f(i, a))).value * ``` * * @since 2.0.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C } from './Applicative' import { FoldableWithIndex, FoldableWithIndex1, FoldableWithIndex2, FoldableWithIndex2C } from './FoldableWithIndex' import { FunctorWithIndex, FunctorWithIndex1, FunctorWithIndex2, FunctorWithIndex2C } from './FunctorWithIndex' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import { Traversable, Traversable1, Traversable2, Traversable2C } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export interface TraversableWithIndex extends FunctorWithIndex, FoldableWithIndex, Traversable { readonly traverseWithIndex: TraverseWithIndex } /** * @since 2.0.0 */ export interface TraversableWithIndex1 extends FunctorWithIndex1, FoldableWithIndex1, Traversable1 { readonly traverseWithIndex: TraverseWithIndex1 } /** * @since 2.0.0 */ export interface TraversableWithIndex2 extends FunctorWithIndex2, FoldableWithIndex2, Traversable2 { readonly traverseWithIndex: TraverseWithIndex2 } /** * @since 2.0.0 */ export interface TraversableWithIndex2C extends FunctorWithIndex2C, FoldableWithIndex2C, Traversable2C { readonly traverseWithIndex: TraverseWithIndex2C } /** * @since 2.0.0 */ export interface TraverseWithIndex { (F: Applicative3): ( ta: HKT, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: HKT, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: HKT, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: HKT, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: HKT, f: (i: I, a: A) => Kind) => Kind> (F: Applicative): (ta: HKT, f: (i: I, a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface TraverseWithIndex1 { (F: Applicative3): ( ta: Kind, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): (ta: Kind, f: (i: I, a: A) => Kind) => Kind> (F: Applicative): (ta: Kind, f: (i: I, a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface TraverseWithIndex2 { (F: Applicative3): ( ta: Kind2, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (i: I, a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind2, f: (i: I, a: A) => HKT) => HKT> } /** * @since 2.0.0 */ export interface TraverseWithIndex2C { (F: Applicative3): ( ta: Kind2, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative3C): ( ta: Kind2, f: (i: I, a: A) => Kind3 ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (i: I, a: A) => Kind2 ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (i: I, a: A) => Kind ) => Kind> (F: Applicative): (ta: Kind2, f: (i: I, a: A) => HKT) => HKT> } // // pipeable `TraverseWithIndex` // /** * @since 2.6.3 */ export interface PipeableTraverseWithIndex1 { (F: Applicative3): ( f: (i: I, a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative3C): ( f: (i: I, a: A) => Kind3 ) => (ta: Kind) => Kind3> (F: Applicative2): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative2C): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind) => Kind2> (F: Applicative1): (f: (i: I, a: A) => Kind) => (ta: Kind) => Kind> (F: Applicative): (f: (i: I, a: A) => HKT) => (ta: Kind) => HKT> } /** * @since 2.6.3 */ export interface PipeableTraverseWithIndex2 { (F: Applicative3): ( f: (i: I, a: A) => Kind3 ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (i: I, a: A) => Kind2 ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (i: I, a: A) => Kind ) => (ta: Kind2) => Kind> (F: Applicative): (f: (i: I, a: A) => HKT) => (ta: Kind2) => HKT> } ================================================ FILE: src/Tree.ts ================================================ /** * Multi-way trees (aka rose trees) and forests, where a forest is * * ```ts * type Forest = Array> * ``` * * @since 2.0.0 */ import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative' import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply' import * as A from './Array' import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain' import { Comonad1 } from './Comonad' import { Eq, fromEquals } from './Eq' import { Extend1 } from './Extend' import { Foldable1 } from './Foldable' import { dual, identity, pipe } from './function' import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import * as _ from './internal' import { Monad as MonadHKT, Monad1, Monad2, Monad2C, Monad3, Monad3C, Monad4 } from './Monad' import { Monoid } from './Monoid' import { Pointed1 } from './Pointed' import { Predicate } from './Predicate' import { Show } from './Show' import { PipeableTraverse1, Traversable1 } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export type Forest = Array> /** * @category model * @since 2.0.0 */ export interface Tree { readonly value: A readonly forest: Forest } /** * @category constructors * @since 2.0.0 */ export function make(value: A, forest: Forest = []): Tree { return { value, forest } } /** * @category instances * @since 2.0.0 */ export function getShow(S: Show): Show> { const show = (t: Tree): string => { return A.isEmpty(t.forest) ? `make(${S.show(t.value)})` : `make(${S.show(t.value)}, [${t.forest.map(show).join(', ')}])` } return { show } } /** * @category instances * @since 2.0.0 */ export function getEq(E: Eq): Eq> { // eslint-disable-next-line prefer-const let SA: Eq>> const R: Eq> = fromEquals((x, y) => E.equals(x.value, y.value) && SA.equals(x.forest, y.forest)) SA = A.getEq(R) return R } const draw = (indentation: string, forest: Forest): string => { let r = '' const len = forest.length let tree: Tree for (let i = 0; i < len; i++) { tree = forest[i] const isLast = i === len - 1 r += indentation + (isLast ? '└' : '├') + '─ ' + tree.value r += draw(indentation + (len > 1 && !isLast ? '│ ' : ' '), tree.forest) } return r } /** * Neat 2-dimensional drawing of a forest * * @since 2.0.0 */ export function drawForest(forest: Forest): string { return draw('\n', forest) } /** * Neat 2-dimensional drawing of a tree * * @example * import { make, drawTree } from 'fp-ts/Tree' * * const fa = make('a', [ * make('b'), * make('c'), * make('d', [make('e'), make('f')]) * ]) * * assert.strictEqual(drawTree(fa), `a * ├─ b * ├─ c * └─ d * ├─ e * └─ f`) * * * @since 2.0.0 */ export function drawTree(tree: Tree): string { return tree.value + drawForest(tree.forest) } /** * Build a (possibly infinite) tree from a seed value in breadth-first order. * * @category constructors * @since 2.0.0 */ export function unfoldTree(b: B, f: (b: B) => [A, Array]): Tree { const [a, bs] = f(b) return { value: a, forest: unfoldForest(bs, f) } } /** * Build a (possibly infinite) forest from a list of seed values in breadth-first order. * * @category constructors * @since 2.0.0 */ export function unfoldForest(bs: Array, f: (b: B) => [A, Array]): Forest { return bs.map((b) => unfoldTree(b, f)) } /** * Monadic tree builder, in depth-first order * * @category constructors * @since 2.0.0 */ export function unfoldTreeM( M: Monad4 ): (b: B, f: (b: B) => Kind4]>) => Kind4> export function unfoldTreeM( M: Monad3 ): (b: B, f: (b: B) => Kind3]>) => Kind3> export function unfoldTreeM( M: Monad3C ): (b: B, f: (b: B) => Kind3]>) => Kind3> export function unfoldTreeM( M: Monad2 ): (b: B, f: (b: B) => Kind2]>) => Kind2> export function unfoldTreeM( M: Monad2C ): (b: B, f: (b: B) => Kind2]>) => Kind2> export function unfoldTreeM( M: Monad1 ): (b: B, f: (b: B) => Kind]>) => Kind> export function unfoldTreeM(M: MonadHKT): (b: B, f: (b: B) => HKT]>) => HKT> export function unfoldTreeM(M: MonadHKT): (b: B, f: (b: B) => HKT]>) => HKT> { const unfoldForestMM = unfoldForestM(M) return (b, f) => M.chain(f(b), ([a, bs]) => M.map(unfoldForestMM(bs, f), (ts) => ({ value: a, forest: ts }))) } /** * Monadic forest builder, in depth-first order * * @category constructors * @since 2.0.0 */ export function unfoldForestM( M: Monad4 ): (bs: Array, f: (b: B) => Kind4]>) => Kind4> export function unfoldForestM( M: Monad3 ): (bs: Array, f: (b: B) => Kind3]>) => Kind3> export function unfoldForestM( M: Monad3C ): (bs: Array, f: (b: B) => Kind3]>) => Kind3> export function unfoldForestM( M: Monad2 ): (bs: Array, f: (b: B) => Kind2]>) => Kind2> export function unfoldForestM( M: Monad2C ): (bs: Array, f: (b: B) => Kind2]>) => Kind2> export function unfoldForestM( M: Monad1 ): (bs: Array, f: (b: B) => Kind]>) => Kind> export function unfoldForestM( M: MonadHKT ): (bs: Array, f: (b: B) => HKT]>) => HKT> export function unfoldForestM( M: MonadHKT ): (bs: Array, f: (b: B) => HKT]>) => HKT> { const traverseM = A.traverse(M) return (bs, f) => pipe( bs, traverseM((b) => unfoldTreeM(M)(b, f)) ) } /** * Fold a tree into a "summary" value in depth-first order. * * For each node in the tree, apply `f` to the `value` and the result of applying `f` to each `forest`. * * This is also known as the catamorphism on trees. * * @example * import { fold, make } from 'fp-ts/Tree' * import { concatAll } from 'fp-ts/Monoid' * import { MonoidSum } from 'fp-ts/number' * * const t = make(1, [make(2), make(3)]) * * const sum = concatAll(MonoidSum) * * // Sum the values in a tree: * assert.deepStrictEqual(fold((a: number, bs: Array) => a + sum(bs))(t), 6) * * // Find the maximum value in the tree: * assert.deepStrictEqual(fold((a: number, bs: Array) => bs.reduce((b, acc) => Math.max(b, acc), a))(t), 3) * * // Count the number of leaves in the tree: * assert.deepStrictEqual(fold((_: number, bs: Array) => (bs.length === 0 ? 1 : sum(bs)))(t), 2) * * @category folding * @since 2.6.0 */ export function fold(f: (a: A, bs: Array) => B): (tree: Tree) => B { const go = (tree: Tree): B => f(tree.value, tree.forest.map(go)) return go } /* istanbul ignore next */ const _map: Monad1['map'] = (fa, f) => pipe(fa, map(f)) const _ap: Monad1['ap'] = (fab, fa) => flatMap(fab, (f) => pipe(fa, map(f))) /* istanbul ignore next */ const _reduce = (fa: Tree, b: B, f: (b: B, a: A) => B): B => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable1['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight = (fa: Tree, b: B, f: (a: A, b: B) => B): B => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ const _extend: Extend1['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _traverse = (F: ApplicativeHKT): ((ta: Tree, f: (a: A) => HKT) => HKT>) => { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /** * @since 2.0.0 */ export const ap: (fa: Tree) => (fab: Tree<(a: A) => B>) => Tree = (fa) => (fab) => _ap(fab, fa) /** * @category sequencing * @since 2.14.0 */ export const flatMap: { (f: (a: A) => Tree): (ma: Tree) => Tree (ma: Tree, f: (a: A) => Tree): Tree } = /*#__PURE__*/ dual(2, (ma: Tree, f: (a: A) => Tree): Tree => { const { value, forest } = f(ma.value) const concat = A.getMonoid>().concat return { value, forest: concat(forest, ma.forest.map(flatMap(f))) } }) /** * @since 2.0.0 */ export const extend: (f: (wa: Tree) => B) => (wa: Tree) => Tree = (f) => (wa) => ({ value: f(wa), forest: wa.forest.map(extend(f)) }) /** * @since 2.0.0 */ export const duplicate: (wa: Tree) => Tree> = /*#__PURE__*/ extend(identity) /** * @category sequencing * @since 2.0.0 */ export const flatten: (mma: Tree>) => Tree = /*#__PURE__*/ flatMap(identity) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Tree) => Tree = (f) => (fa) => ({ value: f(fa.value), forest: fa.forest.map(map(f)) }) /** * @category folding * @since 2.0.0 */ export const reduce = (b: B, f: (b: B, a: A) => B) => (fa: Tree): B => { let r: B = f(b, fa.value) const len = fa.forest.length for (let i = 0; i < len; i++) { r = pipe(fa.forest[i], reduce(r, f)) } return r } /** * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Tree) => M = (M) => (f) => reduce(M.empty, (acc, a) => M.concat(acc, f(a))) /** * @category folding * @since 2.0.0 */ export const reduceRight = (b: B, f: (a: A, b: B) => B) => (fa: Tree): B => { let r: B = b const len = fa.forest.length for (let i = len - 1; i >= 0; i--) { r = pipe(fa.forest[i], reduceRight(r, f)) } return f(fa.value, r) } /** * @category Extract * @since 2.6.2 */ export const extract: (wa: Tree) => A = (wa) => wa.value /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse1 = ( F: ApplicativeHKT ): ((f: (a: A) => HKT) => (ta: Tree) => HKT>) => { const traverseF = A.traverse(F) const out = (f: (a: A) => HKT) => (ta: Tree): HKT> => F.ap( F.map(f(ta.value), (value: B) => (forest: Forest) => ({ value, forest })), pipe(ta.forest, traverseF(out(f))) ) return out } /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable1['sequence'] = ( F: ApplicativeHKT ): ((ta: Tree>) => HKT>) => traverse(F)(identity) /** * @category constructors * @since 2.7.0 */ export const of: (a: A) => Tree = (a) => make(a) /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Tree' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind { readonly [URI]: Tree } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor1 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.10.0 */ export const Pointed: Pointed1 = { URI, of } /** * @category instances * @since 2.10.0 */ export const Apply: Apply1 = { URI, map: _map, ap: _ap } /** * Combine two effectful actions, keeping only the result of the first. * * @since 2.0.0 */ export const apFirst = /*#__PURE__*/ apFirst_(Apply) /** * Combine two effectful actions, keeping only the result of the second. * * @since 2.0.0 */ export const apSecond = /*#__PURE__*/ apSecond_(Apply) /** * @category instances * @since 2.7.0 */ export const Applicative: Applicative1 = { URI, map: _map, ap: _ap, of } /** * @category instances * @since 2.10.0 */ export const Chain: Chain1 = { URI, map: _map, ap: _ap, chain: flatMap } /** * @category instances * @since 2.7.0 */ export const Monad: Monad1 = { URI, map: _map, ap: _ap, of, chain: flatMap } /** * Composes computations in sequence, using the return value of one computation to determine the next computation and * keeping only the result of the first. * * @since 2.0.0 */ export const chainFirst: (f: (a: A) => Tree) => (first: Tree) => Tree = /*#__PURE__*/ chainFirst_(Chain) /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable1 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable1 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad1 = { URI, map: _map, extend: _extend, extract } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 2.9.0 */ export const Do: Tree<{}> = /*#__PURE__*/ of(_.emptyRecord) /** * @category do notation * @since 2.8.0 */ export const bindTo = /*#__PURE__*/ bindTo_(Functor) const let_ = /*#__PURE__*/ let__(Functor) export { /** * @category do notation * @since 2.13.0 */ let_ as let } /** * @category do notation * @since 2.8.0 */ export const bind = /*#__PURE__*/ bind_(Chain) /** * @category do notation * @since 2.8.0 */ export const apS = /*#__PURE__*/ apS_(Apply) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export function elem(E: Eq): (a: A, fa: Tree) => boolean { const go = (a: A, fa: Tree): boolean => E.equals(a, fa.value) || fa.forest.some((tree) => go(a, tree)) return go } /** * @since 2.11.0 */ export const exists = (predicate: Predicate) => (ma: Tree): boolean => predicate(ma.value) || ma.forest.some(exists(predicate)) // ------------------------------------------------------------------------------------- // legacy // ------------------------------------------------------------------------------------- /** * Alias of `flatMap`. * * @category legacy * @since 2.0.0 */ export const chain: (f: (a: A) => Tree) => (ma: Tree) => Tree = flatMap // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.tree` * (where `T` is from `import T from 'fp-ts/Tree'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const tree: Monad1 & Foldable1 & Traversable1 & Comonad1 = { URI, map: _map, of, ap: _ap, chain: flatMap, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence, extract, extend: _extend } ================================================ FILE: src/Tuple.ts ================================================ /** * @since 2.0.0 */ import { Applicative, Applicative2C } from './Applicative' import { Apply2C } from './Apply' import { Bifunctor2 } from './Bifunctor' import { Chain2C } from './Chain' import { ChainRec2C } from './ChainRec' import { Comonad2 } from './Comonad' import { Either } from './Either' import { Extend2 } from './Extend' import { Foldable2 } from './Foldable' import { identity, pipe } from './function' import { flap as flap_, Functor2 } from './Functor' import { HKT } from './HKT' import { Monad2C } from './Monad' import { Monoid } from './Monoid' import * as RT from './ReadonlyTuple' import { Semigroup } from './Semigroup' import { Semigroupoid2 } from './Semigroupoid' import { PipeableTraverse2, Traversable2 } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export const fst: (ea: [A, E]) => A = RT.fst /** * @since 2.0.0 */ export const snd: (ea: [A, E]) => E = RT.snd /** * @since 2.0.0 */ export const swap = (ea: [A, E]): [E, A] => [snd(ea), fst(ea)] /** * @category instances * @since 2.0.0 */ export function getApply(S: Semigroup): Apply2C { return { URI, _E: undefined as any, map: _map, ap: (fab, fa) => [fst(fab)(fst(fa)), S.concat(snd(fab), snd(fa))] } } const of = (M: Monoid) => (a: A): [A, M] => { return [a, M.empty] } /** * @category instances * @since 2.0.0 */ export function getApplicative(M: Monoid): Applicative2C { const A = getApply(M) return { URI, _E: undefined as any, map: A.map, ap: A.ap, of: of(M) } } /** * @category instances * @since 2.0.0 */ export function getChain(S: Semigroup): Chain2C { const A = getApply(S) return { URI, _E: undefined as any, map: A.map, ap: A.ap, chain: (ma, f) => { const [b, s] = f(fst(ma)) return [b, S.concat(snd(ma), s)] } } } /** * @category instances * @since 2.0.0 */ export function getMonad(M: Monoid): Monad2C { const C = getChain(M) return { URI, _E: undefined as any, map: C.map, ap: C.ap, chain: C.chain, of: of(M) } } /** * @category instances * @since 2.0.0 */ export function getChainRec(M: Monoid): ChainRec2C { const chainRec = (a: A, f: (a: A) => [Either, M]): [B, M] => { let result: [Either, M] = f(a) let acc: M = M.empty let s: Either = fst(result) while (s._tag === 'Left') { acc = M.concat(acc, snd(result)) result = f(s.left) s = fst(result) } return [s.right, M.concat(acc, snd(result))] } const C = getChain(M) return { URI, _E: undefined as any, map: C.map, ap: C.ap, chain: C.chain, chainRec } } /* istanbul ignore next */ const _compose: Semigroupoid2['compose'] = (bc, ab) => pipe(bc, compose(ab)) /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, mapFst(f)) /* istanbul ignore next */ const _bimap: Bifunctor2['bimap'] = (fa, f, g) => pipe(fa, bimap(f, g)) /* istanbul ignore next */ const _mapLeft: Bifunctor2['mapLeft'] = (fa, f) => pipe(fa, mapSnd(f)) /* istanbul ignore next */ const _extend: Extend2['extend'] = (wa, f) => pipe(wa, extend(f)) /* istanbul ignore next */ const _reduce: Foldable2['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) /* istanbul ignore next */ const _foldMap: Foldable2['foldMap'] = (M) => { const foldMapM = foldMap(M) return (fa, f) => pipe(fa, foldMapM(f)) } /* istanbul ignore next */ const _reduceRight: Foldable2['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) /* istanbul ignore next */ function _traverse(F: Applicative): (ta: [A, S], f: (a: A) => HKT) => HKT { const traverseF = traverse(F) return (ta, f) => pipe(ta, traverseF(f)) } /** * Map a pair of functions over the two type arguments of the bifunctor. * * @category mapping * @since 2.0.0 */ export const bimap: (mapSnd: (e: E) => G, mapFst: (a: A) => B) => (fa: [A, E]) => [B, G] = (f, g) => (fa) => [g(fst(fa)), f(snd(fa))] /** * Map a function over the first component of a `Tuple`. * * This is the `map` operation of the `Functor` instance. * * @category mapping * @since 2.0.0 */ export const mapFst: (f: (a: A) => B) => (fa: [A, E]) => [B, E] = (f) => (fa) => [f(fst(fa)), snd(fa)] /** * Map a function over the second component of a `Tuple`. * * This is the `mapLeft` operation of the `Bifunctor` instance. * * @category mapping * @since 2.10.0 */ export const mapSnd: (f: (e: E) => G) => (fa: [A, E]) => [A, G] = (f) => (fa) => [fst(fa), f(snd(fa))] /** * @since 2.0.0 */ export const compose: (ab: [B, A]) => (bc: [C, B]) => [C, A] = (ab) => (bc) => [fst(bc), snd(ab)] /** * @since 2.0.0 */ export const extend: (f: (wa: [A, E]) => B) => (wa: [A, E]) => [B, E] = (f) => (wa) => [f(wa), snd(wa)] /** * @since 2.0.0 */ export const duplicate: (wa: [A, E]) => [[A, E], E] = /*#__PURE__*/ extend(identity) /** * @category Extract * @since 2.6.2 */ export const extract: (wa: [A, E]) => A = RT.extract /** * @category folding * @since 2.0.0 */ export const foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: [A, E]) => M = RT.foldMap /** * @category folding * @since 2.0.0 */ export const reduce: (b: B, f: (b: B, a: A) => B) => (fa: [A, E]) => B = RT.reduce /** * @category folding * @since 2.0.0 */ export const reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: [A, E]) => B = RT.reduceRight /** * @category traversing * @since 2.6.3 */ export const traverse: PipeableTraverse2 = ( F: Applicative ): ((f: (a: A) => HKT) => (as: [A, E]) => HKT) => { return (f) => (ta) => F.map(f(fst(ta)), (b) => [b, snd(ta)]) } /** * @category traversing * @since 2.6.3 */ export const sequence: Traversable2['sequence'] = (F: Applicative) => (fas: [HKT, E]): HKT => { return F.map(fst(fas), (a) => [a, snd(fas)]) } /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Tuple' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: [A, E] } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) /** * @category instances * @since 2.7.0 */ export const Bifunctor: Bifunctor2 = { URI, bimap: _bimap, mapLeft: _mapLeft } /** * @category instances * @since 2.7.0 */ export const Semigroupoid: Semigroupoid2 = { URI, compose: _compose } /** * @category instances * @since 2.7.0 */ export const Comonad: Comonad2 = { URI, map: _map, extend: _extend, extract } /** * @category instances * @since 2.7.0 */ export const Foldable: Foldable2 = { URI, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight } /** * @category instances * @since 2.7.0 */ export const Traversable: Traversable2 = { URI, map: _map, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`mapFst`](#mapfst) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const map: (f: (a: A) => B) => (fa: [A, E]) => [B, E] = mapFst /** * Use [`mapSnd`](#mapsnd) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const mapLeft: (f: (e: E) => G) => (fa: [A, E]) => [A, G] = mapSnd /** * This instance is deprecated, use small, specific instances instead. * For example if a function needs a `Functor` instance, pass `T.Functor` instead of `T.tuple` * (where `T` is from `import T from 'fp-ts/Tuple'`) * * @category zone of death * @since 2.0.0 * @deprecated */ export const tuple: Semigroupoid2 & Bifunctor2 & Comonad2 & Foldable2 & Traversable2 = { URI, compose: _compose, map: _map, bimap: _bimap, mapLeft: _mapLeft, extract, extend: _extend, reduce: _reduce, foldMap: _foldMap, reduceRight: _reduceRight, traverse: _traverse, sequence } ================================================ FILE: src/Unfoldable.ts ================================================ /** * This class identifies data structures which can be _unfolded_, generalizing `unfold` on arrays. * * @since 2.0.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Option } from './Option' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Unfoldable { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => HKT } /** * @category model * @since 2.0.0 */ export interface Unfoldable1 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind } /** * @category model * @since 2.0.0 */ export interface Unfoldable2 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Unfoldable2C { readonly URI: F readonly _E: E readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind2 } /** * @category model * @since 2.0.0 */ export interface Unfoldable3 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind3 } /** * @category model * @since 2.10.0 */ export interface Unfoldable3C { readonly URI: F readonly _E: E readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind3 } /** * @category model * @since 2.0.0 */ export interface Unfoldable4 { readonly URI: F readonly unfold: (b: B, f: (b: B) => Option<[A, B]>) => Kind4 } ================================================ FILE: src/ValidationT.ts ================================================ /** * @since 2.0.0 */ import { ApplicativeComposition12C, ApplicativeComposition22C, ApplicativeCompositionHKT2C, getApplicativeComposition } from './Applicative' import * as E from './Either' import { LazyArg } from './function' import { HKT, Kind, Kind2, URIS, URIS2 } from './HKT' import * as _ from './internal' import { Monad, Monad1, Monad2 } from './Monad' import { Semigroup } from './Semigroup' import Either = E.Either // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ValidationT extends HKT> {} /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ValidationM extends ApplicativeCompositionHKT2C { readonly chain: (ma: ValidationT, f: (a: A) => ValidationT) => ValidationT readonly alt: (fa: ValidationT, that: LazyArg>) => ValidationT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export type ValidationT1 = Kind> /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ValidationM1 extends ApplicativeComposition12C { readonly chain: (ma: ValidationT1, f: (a: A) => ValidationT1) => ValidationT1 readonly alt: (fa: ValidationT1, that: LazyArg>) => ValidationT1 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export type ValidationT2 = Kind2> /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface ValidationM2 extends ApplicativeComposition22C { readonly chain: ( ma: ValidationT2, f: (a: A) => ValidationT2 ) => ValidationT2 readonly alt: ( fa: ValidationT2, that: LazyArg> ) => ValidationT2 } /** * Use `EitherT` instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function getValidationM(S: Semigroup, M: Monad2): ValidationM2 /** @deprecated */ export function getValidationM(S: Semigroup, M: Monad1): ValidationM1 /** @deprecated */ export function getValidationM(S: Semigroup, M: Monad): ValidationM /** @deprecated */ export function getValidationM(S: Semigroup, M: Monad): ValidationM { const A = getApplicativeComposition(M, E.getApplicativeValidation(S)) return { map: A.map, ap: A.ap, of: A.of, chain: (ma, f) => M.chain(ma, (e) => (_.isLeft(e) ? M.of(_.left(e.left)) : f(e.right))), alt: (me, that) => M.chain(me, (e1) => _.isRight(e1) ? M.of(e1) : M.map(that(), (e2) => (_.isLeft(e2) ? _.left(S.concat(e1.left, e2.left)) : e2)) ) } } ================================================ FILE: src/Witherable.ts ================================================ /** * `Witherable` represents data structures which can be _partitioned_ with effects in some `Applicative` functor. * * Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Witherable.purs * * @since 2.0.0 */ import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3, Applicative3C } from './Applicative' import { Compactable, Compactable1, Compactable2, Compactable2C } from './Compactable' import { Either } from './Either' import { Filterable, Filterable1, Filterable2, Filterable2C, Filterable3 } from './Filterable' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import * as _ from './internal' import { Option } from './Option' import { Separated } from './Separated' import { Traversable, Traversable1, Traversable2, Traversable2C, Traversable3 } from './Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Witherable extends Traversable, Filterable { /** * Partition a structure with effects */ readonly wilt: Wilt /** * Filter a structure with effects */ readonly wither: Wither } /** * @category model * @since 2.0.0 */ export interface Witherable1 extends Traversable1, Filterable1 { readonly wilt: Wilt1 readonly wither: Wither1 } /** * @category model * @since 2.0.0 */ export interface Witherable2 extends Traversable2, Filterable2 { readonly wilt: Wilt2 readonly wither: Wither2 } /** * @category model * @since 2.0.0 */ export interface Witherable2C extends Traversable2C, Filterable2C { readonly wilt: Wilt2C readonly wither: Wither2C } /** * @category model * @since 2.0.0 */ export interface Witherable3 extends Traversable3, Filterable3 { readonly wilt: Wilt3 readonly wither: Wither3 } /** * @since 2.0.0 */ export interface Wither { (F: Applicative3): ( ta: HKT, f: (a: A) => Kind3> ) => Kind3> (F: Applicative3C): ( ta: HKT, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: HKT, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: HKT, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): (ta: HKT, f: (a: A) => Kind>) => Kind> (F: Applicative): (ta: HKT, f: (a: A) => HKT>) => HKT> } /** * @since 2.0.0 */ export interface Wither1 { (F: Applicative3): ( ta: Kind, f: (a: A) => Kind3> ) => Kind3> (F: Applicative3C): ( ta: Kind, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): (ta: Kind, f: (a: A) => Kind>) => Kind> (F: Applicative): (ta: Kind, f: (a: A) => HKT>) => HKT> } /** * @since 2.0.0 */ export interface Wither2 { (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (a: A) => Kind> ) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT>) => HKT> } /** * @since 2.0.0 */ export interface Wither2C { (F: Applicative3): ( ta: Kind2, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind2, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): ( ta: Kind2, f: (a: A) => Kind> ) => Kind> (F: Applicative): (ta: Kind2, f: (a: A) => HKT>) => HKT> } /** * @since 2.0.0 */ export interface Wither3 { (F: Applicative3): ( ta: Kind3, f: (a: A) => Kind3> ) => Kind3> (F: Applicative2): ( ta: Kind3, f: (a: A) => Kind2> ) => Kind2> (F: Applicative2C): ( ta: Kind3, f: (a: A) => Kind2> ) => Kind2> (F: Applicative1): ( ta: Kind3, f: (a: A) => Kind> ) => Kind> (F: Applicative): ( ta: Kind3, f: (a: A) => HKT> ) => HKT> } /** * @since 2.0.0 */ export interface Wilt { (F: Applicative3): ( wa: HKT, f: (a: A) => Kind3> ) => Kind3, HKT>> (F: Applicative3C): ( wa: HKT, f: (a: A) => Kind3> ) => Kind3, HKT>> (F: Applicative2): ( wa: HKT, f: (a: A) => Kind2> ) => Kind2, HKT>> (F: Applicative2C): ( wa: HKT, f: (a: A) => Kind2> ) => Kind2, HKT>> (F: Applicative1): ( wa: HKT, f: (a: A) => Kind> ) => Kind, HKT>> (F: Applicative): ( wa: HKT, f: (a: A) => HKT> ) => HKT, HKT>> } /** * @since 2.0.0 */ export interface Wilt1 { (F: Applicative3): ( wa: Kind, f: (a: A) => Kind3> ) => Kind3, Kind>> (F: Applicative3C): ( wa: Kind, f: (a: A) => Kind3> ) => Kind3, Kind>> (F: Applicative2): ( wa: Kind, f: (a: A) => Kind2> ) => Kind2, Kind>> (F: Applicative2C): ( wa: Kind, f: (a: A) => Kind2> ) => Kind2, Kind>> (F: Applicative1): ( wa: Kind, f: (a: A) => Kind> ) => Kind, Kind>> (F: Applicative): ( wa: Kind, f: (a: A) => HKT> ) => HKT, Kind>> } /** * @since 2.0.0 */ export interface Wilt2 { (F: Applicative3): ( wa: Kind2, f: (a: A) => Kind3> ) => Kind3, Kind2>> (F: Applicative2): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative2C): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative1): ( wa: Kind2, f: (a: A) => Kind> ) => Kind, Kind2>> (F: Applicative): ( wa: Kind2, f: (a: A) => HKT> ) => HKT, Kind2>> } /** * @since 2.0.0 */ export interface Wilt2C { (F: Applicative3): ( wa: Kind2, f: (a: A) => Kind3> ) => Kind3, Kind2>> (F: Applicative2): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative2C): ( wa: Kind2, f: (a: A) => Kind2> ) => Kind2, Kind2>> (F: Applicative1): ( wa: Kind2, f: (a: A) => Kind> ) => Kind, Kind2>> (F: Applicative): ( wa: Kind2, f: (a: A) => HKT> ) => HKT, Kind2>> } /** * @since 2.0.0 */ export interface Wilt3 { (F: Applicative3): ( wa: Kind3, f: (a: A) => Kind3> ) => Kind3, Kind3>> (F: Applicative2): ( wa: Kind3, f: (a: A) => Kind2> ) => Kind2, Kind3>> (F: Applicative2C): ( wa: Kind3, f: (a: A) => Kind2> ) => Kind2, Kind3>> (F: Applicative1): ( wa: Kind3, f: (a: A) => Kind> ) => Kind, Kind3>> (F: Applicative): ( wa: Kind3, f: (a: A) => HKT> ) => HKT, Kind3>> } // // pipeable `Wither` // /** * @since 2.6.5 */ export interface PipeableWither { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: HKT) => Kind3> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (ta: HKT) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: HKT) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: HKT) => Kind2> (F: Applicative1): (f: (a: A) => Kind>) => (ta: HKT) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: HKT) => HKT> } /** * @since 2.6.5 */ export interface PipeableWither1 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind) => Kind3> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (ta: Kind) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: Kind) => HKT> } /** * @since 2.6.5 */ export interface PipeableWither2 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind2) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: Kind2) => HKT> } /** * @since 2.6.5 */ export interface PipeableWither2C { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind2) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind2) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind2) => Kind> (F: Applicative): (f: (a: A) => HKT>) => (ta: Kind2) => HKT> } /** * @since 2.6.5 */ export interface PipeableWither3 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (ta: Kind3) => Kind3> (F: Applicative2): ( f: (a: A) => Kind2> ) => (ta: Kind3) => Kind2> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (ta: Kind3) => Kind2> (F: Applicative1): ( f: (a: A) => Kind> ) => (ta: Kind3) => Kind> (F: Applicative): ( f: (a: A) => HKT> ) => (ta: Kind3) => HKT> } // // pipeable `Wilt` // /** * @since 2.6.5 */ export interface PipeableWilt { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: HKT) => Kind3, HKT>> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (wa: HKT) => Kind3, HKT>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: HKT) => Kind2, HKT>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: HKT) => Kind2, HKT>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: HKT) => Kind, HKT>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: HKT) => HKT, HKT>> } /** * @since 2.6.5 */ export interface PipeableWilt1 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind) => Kind3, Kind>> (F: Applicative3C): ( f: (a: A) => Kind3> ) => (wa: Kind) => Kind3, Kind>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind) => Kind2, Kind>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind) => Kind2, Kind>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind) => Kind, Kind>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind) => HKT, Kind>> } /** * @since 2.6.5 */ export interface PipeableWilt2 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind2) => Kind3, Kind2>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind2) => Kind, Kind2>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind2) => HKT, Kind2>> } /** * @since 2.6.5 */ export interface PipeableWilt2C { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind2) => Kind3, Kind2>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind2) => Kind2, Kind2>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind2) => Kind, Kind2>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind2) => HKT, Kind2>> } /** * @since 2.6.5 */ export interface PipeableWilt3 { (F: Applicative3): ( f: (a: A) => Kind3> ) => (wa: Kind3) => Kind3, Kind3>> (F: Applicative2): ( f: (a: A) => Kind2> ) => (wa: Kind3) => Kind2, Kind3>> (F: Applicative2C): ( f: (a: A) => Kind2> ) => (wa: Kind3) => Kind2, Kind3>> (F: Applicative1): ( f: (a: A) => Kind> ) => (wa: Kind3) => Kind, Kind3>> (F: Applicative): ( f: (a: A) => HKT> ) => (wa: Kind3) => HKT, Kind3>> } // ------------------------------------------------------------------------------------- // defaults // ------------------------------------------------------------------------------------- /** * Return a `wilt` implementation from `Traversable` and `Compactable`. * * @category defaults * @since 2.11.0 */ export function wiltDefault(T: Traversable2C, C: Compactable2): Witherable2C['wilt'] export function wiltDefault(T: Traversable2, C: Compactable2C): Witherable2C['wilt'] export function wiltDefault(T: Traversable1, C: Compactable1): Witherable1['wilt'] export function wiltDefault(T: Traversable, C: Compactable): Witherable['wilt'] export function wiltDefault(T: Traversable, C: Compactable): Witherable['wilt'] { return ( F: Applicative ): ((wa: HKT, f: (a: A) => HKT>) => HKT, HKT>>) => { const traverseF = T.traverse(F) return (wa, f) => F.map(traverseF(wa, f), C.separate) } } /** * Return a `wither` implementation from `Traversable` and `Compactable`. * * @category defaults * @since 2.11.0 */ export function witherDefault( T: Traversable2C, C: Compactable2 ): Witherable2C['wither'] export function witherDefault( T: Traversable2, C: Compactable2C ): Witherable2C['wither'] export function witherDefault(T: Traversable1, C: Compactable1): Witherable1['wither'] export function witherDefault(T: Traversable, C: Compactable): Witherable['wither'] export function witherDefault(T: Traversable, C: Compactable): Witherable['wither'] { return (F: Applicative): ((wa: HKT, f: (a: A) => HKT>) => HKT>) => { const traverseF = T.traverse(F) return (wa, f) => F.map(traverseF(wa, f), C.compact) } } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export interface FilterE1 { (F: Applicative3): ( predicate: (a: A) => Kind3 ) => (ga: Kind) => Kind3> (F: Applicative3C): ( predicate: (a: A) => Kind3 ) => (ga: Kind) => Kind3> (F: Applicative2): ( predicate: (a: A) => Kind2 ) => (ga: Kind) => Kind2> (F: Applicative2C): ( predicate: (a: A) => Kind2 ) => (ga: Kind) => Kind2> (F: Applicative1): ( predicate: (a: A) => Kind ) => (ga: Kind) => Kind> (F: Applicative): (predicate: (a: A) => HKT) => (ga: Kind) => HKT> } /** * Filter values inside a `F` context. * * See `ReadonlyArray`'s `filterE` for an example of usage. * * @since 2.11.0 */ export function filterE(W: Witherable1): FilterE1 export function filterE( W: Witherable ): (F: Applicative) => (predicate: (a: A) => HKT) => (ga: HKT) => HKT> export function filterE( W: Witherable ): (F: Applicative) => (predicate: (a: A) => HKT) => (ga: HKT) => HKT> { return (F) => { const witherF = W.wither(F) return (predicate) => (ga) => witherF(ga, (a) => F.map(predicate(a), (b) => (b ? _.some(a) : _.none))) } } ================================================ FILE: src/Writer.ts ================================================ /** * @since 2.0.0 */ import { Applicative2C } from './Applicative' import { Apply2C } from './Apply' import { Chain2C } from './Chain' import { pipe } from './function' import { flap as flap_, Functor2 } from './Functor' import { Monad2C } from './Monad' import { Monoid } from './Monoid' import { Pointed2C } from './Pointed' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.0.0 */ export interface Writer { (): [A, W] } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Appends a value to the accumulator * * @category constructors * @since 2.0.0 */ export const tell: (w: W) => Writer = (w) => () => [undefined, w] // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Modifies the result to include the changes to the accumulator * * @since 2.0.0 */ export const listen: (fa: Writer) => Writer = (fa) => () => { const [a, w] = fa() return [[a, w], w] } /** * Applies the returned function to the accumulator * * @since 2.0.0 */ export const pass: (fa: Writer W]>) => Writer = (fa) => () => { const [[a, f], w] = fa() return [a, f(w)] } /** * Projects a value from modifications made to the accumulator during an action * * @since 2.0.0 */ export const listens: (f: (w: W) => B) => (fa: Writer) => Writer = (f) => (fa) => () => { const [a, w] = fa() return [[a, f(w)], w] } /** * Modify the final accumulator value by applying a function * * @since 2.0.0 */ export const censor: (f: (w: W) => W) => (fa: Writer) => Writer = (f) => (fa) => () => { const [a, w] = fa() return [a, f(w)] } /* istanbul ignore next */ const _map: Functor2['map'] = (fa, f) => pipe(fa, map(f)) /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F) => F` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category mapping * @since 2.0.0 */ export const map: (f: (a: A) => B) => (fa: Writer) => Writer = (f) => (fa) => () => { const [a, w] = fa() return [f(a), w] } /** * @category type lambdas * @since 2.0.0 */ export const URI = 'Writer' /** * @category type lambdas * @since 2.0.0 */ export type URI = typeof URI declare module './HKT' { interface URItoKind2 { readonly [URI]: Writer } } /** * @category instances * @since 2.10.0 */ export const getPointed = (M: Monoid): Pointed2C => ({ URI, _E: undefined as any, of: (a) => () => [a, M.empty] }) /** * @category instances * @since 2.10.0 */ export const getApply = (S: Semigroup): Apply2C => ({ URI, _E: undefined as any, map: _map, ap: (fab, fa) => () => { const [f, w1] = fab() const [a, w2] = fa() return [f(a), S.concat(w1, w2)] } }) /** * @category instances * @since 2.10.0 */ export const getApplicative = (M: Monoid): Applicative2C => { const A = getApply(M) const P = getPointed(M) return { URI, _E: undefined as any, map: _map, ap: A.ap, of: P.of } } /** * @category instances * @since 2.10.0 */ export function getChain(S: Semigroup): Chain2C { const A = getApply(S) return { URI, _E: undefined as any, map: _map, ap: A.ap, chain: (fa, f) => () => { const [a, w1] = fa() const [b, w2] = f(a)() return [b, S.concat(w1, w2)] } } } /** * @category instances * @since 2.0.0 */ export function getMonad(M: Monoid): Monad2C { const A = getApplicative(M) const C = getChain(M) return { URI, _E: undefined as any, map: _map, ap: A.ap, of: A.of, chain: C.chain } } /** * @category instances * @since 2.7.0 */ export const Functor: Functor2 = { URI, map: _map } /** * @category mapping * @since 2.10.0 */ export const flap = /*#__PURE__*/ flap_(Functor) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.8.0 */ export const evaluate: (fa: Writer) => A = (fa) => fa()[0] /** * @since 2.8.0 */ export const execute: (fa: Writer) => W = (fa) => fa()[1] // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`evaluate`](#evaluate) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const evalWriter: (fa: Writer) => A = (fa) => fa()[0] /** * Use [`execute`](#execute) instead * * @category zone of death * @since 2.0.0 * @deprecated */ export const execWriter: (fa: Writer) => W = (fa) => fa()[1] /** * Use [`Functor`](#functor) instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export const writer: Functor2 = Functor ================================================ FILE: src/WriterT.ts ================================================ /** * @since 2.4.0 */ import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from './HKT' import { Monad, Monad1, Monad2, Monad2C, Monad3 } from './Monad' import { Monoid } from './Monoid' // TODO: remove module in v3 /** * @category model * @since 2.4.0 */ export interface WriterT { (): HKT } /** * @since 2.4.0 */ export interface WriterM { readonly map: (fa: WriterT, f: (a: A) => B) => WriterT readonly evalWriter: (fa: WriterT) => HKT readonly execWriter: (fa: WriterT) => HKT readonly tell: (w: W) => WriterT readonly listen: (fa: WriterT) => WriterT readonly pass: (fa: WriterT W]>) => WriterT readonly listens: (fa: WriterT, f: (w: W) => B) => WriterT readonly censor: (fa: WriterT, f: (w: W) => W) => WriterT readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT, f: (a: A) => B) => WriterT readonly of: (a: A) => WriterT readonly ap: (mab: WriterT B>, ma: WriterT) => WriterT readonly chain: (ma: WriterT, f: (a: A) => WriterT) => WriterT } } /** * @category model * @since 2.4.0 */ export interface WriterT1 { (): Kind } /** * @since 2.4.0 */ export interface WriterM1 { readonly map: (fa: WriterT1, f: (a: A) => B) => WriterT1 readonly evalWriter: (fa: WriterT1) => Kind readonly execWriter: (fa: WriterT1) => Kind readonly tell: (w: W) => WriterT1 readonly listen: (fa: WriterT1) => WriterT1 readonly pass: (fa: WriterT1 W]>) => WriterT1 readonly listens: (fa: WriterT1, f: (w: W) => B) => WriterT1 readonly censor: (fa: WriterT1, f: (w: W) => W) => WriterT1 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT1, f: (a: A) => B) => WriterT1 readonly of: (a: A) => WriterT1 readonly ap: (mab: WriterT1 B>, ma: WriterT1) => WriterT1 readonly chain: (ma: WriterT1, f: (a: A) => WriterT1) => WriterT1 } } /** * @category model * @since 2.4.0 */ export interface WriterT2 { (): Kind2 } /** * @since 2.4.0 */ export interface WriterM2 { readonly map: (fa: WriterT2, f: (a: A) => B) => WriterT2 readonly evalWriter: (fa: WriterT2) => Kind2 readonly execWriter: (fa: WriterT2) => Kind2 readonly tell: (w: W) => WriterT2 readonly listen: (fa: WriterT2) => WriterT2 readonly pass: (fa: WriterT2 W]>) => WriterT2 readonly listens: (fa: WriterT2, f: (w: W) => B) => WriterT2 readonly censor: (fa: WriterT2, f: (w: W) => W) => WriterT2 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT2, f: (a: A) => B) => WriterT2 readonly of: (a: A) => WriterT2 readonly ap: (mab: WriterT2 B>, ma: WriterT2) => WriterT2 readonly chain: (ma: WriterT2, f: (a: A) => WriterT2) => WriterT2 } } /** * @since 2.4.0 */ export interface WriterM2C { readonly map: (fa: WriterT2, f: (a: A) => B) => WriterT2 readonly evalWriter: (fa: WriterT2) => Kind2 readonly execWriter: (fa: WriterT2) => Kind2 readonly tell: (w: W) => WriterT2 readonly listen: (fa: WriterT2) => WriterT2 readonly pass: (fa: WriterT2 W]>) => WriterT2 readonly listens: (fa: WriterT2, f: (w: W) => B) => WriterT2 readonly censor: (fa: WriterT2, f: (w: W) => W) => WriterT2 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT2, f: (a: A) => B) => WriterT2 readonly of: (a: A) => WriterT2 readonly ap: (mab: WriterT2 B>, ma: WriterT2) => WriterT2 readonly chain: (ma: WriterT2, f: (a: A) => WriterT2) => WriterT2 } } /** * @since 2.4.0 */ export interface WriterT3 { (): Kind3 } /** * @since 2.4.0 */ export interface WriterM3 { readonly map: (fa: WriterT3, f: (a: A) => B) => WriterT3 readonly evalWriter: (fa: WriterT3) => Kind3 readonly execWriter: (fa: WriterT3) => Kind3 readonly tell: (w: W) => WriterT3 readonly listen: (fa: WriterT3) => WriterT3 readonly pass: (fa: WriterT3 W]>) => WriterT3 readonly listens: (fa: WriterT3, f: (w: W) => B) => WriterT3 readonly censor: (fa: WriterT3, f: (w: W) => W) => WriterT3 readonly getMonad: (M: Monoid) => { readonly _E: W readonly map: (ma: WriterT3, f: (a: A) => B) => WriterT3 readonly of: (a: A) => WriterT3 readonly ap: ( mab: WriterT3 B>, ma: WriterT3 ) => WriterT3 readonly chain: ( ma: WriterT3, f: (a: A) => WriterT3 ) => WriterT3 } } /** * @since 2.4.0 */ export function getWriterM(M: Monad3): WriterM3 export function getWriterM(M: Monad2): WriterM2 export function getWriterM(M: Monad2C): WriterM2C export function getWriterM(M: Monad1): WriterM1 export function getWriterM(M: Monad): WriterM export function getWriterM(M: Monad): WriterM { const map = (fa: WriterT, f: (a: A) => B): WriterT => () => M.map(fa(), ([a, w]) => [f(a), w]) return { map, evalWriter: (fa) => M.map(fa(), ([a]) => a), execWriter: (fa) => M.map(fa(), ([_, w]) => w), tell: (w) => () => M.of([undefined, w]), listen: (fa) => () => M.map(fa(), ([a, w]) => [[a, w], w]), pass: (fa) => () => M.map(fa(), ([[a, f], w]) => [a, f(w)]), listens: (fa, f) => () => M.map(fa(), ([a, w]) => [[a, f(w)], w]), censor: (fa, f) => () => M.map(fa(), ([a, w]) => [a, f(w)]), getMonad: (W) => { return { _E: undefined as any, map, of: (a) => () => M.of([a, W.empty]), ap: (mab, ma) => () => M.chain(mab(), ([f, w1]) => M.map(ma(), ([a, w2]) => [f(a), W.concat(w1, w2)])), chain: (ma, f) => () => M.chain(ma(), ([a, w1]) => M.map(f(a)(), ([b, w2]) => [b, W.concat(w1, w2)])) } } } } ================================================ FILE: src/Zero.ts ================================================ /** * @since 2.11.0 */ import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { Pointed, Pointed1, Pointed2, Pointed2C, Pointed3, Pointed3C, Pointed4 } from './Pointed' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.11.0 */ export interface Zero { readonly URI: F readonly zero: () => HKT } /** * @category model * @since 2.11.0 */ export interface Zero1 { readonly URI: F readonly zero: () => Kind } /** * @category model * @since 2.11.0 */ export interface Zero2 { readonly URI: F readonly zero: () => Kind2 } /** * @category model * @since 2.11.0 */ export interface Zero2C { readonly URI: F readonly _E: E readonly zero: () => Kind2 } /** * @category model * @since 2.11.0 */ export interface Zero3 { readonly URI: F readonly zero: () => Kind3 } /** * @category model * @since 2.11.0 */ export interface Zero3C { readonly URI: F readonly _E: E readonly zero: () => Kind3 } /** * @category model * @since 2.11.0 */ export interface Zero4 { readonly URI: F readonly zero: () => Kind4 } /** * @category do notation * @since 2.11.0 */ export function guard(F: Zero4, P: Pointed4): (b: boolean) => Kind4 export function guard(F: Zero3, P: Pointed3): (b: boolean) => Kind3 export function guard(F: Zero3C, P: Pointed3C): (b: boolean) => Kind3 export function guard(F: Zero2, P: Pointed2): (b: boolean) => Kind2 export function guard(F: Zero2C, P: Pointed2C): (b: boolean) => Kind2 export function guard(F: Zero1, P: Pointed1): (b: boolean) => Kind export function guard(F: Zero, P: Pointed): (b: boolean) => HKT export function guard(F: Zero, P: Pointed): (b: boolean) => HKT { return (b) => (b ? P.of(undefined) : F.zero()) } ================================================ FILE: src/boolean.ts ================================================ /** * @since 2.2.0 */ import * as BA from './BooleanAlgebra' import * as E from './Eq' import { LazyArg } from './function' import { Monoid } from './Monoid' import * as O from './Ord' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import * as S from './Show' // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * @category refinements * @since 2.11.0 */ export const isBoolean: Refinement = (u: unknown): u is boolean => typeof u === 'boolean' /** * Less strict version of [`match`](#match). * * The `W` suffix (short for **W**idening) means that the handler return types will be merged. * * @category pattern matching * @since 2.10.0 */ export const matchW = (onFalse: LazyArg, onTrue: LazyArg) => (value: boolean): A | B => value ? onTrue() : onFalse() /** * Alias of [`matchW`](#matchw). * * @category pattern matching * @since 2.10.0 */ export const foldW = matchW /** * Defines the fold over a boolean value. * Takes two thunks `onTrue`, `onFalse` and a `boolean` value. * If `value` is false, `onFalse()` is returned, otherwise `onTrue()`. * * @example * import { some, map } from 'fp-ts/Option' * import { pipe } from 'fp-ts/function' * import { match } from 'fp-ts/boolean' * * assert.deepStrictEqual( * pipe( * some(true), * map(match(() => 'false', () => 'true')) * ), * some('true') * ) * * @category pattern matching * @since 2.10.0 */ export const match: (onFalse: LazyArg, onTrue: LazyArg) => (value: boolean) => A = foldW /** * Alias of [`match`](#match). * * @category pattern matching * @since 2.2.0 */ export const fold = match // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.10.0 */ export const Eq: E.Eq = { equals: (first, second) => first === second } /** * @category instances * @since 2.10.0 */ export const BooleanAlgebra: BA.BooleanAlgebra = { meet: (first, second) => first && second, join: (first, second) => first || second, zero: false, one: true, implies: (first, second) => !first || second, not: (b) => !b } /** * `boolean` semigroup under conjunction. * * @example * import { SemigroupAll } from 'fp-ts/boolean' * * assert.deepStrictEqual(SemigroupAll.concat(true, true), true) * assert.deepStrictEqual(SemigroupAll.concat(true, false), false) * * @category instances * @since 2.10.0 */ export const SemigroupAll: Semigroup = { concat: (first, second) => first && second } /** * `boolean` semigroup under disjunction. * * @example * import { SemigroupAny } from 'fp-ts/boolean' * * assert.deepStrictEqual(SemigroupAny.concat(true, true), true) * assert.deepStrictEqual(SemigroupAny.concat(true, false), true) * assert.deepStrictEqual(SemigroupAny.concat(false, false), false) * * @category instances * @since 2.10.0 */ export const SemigroupAny: Semigroup = { concat: (first, second) => first || second } /** * `boolean` monoid under conjunction. * * The `empty` value is `true`. * * @example * import { MonoidAll } from 'fp-ts/boolean' * * assert.deepStrictEqual(MonoidAll.concat(true, true), true) * assert.deepStrictEqual(MonoidAll.concat(true, false), false) * * @category instances * @since 2.10.0 */ export const MonoidAll: Monoid = { concat: SemigroupAll.concat, empty: true } /** * `boolean` monoid under disjunction. * * The `empty` value is `false`. * * @example * import { MonoidAny } from 'fp-ts/boolean' * * assert.deepStrictEqual(MonoidAny.concat(true, true), true) * assert.deepStrictEqual(MonoidAny.concat(true, false), true) * assert.deepStrictEqual(MonoidAny.concat(false, false), false) * * @category instances * @since 2.10.0 */ export const MonoidAny: Monoid = { concat: SemigroupAny.concat, empty: false } /** * @category instances * @since 2.10.0 */ export const Ord: O.Ord = { equals: Eq.equals, compare: (first, second) => (first < second ? -1 : first > second ? 1 : 0) } /** * @category instances * @since 2.10.0 */ export const Show: S.Show = { show: (b) => JSON.stringify(b) } ================================================ FILE: src/function.ts ================================================ /** * @since 2.0.0 */ import { BooleanAlgebra } from './BooleanAlgebra' import { Monoid } from './Monoid' import { Ring } from './Ring' import { Semigroup } from './Semigroup' import { Semiring } from './Semiring' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.10.0 */ export const getBooleanAlgebra = (B: BooleanAlgebra) => (): BooleanAlgebra<(a: A) => B> => ({ meet: (x, y) => (a) => B.meet(x(a), y(a)), join: (x, y) => (a) => B.join(x(a), y(a)), zero: () => B.zero, one: () => B.one, implies: (x, y) => (a) => B.implies(x(a), y(a)), not: (x) => (a) => B.not(x(a)) }) /** * Unary functions form a semigroup as long as you can provide a semigroup for the codomain. * * @example * import { Predicate, getSemigroup } from 'fp-ts/function' * import * as B from 'fp-ts/boolean' * * const f: Predicate = (n) => n <= 2 * const g: Predicate = (n) => n >= 0 * * const S1 = getSemigroup(B.SemigroupAll)() * * assert.deepStrictEqual(S1.concat(f, g)(1), true) * assert.deepStrictEqual(S1.concat(f, g)(3), false) * * const S2 = getSemigroup(B.SemigroupAny)() * * assert.deepStrictEqual(S2.concat(f, g)(1), true) * assert.deepStrictEqual(S2.concat(f, g)(3), true) * * @category instances * @since 2.10.0 */ export const getSemigroup = (S: Semigroup) => (): Semigroup<(a: A) => S> => ({ concat: (f, g) => (a) => S.concat(f(a), g(a)) }) /** * Unary functions form a monoid as long as you can provide a monoid for the codomain. * * @example * import { Predicate } from 'fp-ts/Predicate' * import { getMonoid } from 'fp-ts/function' * import * as B from 'fp-ts/boolean' * * const f: Predicate = (n) => n <= 2 * const g: Predicate = (n) => n >= 0 * * const M1 = getMonoid(B.MonoidAll)() * * assert.deepStrictEqual(M1.concat(f, g)(1), true) * assert.deepStrictEqual(M1.concat(f, g)(3), false) * * const M2 = getMonoid(B.MonoidAny)() * * assert.deepStrictEqual(M2.concat(f, g)(1), true) * assert.deepStrictEqual(M2.concat(f, g)(3), true) * * @category instances * @since 2.10.0 */ export const getMonoid = (M: Monoid): (() => Monoid<(a: A) => M>) => { const getSemigroupM = getSemigroup(M) return () => ({ concat: getSemigroupM().concat, empty: () => M.empty }) } /** * @category instances * @since 2.10.0 */ export const getSemiring = (S: Semiring): Semiring<(a: A) => B> => ({ add: (f, g) => (x) => S.add(f(x), g(x)), zero: () => S.zero, mul: (f, g) => (x) => S.mul(f(x), g(x)), one: () => S.one }) /** * @category instances * @since 2.10.0 */ export const getRing = (R: Ring): Ring<(a: A) => B> => { const S = getSemiring(R) return { add: S.add, mul: S.mul, one: S.one, zero: S.zero, sub: (f, g) => (x) => R.sub(f(x), g(x)) } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const apply = (a: A) => (f: (a: A) => B): B => f(a) /** * @example * import { FunctionN } from 'fp-ts/function' * * export const sum: FunctionN<[number, number], number> = (a, b) => a + b * * @since 2.0.0 */ export interface FunctionN, B> { (...args: A): B } /** * @since 2.0.0 */ export function identity(a: A): A { return a } /** * @since 2.0.0 */ export const unsafeCoerce: (a: A) => B = identity as any /** * @since 2.0.0 */ export function constant(a: A): LazyArg { return () => a } /** * A thunk that returns always `true`. * * @since 2.0.0 */ export const constTrue: LazyArg = /*#__PURE__*/ constant(true) /** * A thunk that returns always `false`. * * @since 2.0.0 */ export const constFalse: LazyArg = /*#__PURE__*/ constant(false) /** * A thunk that returns always `null`. * * @since 2.0.0 */ export const constNull: LazyArg = /*#__PURE__*/ constant(null) /** * A thunk that returns always `undefined`. * * @since 2.0.0 */ export const constUndefined: LazyArg = /*#__PURE__*/ constant(undefined) /** * A thunk that returns always `void`. * * @since 2.0.0 */ export const constVoid: LazyArg = constUndefined /** * Flips the arguments of a curried function. * * @example * import { flip } from 'fp-ts/function' * * const f = (a: number) => (b: string) => a - b.length * * assert.strictEqual(flip(f)('aaa')(2), -1) * * @since 2.0.0 */ export function flip(f: (a: A) => (b: B) => C): (b: B) => (a: A) => C /** @deprecated */ export function flip(f: (a: A, b: B) => C): (b: B, a: A) => C export function flip(f: Function): Function { return (...args: Array) => { if (args.length > 1) { return f(args[1], args[0]) } return (a: any) => f(a)(args[0]) } } /** * Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary. * * See also [`pipe`](#pipe). * * @example * import { flow } from 'fp-ts/function' * * const len = (s: string): number => s.length * const double = (n: number): number => n * 2 * * const f = flow(len, double) * * assert.strictEqual(f('aaa'), 6) * * @since 2.0.0 */ export function flow, B>(ab: (...a: A) => B): (...a: A) => B export function flow, B, C>(ab: (...a: A) => B, bc: (b: B) => C): (...a: A) => C export function flow, B, C, D>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D ): (...a: A) => D export function flow, B, C, D, E>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E ): (...a: A) => E export function flow, B, C, D, E, F>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F ): (...a: A) => F export function flow, B, C, D, E, F, G>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G ): (...a: A) => G export function flow, B, C, D, E, F, G, H>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H ): (...a: A) => H export function flow, B, C, D, E, F, G, H, I>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I ): (...a: A) => I export function flow, B, C, D, E, F, G, H, I, J>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J ): (...a: A) => J export function flow( ab: Function, bc?: Function, cd?: Function, de?: Function, ef?: Function, fg?: Function, gh?: Function, hi?: Function, ij?: Function ): unknown { switch (arguments.length) { case 1: return ab case 2: return function (this: unknown) { return bc!(ab.apply(this, arguments)) } case 3: return function (this: unknown) { return cd!(bc!(ab.apply(this, arguments))) } case 4: return function (this: unknown) { return de!(cd!(bc!(ab.apply(this, arguments)))) } case 5: return function (this: unknown) { return ef!(de!(cd!(bc!(ab.apply(this, arguments))))) } case 6: return function (this: unknown) { return fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))) } case 7: return function (this: unknown) { return gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))) } case 8: return function (this: unknown) { return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))))) } case 9: return function (this: unknown) { return ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))))) } } return } /** * @since 2.0.0 */ export function tuple>(...t: T): T { return t } /** * @since 2.0.0 */ export function increment(n: number): number { return n + 1 } /** * @since 2.0.0 */ export function decrement(n: number): number { return n - 1 } /** * @since 2.0.0 */ export function absurd(_: never): A { throw new Error('Called `absurd` function which should be uncallable') } /** * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. * * @example * import { tupled } from 'fp-ts/function' * * const add = tupled((x: number, y: number): number => x + y) * * assert.strictEqual(add([1, 2]), 3) * * @since 2.4.0 */ export function tupled, B>(f: (...a: A) => B): (a: A) => B { return (a) => f(...a) } /** * Inverse function of `tupled` * * @since 2.4.0 */ export function untupled, B>(f: (a: A) => B): (...a: A) => B { return (...a) => f(a) } /** * Pipes the value of an expression into a pipeline of functions. * * See also [`flow`](#flow). * * @example * import { pipe } from 'fp-ts/function' * * const len = (s: string): number => s.length * const double = (n: number): number => n * 2 * * // without pipe * assert.strictEqual(double(len('aaa')), 6) * * // with pipe * assert.strictEqual(pipe('aaa', len, double), 6) * * @since 2.6.3 */ export function pipe(a: A): A export function pipe(a: A, ab: (a: A) => B): B export function pipe(a: A, ab: (a: A) => B, bc: (b: B) => C): C export function pipe(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D export function pipe(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): E export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F ): F export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G ): G export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H ): H export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I ): I export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J ): J export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K ): K export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L ): L export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M ): M export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N ): N export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O ): O export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P ): P export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q ): Q export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R ): R export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S ): S export function pipe( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S, st: (s: S) => T ): T export function pipe( a: unknown, ab?: Function, bc?: Function, cd?: Function, de?: Function, ef?: Function, fg?: Function, gh?: Function, hi?: Function ): unknown { switch (arguments.length) { case 1: return a case 2: return ab!(a) case 3: return bc!(ab!(a)) case 4: return cd!(bc!(ab!(a))) case 5: return de!(cd!(bc!(ab!(a)))) case 6: return ef!(de!(cd!(bc!(ab!(a))))) case 7: return fg!(ef!(de!(cd!(bc!(ab!(a)))))) case 8: return gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))) case 9: return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))) default: { let ret = arguments[0] for (let i = 1; i < arguments.length; i++) { ret = arguments[i](ret) } return ret } } } /** * Type hole simulation * * @since 2.7.0 */ export const hole: () => T = absurd as any /** * @since 2.11.0 */ export const SK = (_: A, b: B): B => b // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use `Refinement` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export interface Refinement { (a: A): a is B } /** * Use `Predicate` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export interface Predicate { (a: A): boolean } /** * Use `Predicate` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export function not(predicate: Predicate): Predicate { return (a) => !predicate(a) } /** * Use `Endomorphism` module instead. * * @category zone of death * @since 2.0.0 * @deprecated */ export interface Endomorphism { (a: A): A } /** * Use `Endomorphism` module instead. * * @category zone of death * @since 2.10.0 * @deprecated */ export const getEndomorphismMonoid = (): Monoid> => ({ concat: (first, second) => flow(first, second), empty: identity }) /** * A lazy argument. * * @since 2.15.0 */ export interface LazyArg { (): A } /** @internal */ export const dual: { ) => any, DataFirst extends (...args: Array) => any>( arity: Parameters['length'], body: DataFirst ): DataLast & DataFirst ) => any, DataFirst extends (...args: Array) => any>( isDataFirst: (args: IArguments) => boolean, body: DataFirst ): DataLast & DataFirst } = (arity: any, body: any) => { const isDataFirst: (args: IArguments) => boolean = typeof arity === 'number' ? (args) => args.length >= arity : arity return function (this: any) { const args = Array.from(arguments) if (isDataFirst(arguments)) { return body.apply(this, args) } return (self: any) => body(self, ...args) } } // ------------------------------------------------------------------------------------- // lagacy // ------------------------------------------------------------------------------------- /** * Use `LazyArg` instead. * * @category lagacy * @since 2.0.0 */ export interface Lazy { (): A } ================================================ FILE: src/index.ts ================================================ /** * @since 2.0.0 */ import * as alt from './Alt' import * as alternative from './Alternative' import * as applicative from './Applicative' import * as apply from './Apply' import * as array from './Array' import * as bifunctor from './Bifunctor' import * as boolean from './boolean' import * as booleanAlgebra from './BooleanAlgebra' import * as bounded from './Bounded' import * as boundedDistributiveLattice from './BoundedDistributiveLattice' import * as boundedJoinSemilattice from './BoundedJoinSemilattice' import * as boundedLattice from './BoundedLattice' import * as boundedMeetSemilattice from './BoundedMeetSemilattice' import * as category from './Category' import * as chain from './Chain' import * as chainRec from './ChainRec' import * as choice from './Choice' import * as comonad from './Comonad' import * as compactable from './Compactable' import * as console from './Console' import * as const_ from './Const' import * as contravariant from './Contravariant' import * as date from './Date' import * as distributiveLattice from './DistributiveLattice' import * as either from './Either' import * as eitherT from './EitherT' import * as endomorphism from './Endomorphism' import * as eq from './Eq' import * as extend from './Extend' import * as field from './Field' import * as filterable from './Filterable' import * as filterableWithIndex from './FilterableWithIndex' import * as foldable from './Foldable' import * as foldableWithIndex from './FoldableWithIndex' import * as fromEither from './FromEither' import * as fromIO from './FromIO' import * as fromReader from './FromReader' import * as fromState from './FromState' import * as fromTask from './FromTask' import * as fromThese from './FromThese' import * as function_ from './function' import * as functor from './Functor' import * as functorWithIndex from './FunctorWithIndex' import * as group from './Group' import * as heytingAlgebra from './HeytingAlgebra' import * as hkt from './HKT' import * as identity from './Identity' import * as invariant from './Invariant' import * as io from './IO' import * as ioEither from './IOEither' import * as ioOption from './IOOption' import * as ioRef from './IORef' import * as joinSemilattice from './JoinSemilattice' import * as json from './Json' import * as lattice from './Lattice' import * as magma from './Magma' import * as map from './Map' import * as meetSemilattice from './MeetSemilattice' import * as monad from './Monad' import * as monadIO from './MonadIO' import * as monadTask from './MonadTask' import * as monadThrow from './MonadThrow' import * as monoid from './Monoid' import * as naturalTransformation from './NaturalTransformation' import * as nonEmptyArray from './NonEmptyArray' import * as number from './number' import * as option from './Option' import * as optionT from './OptionT' import * as ord from './Ord' import * as ordering from './Ordering' import * as pipeable from './pipeable' import * as pointed from './Pointed' import * as predicate from './Predicate' import * as profunctor from './Profunctor' import * as random from './Random' import * as reader from './Reader' import * as readerEither from './ReaderEither' import * as readerIO from './ReaderIO' import * as readerT from './ReaderT' import * as readerTask from './ReaderTask' import * as readerTaskEither from './ReaderTaskEither' import * as readonlyArray from './ReadonlyArray' import * as readonlyMap from './ReadonlyMap' import * as readonlyNonEmptyArray from './ReadonlyNonEmptyArray' import * as readonlyRecord from './ReadonlyRecord' import * as readonlySet from './ReadonlySet' import * as readonlyTuple from './ReadonlyTuple' import * as record from './Record' import * as refinement from './Refinement' import * as ring from './Ring' import * as semigroup from './Semigroup' import * as semigroupoid from './Semigroupoid' import * as semiring from './Semiring' import * as separated from './Separated' import * as set from './Set' import * as show from './Show' import * as state from './State' import * as stateReaderTaskEither from './StateReaderTaskEither' import * as stateT from './StateT' import * as store from './Store' import * as string from './string' import * as strong from './Strong' import * as struct from './struct' import * as task from './Task' import * as taskEither from './TaskEither' import * as taskOption from './TaskOption' import * as taskThese from './TaskThese' import * as these from './These' import * as theseT from './TheseT' import * as traced from './Traced' import * as traversable from './Traversable' import * as traversableWithIndex from './TraversableWithIndex' import * as tree from './Tree' import * as tuple from './Tuple' import * as unfoldable from './Unfoldable' import * as validationT from './ValidationT' import * as void_ from './void' import * as witherable from './Witherable' import * as writer from './Writer' import * as writerT from './WriterT' import * as zero from './Zero' export { /** * @category model * @since 2.0.0 */ alt, /** * @category model * @since 2.0.0 */ alternative, /** * @category model * @since 2.0.0 */ applicative, /** * @category model * @since 2.0.0 */ apply, /** * @category data types * @since 2.0.0 */ array, /** * @category model * @since 2.0.0 */ bifunctor, /** * @since 2.2.0 */ boolean, /** * @category model * @since 2.0.0 */ booleanAlgebra, /** * @category model * @since 2.0.0 */ bounded, /** * @category model * @since 2.0.0 */ boundedDistributiveLattice, /** * @category model * @since 2.0.0 */ boundedJoinSemilattice, /** * @category model * @since 2.0.0 */ boundedLattice, /** * @category model * @since 2.0.0 */ boundedMeetSemilattice, /** * @category model * @since 2.0.0 */ category, /** * @category model * @since 2.0.0 */ chain, /** * @category model * @since 2.0.0 */ chainRec, /** * @category model * @since 2.0.0 */ choice, /** * @category model * @since 2.0.0 */ comonad, /** * @category model * @since 2.0.0 */ compactable, /** * @since 2.0.0 */ console, /** * @category data types * @since 2.0.0 */ const_ as const, /** * @category model * @since 2.0.0 */ contravariant, /** * @since 2.0.0 */ date, /** * @category model * @since 2.0.0 */ distributiveLattice, /** * @category data types * @since 2.0.0 */ either, /** * @category monad transformers * @since 2.0.0 */ eitherT, /** * @category data types * @since 2.11.0 */ endomorphism, /** * @category model * @since 2.0.0 */ extend, /** * @category model * @since 2.0.0 */ field, /** * @category model * @since 2.0.0 */ filterable, /** * @category model * @since 2.0.0 */ filterableWithIndex, /** * @category model * @since 2.0.0 */ foldable, /** * @category model * @since 2.0.0 */ foldableWithIndex, /** * @category model * @since 2.10.0 */ fromEither, /** * @category model * @since 2.10.0 */ fromIO, /** * @category model * @since 2.11.0 */ fromReader, /** * @category model * @since 2.11.0 */ fromState, /** * @category model * @since 2.10.0 */ fromTask, /** * @category model * @since 2.11.0 */ fromThese, /** * @since 2.0.0 */ function_ as function, /** * @category model * @since 2.0.0 */ functor, /** * @category model * @since 2.0.0 */ functorWithIndex, /** * @category model * @since 2.0.0 */ group, /** * @category model * @since 2.0.0 */ heytingAlgebra, /** * @since 2.0.0 */ hkt, /** * @category data types * @since 2.0.0 */ identity, /** * @category model * @since 2.0.0 */ invariant, /** * @category data types * @since 2.0.0 */ io, /** * @category data types * @since 2.0.0 */ ioEither, /** * @category data types * @since 2.12.0 */ ioOption, /** * @since 2.0.0 */ ioRef, /** * @category model * @since 2.0.0 */ joinSemilattice, /** * @since 2.10.0 */ json, /** * @category model * @since 2.0.0 */ lattice, /** * @category model * @since 2.0.0 */ magma, /** * @category data types * @since 2.0.0 */ map, /** * @category model * @since 2.0.0 */ meetSemilattice, /** * @category model * @since 2.0.0 */ monad, /** * @category model * @since 2.0.0 */ monadIO, /** * @category model * @since 2.0.0 */ monadTask, /** * @category model * @since 2.0.0 */ monadThrow, /** * @category model * @since 2.0.0 */ monoid, /** * @since 2.11.0 */ naturalTransformation, /** * @category data types * @since 2.0.0 */ nonEmptyArray, /** * @since 2.10.0 */ number, /** * @category data types * @since 2.0.0 */ option, /** * @category monad transformers * @since 2.0.0 */ optionT, /** * @category model * @since 2.0.0 */ ord, /** * @since 2.0.0 */ ordering, /** * @since 2.0.0 */ pipeable, /** * @category model * @since 2.10.0 */ pointed, /** * @category data types * @since 2.11.0 */ predicate, /** * @category model * @since 2.0.0 */ profunctor, /** * @since 2.0.0 */ random, /** * @category data types * @since 2.0.0 */ reader, /** * @category data types * @since 2.0.0 */ readerEither, /** * @category data types * @since 2.0.0 */ readerIO, /** * @category monad transformers * @since 2.0.0 */ readerT, /** * @category data types * @since 2.0.0 */ readerTaskEither, /** * @category data types * @since 2.5.0 */ readonlyArray, /** * @category data types * @since 2.5.0 */ readonlyMap, /** * @category data types * @since 2.5.0 */ readonlyNonEmptyArray, /** * @category data types * @since 2.5.0 */ readonlyRecord, /** * @category data types * @since 2.5.0 */ readonlySet, /** * @category data types * @since 2.5.0 */ readonlyTuple, /** * @category data types * @since 2.3.0 */ readerTask, /** * @category data types * @since 2.0.0 */ record, /** * @category data types * @since 2.11.0 */ refinement, /** * @category model * @since 2.0.0 */ ring, /** * @category model * @since 2.0.0 */ semigroup, /** * @category model * @since 2.0.0 */ semigroupoid, /** * @category model * @since 2.0.0 */ semiring, /** * @category data types * @since 2.10.0 */ separated, /** * @category data types * @since 2.0.0 */ set, /** * @category model * @since 2.0.0 */ eq, /** * @category model * @since 2.0.0 */ show, /** * @category data types * @since 2.0.0 */ state, /** * @category data types * @since 2.0.0 */ stateReaderTaskEither, /** * @category monad transformers * @since 2.0.0 */ stateT, /** * @category data types * @since 2.0.0 */ store, /** * @since 2.10.0 */ string, /** * @category model * @since 2.0.0 */ strong, /** * @since 2.10.0 */ struct, /** * @category data types * @since 2.0.0 */ task, /** * @category data types * @since 2.0.0 */ taskEither, /** * @category data types * @since 2.10.0 */ taskOption, /** * @category data types * @since 2.4.0 */ taskThese, /** * @category data types * @since 2.0.0 */ these, /** * @category monad transformers * @since 2.4.0 */ theseT, /** * @category data types * @since 2.0.0 */ traced, /** * @category model * @since 2.0.0 */ traversable, /** * @category model * @since 2.0.0 */ traversableWithIndex, /** * @category data types * @since 2.0.0 */ tree, /** * @category data types * @since 2.0.0 */ tuple, /** * @category model * @since 2.0.0 */ unfoldable, /** * @category data types * @since 2.0.0 */ validationT, /** * @category zone of death * @since 2.11.0 * @deprecated */ void_ as void, /** * @category model * @since 2.0.0 */ witherable, /** * @category data types * @since 2.0.0 */ writer, /** * @category monad transformers * @since 2.4.0 */ writerT, /** * @category model * @since 2.11.0 */ zero } ================================================ FILE: src/internal.ts ================================================ import { Either, Left, Right } from './Either' import { dual } from './function' import { IO } from './IO' import { NonEmptyArray } from './NonEmptyArray' import { None, Option, Some } from './Option' import { Reader } from './Reader' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Task } from './Task' // ------------------------------------------------------------------------------------- // Option // ------------------------------------------------------------------------------------- /** @internal */ export const isNone = (fa: Option): fa is None => fa._tag === 'None' /** @internal */ export const isSome = (fa: Option): fa is Some => fa._tag === 'Some' /** @internal */ export const none: Option = { _tag: 'None' } /** @internal */ export const some = (a: A): Option => ({ _tag: 'Some', value: a }) // ------------------------------------------------------------------------------------- // Either // ------------------------------------------------------------------------------------- /** @internal */ export const isLeft = (ma: Either): ma is Left => ma._tag === 'Left' /** @internal */ export const isRight = (ma: Either): ma is Right => ma._tag === 'Right' /** @internal */ export const left = (e: E): Either => ({ _tag: 'Left', left: e }) /** @internal */ export const right = (a: A): Either => ({ _tag: 'Right', right: a }) // ------------------------------------------------------------------------------------- // ReadonlyNonEmptyArray // ------------------------------------------------------------------------------------- /** @internal */ export const singleton = (a: A): NonEmptyArray => [a] /** @internal */ export const isNonEmpty = (as: ReadonlyArray): as is ReadonlyNonEmptyArray => as.length > 0 /** @internal */ export const head = (as: ReadonlyNonEmptyArray): A => as[0] /** @internal */ export const tail = (as: ReadonlyNonEmptyArray): ReadonlyArray => as.slice(1) // ------------------------------------------------------------------------------------- // empty // ------------------------------------------------------------------------------------- /** @internal */ export const emptyReadonlyArray: readonly [] = [] /** @internal */ export const emptyRecord: {} = {} // ------------------------------------------------------------------------------------- // Record // ------------------------------------------------------------------------------------- /** @internal */ export const has = Object.prototype.hasOwnProperty // ------------------------------------------------------------------------------------- // NonEmptyArray // ------------------------------------------------------------------------------------- /** @internal */ export const fromReadonlyNonEmptyArray = (as: ReadonlyNonEmptyArray): NonEmptyArray => [as[0], ...as.slice(1)] // ------------------------------------------------------------------------------------- // HKT // ------------------------------------------------------------------------------------- /** @internal */ export declare const URI: unique symbol /** @internal */ export interface TypeLambda { readonly In: unknown readonly Out2: unknown readonly Out1: unknown readonly Target: unknown } /** @internal */ export interface TypeClass { readonly [URI]?: F } /** @internal */ export type Kind = F extends { readonly type: unknown } ? (F & { readonly In: In readonly Out2: Out2 readonly Out1: Out1 readonly Target: Target })['type'] : { readonly F: F readonly In: (_: In) => void readonly Out2: () => Out2 readonly Out1: () => Out1 readonly Target: (_: Target) => Target } // ------------------------------------------------------------------------------------- // type classes // ------------------------------------------------------------------------------------- /** @internal */ export interface FromEither extends TypeClass { readonly fromEither: (e: Either) => Kind } /** @internal */ export interface FromIO extends TypeClass { readonly fromIO: (e: IO) => Kind } /** @internal */ export interface FromTask extends TypeClass { readonly fromTask: (e: Task) => Kind } /** @internal */ export interface FromReader extends TypeClass { readonly fromReader: (e: Reader) => Kind } /** @internal */ export const liftNullable = (F: FromEither) => , B, E>(f: (...a: A) => B | null | undefined, onNullable: (...a: A) => E) => (...a: A): Kind> => { const o = f(...a) return F.fromEither>( o == null ? left(onNullable(...a)) : right, E>(o as any) ) } /** @internal */ export const liftOption = (F: FromEither) => , B, E>(f: (...a: A) => Option, onNone: (...a: A) => E) => (...a: A): Kind => { const o = f(...a) return F.fromEither(isNone(o) ? left(onNone(...a)) : right(o.value)) } /** @internal */ export interface FlatMap extends TypeClass { readonly flatMap: { (f: (a: A) => Kind): ( self: Kind ) => Kind (self: Kind, f: (a: A) => Kind): Kind< F, R1 & R2, O1 | O2, E1 | E2, B > } } /** @internal */ export const flatMapNullable = ( F: FromEither, M: FlatMap ): { (f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): ( self: Kind ) => Kind> (self: Kind, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2): Kind< F, R, O, E1 | E2, NonNullable > } => { return /*#__PURE__*/ dual( 3, ( self: Kind, f: (a: A) => B | null | undefined, onNullable: (a: A) => E2 ): Kind> => M.flatMap>(self, liftNullable(F)(f, onNullable)) ) } /** @internal */ export const flatMapOption = ( F: FromEither, M: FlatMap ): { (f: (a: A) => Option, onNone: (a: A) => E2): ( self: Kind ) => Kind (self: Kind, f: (a: A) => Option, onNone: (a: A) => E2): Kind< F, R, O, E1 | E2, B > } => { return /*#__PURE__*/ dual( 3, ( self: Kind, f: (a: A) => Option, onNone: (a: A) => E2 ): Kind => M.flatMap(self, liftOption(F)(f, onNone)) ) } /** @internal */ export const flatMapEither = ( F: FromEither, M: FlatMap ): { (f: (a: A) => Either): (self: Kind) => Kind (self: Kind, f: (a: A) => Either): Kind } => { return /*#__PURE__*/ dual( 2, (self: Kind, f: (a: A) => Either): Kind => M.flatMap(self, (a) => F.fromEither(f(a))) ) } /** @internal */ export const flatMapIO = ( F: FromIO, M: FlatMap ): { (f: (a: A) => IO): (self: Kind) => Kind (self: Kind, f: (a: A) => IO): Kind } => { return /*#__PURE__*/ dual( 2, (self: Kind, f: (a: A) => IO): Kind => M.flatMap(self, (a) => F.fromIO(f(a))) ) } /** @internal */ export const flatMapTask = ( F: FromTask, M: FlatMap ): { (f: (a: A) => Task): (self: Kind) => Kind (self: Kind, f: (a: A) => Task): Kind } => { return /*#__PURE__*/ dual( 2, (self: Kind, f: (a: A) => Task): Kind => M.flatMap(self, (a) => F.fromTask(f(a))) ) } /** @internal */ export const flatMapReader = ( F: FromReader, M: FlatMap ): { (f: (a: A) => Reader): (self: Kind) => Kind (self: Kind, f: (a: A) => Reader): Kind } => { return /*#__PURE__*/ dual( 2, (self: Kind, f: (a: A) => Reader): Kind => M.flatMap(self, (a) => F.fromReader(f(a))) ) } ================================================ FILE: src/number.ts ================================================ /** * @since 2.10.0 */ import * as B from './Bounded' import * as E from './Eq' import * as F from './Field' import { Magma } from './Magma' import { Monoid } from './Monoid' import * as O from './Ord' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import * as S from './Show' // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * @category refinements * @since 2.11.0 */ export const isNumber: Refinement = (u: unknown): u is number => typeof u === 'number' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.10.0 */ export const Eq: E.Eq = { equals: (first, second) => first === second } /** * @category instances * @since 2.10.0 */ export const Ord: O.Ord = { equals: Eq.equals, compare: (first, second) => (first < second ? -1 : first > second ? 1 : 0) } /** * @category instances * @since 2.10.0 */ export const Bounded: B.Bounded = { equals: Eq.equals, compare: Ord.compare, top: Infinity, bottom: -Infinity } /** * @category instances * @since 2.10.0 */ export const Show: S.Show = { show: (n) => JSON.stringify(n) } /** * @category instances * @since 2.11.0 */ export const MagmaSub: Magma = { concat: (first, second) => first - second } /** * `number` semigroup under addition. * * @example * import { SemigroupSum } from 'fp-ts/number' * * assert.deepStrictEqual(SemigroupSum.concat(2, 3), 5) * * @category instances * @since 2.10.0 */ export const SemigroupSum: Semigroup = { concat: (first, second) => first + second } /** * `number` semigroup under multiplication. * * @example * import { SemigroupProduct } from 'fp-ts/number' * * assert.deepStrictEqual(SemigroupProduct.concat(2, 3), 6) * * @category instances * @since 2.10.0 */ export const SemigroupProduct: Semigroup = { concat: (first, second) => first * second } /** * `number` monoid under addition. * * The `empty` value is `0`. * * @example * import { MonoidSum } from 'fp-ts/number' * * assert.deepStrictEqual(MonoidSum.concat(2, MonoidSum.empty), 2) * * @category instances * @since 2.10.0 */ export const MonoidSum: Monoid = { concat: SemigroupSum.concat, empty: 0 } /** * `number` monoid under multiplication. * * The `empty` value is `1`. * * @example * import { MonoidProduct } from 'fp-ts/number' * * assert.deepStrictEqual(MonoidProduct.concat(2, MonoidProduct.empty), 2) * * @category instances * @since 2.10.0 */ export const MonoidProduct: Monoid = { concat: SemigroupProduct.concat, empty: 1 } /** * @category instances * @since 2.10.0 */ export const Field: F.Field = { add: SemigroupSum.concat, zero: 0, mul: SemigroupProduct.concat, one: 1, sub: MagmaSub.concat, degree: (_) => 1, div: (first, second) => first / second, mod: (first, second) => first % second } ================================================ FILE: src/pipeable.ts ================================================ /** * @since 2.0.0 */ import { Alt, Alt1, Alt2, Alt2C, Alt3, Alt3C, Alt4 } from './Alt' import { apFirst as apFirst_, Apply, Apply1, Apply2, Apply2C, Apply3, Apply3C, Apply4, apSecond as apSecond_ } from './Apply' import { Bifunctor, Bifunctor2, Bifunctor2C, Bifunctor3, Bifunctor3C, Bifunctor4 } from './Bifunctor' import { Chain, Chain1, Chain2, Chain2C, Chain3, Chain3C, Chain4, chainFirst as chainFirst_ } from './Chain' import { Compactable, Compactable1, Compactable2, Compactable2C, Compactable3, Compactable3C, Compactable4 } from './Compactable' import { Contravariant, Contravariant1, Contravariant2, Contravariant2C, Contravariant3, Contravariant3C, Contravariant4 } from './Contravariant' import { Either } from './Either' import { Extend, Extend1, Extend2, Extend2C, Extend3, Extend3C, Extend4 } from './Extend' import { Filterable, Filterable1, Filterable2, Filterable2C, Filterable3, Filterable3C, Filterable4 } from './Filterable' import { FilterableWithIndex, FilterableWithIndex1, FilterableWithIndex2, FilterableWithIndex2C, FilterableWithIndex3, FilterableWithIndex3C, FilterableWithIndex4, PredicateWithIndex, RefinementWithIndex } from './FilterableWithIndex' import { Foldable, Foldable1, Foldable2, Foldable2C, Foldable3, Foldable3C, Foldable4 } from './Foldable' import { FoldableWithIndex, FoldableWithIndex1, FoldableWithIndex2, FoldableWithIndex2C, FoldableWithIndex3, FoldableWithIndex3C, FoldableWithIndex4 } from './FoldableWithIndex' import { identity, LazyArg, pipe as pipeFromFunctionModule } from './function' import { Functor, Functor1, Functor2, Functor2C, Functor3, Functor3C, Functor4 } from './Functor' import { FunctorWithIndex, FunctorWithIndex1, FunctorWithIndex2, FunctorWithIndex2C, FunctorWithIndex3, FunctorWithIndex3C, FunctorWithIndex4 } from './FunctorWithIndex' import { HKT, HKT2, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from './HKT' import { MonadThrow, MonadThrow1, MonadThrow2, MonadThrow2C, MonadThrow3, MonadThrow3C, MonadThrow4 } from './MonadThrow' import { Monoid } from './Monoid' import { Option } from './Option' import { Predicate } from './Predicate' import { Profunctor, Profunctor2, Profunctor2C, Profunctor3, Profunctor3C, Profunctor4 } from './Profunctor' import { Refinement } from './Refinement' import { Semigroupoid, Semigroupoid2, Semigroupoid2C, Semigroupoid3, Semigroupoid3C, Semigroupoid4 } from './Semigroupoid' import { Separated } from './Separated' // ------------------------------------------------------------------------------------- // pipeable helpers // ------------------------------------------------------------------------------------- /** * Returns a pipeable `map` * * @category pipeable helper * @since 2.13.0 */ export function map( F: Functor4 ): (f: (a: A) => B) => (fa: Kind4) => Kind4 export function map( F: Functor3 ): (f: (a: A) => B) => (fa: Kind3) => Kind3 export function map( F: Functor3C ): (f: (a: A) => B) => (fa: Kind3) => Kind3 export function map( F: Functor2 ): (f: (a: A) => B) => (fa: Kind2) => Kind2 export function map( F: Functor2C ): (f: (a: A) => B) => (fa: Kind2) => Kind2 export function map(F: Functor1): (f: (a: A) => B) => (fa: Kind) => Kind export function map(F: Functor): (f: (a: A) => B) => (fa: HKT) => HKT export function map(F: Functor): (f: (a: A) => B) => (fa: HKT) => HKT { return (f) => (fa) => F.map(fa, f) } /** * Returns a pipeable `contramap` * * @category pipeable helper * @since 2.13.0 */ export function contramap( F: Contravariant4 ): (f: (b: B) => A) => (fa: Kind4) => Kind4 export function contramap( F: Contravariant3 ): (f: (b: B) => A) => (fa: Kind3) => Kind3 export function contramap( F: Contravariant3C ): (f: (b: B) => A) => (fa: Kind3) => Kind3 export function contramap( F: Contravariant2 ): (f: (b: B) => A) => (fa: Kind2) => Kind2 export function contramap( F: Contravariant2C ): (f: (b: B) => A) => (fa: Kind2) => Kind2 export function contramap( F: Contravariant1 ): (f: (b: B) => A) => (fa: Kind) => Kind export function contramap(F: Contravariant): (f: (b: B) => A) => (fa: HKT) => HKT export function contramap(F: Contravariant): (f: (b: B) => A) => (fa: HKT) => HKT { return (f) => (fa) => F.contramap(fa, f) } /** * Returns a pipeable `mapWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function mapWithIndex( F: FunctorWithIndex4 ): (f: (i: I, a: A) => B) => (fa: Kind4) => Kind4 export function mapWithIndex( F: FunctorWithIndex3 ): (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 export function mapWithIndex( F: FunctorWithIndex3C ): (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 export function mapWithIndex( F: FunctorWithIndex2 ): (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 export function mapWithIndex( F: FunctorWithIndex2C ): (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 export function mapWithIndex( F: FunctorWithIndex1 ): (f: (i: I, a: A) => B) => (fa: Kind) => Kind export function mapWithIndex( F: FunctorWithIndex ): (f: (i: I, a: A) => B) => (fa: HKT) => HKT export function mapWithIndex( F: FunctorWithIndex ): (f: (i: I, a: A) => B) => (fa: HKT) => HKT { return (f) => (fa) => F.mapWithIndex(fa, f) } /** * Returns a pipeable `ap` * * @category pipeable helper * @since 2.13.0 */ export function ap( F: Apply4 ): (fa: Kind4) => (fab: Kind4 B>) => Kind4 export function ap( F: Apply3 ): (fa: Kind3) => (fab: Kind3 B>) => Kind3 export function ap( F: Apply3C ): (fa: Kind3) => (fab: Kind3 B>) => Kind3 export function ap( F: Apply2 ): (fa: Kind2) => (fab: Kind2 B>) => Kind2 export function ap( F: Apply2C ): (fa: Kind2) => (fab: Kind2 B>) => Kind2 export function ap(F: Apply1): (fa: Kind) => (fab: Kind B>) => Kind export function ap(F: Apply): (fa: HKT) => (fab: HKT B>) => HKT export function ap(F: Apply): (fa: HKT) => (fab: HKT B>) => HKT { return (fa) => (fab) => F.ap(fab, fa) } /** * Returns a pipeable `chain` * * @category pipeable helper * @since 2.13.0 */ export function chain( F: Chain4 ): (f: (a: A) => Kind4) => (fa: Kind4) => Kind4 export function chain( F: Chain3 ): (f: (a: A) => Kind3) => (fa: Kind3) => Kind3 export function chain( F: Chain3C ): (f: (a: A) => Kind3) => (fa: Kind3) => Kind3 export function chain( F: Chain2 ): (f: (a: A) => Kind2) => (fa: Kind2) => Kind2 export function chain( F: Chain2C ): (f: (a: A) => Kind2) => (fa: Kind2) => Kind2 export function chain(F: Chain1): (f: (a: A) => Kind) => (fa: Kind) => Kind export function chain(F: Chain): (f: (a: A) => HKT) => (fa: HKT) => HKT export function chain(F: Chain): (f: (a: A) => HKT) => (fa: HKT) => HKT { return (f) => (fa) => F.chain(fa, f) } /** * Returns a pipeable `bimap` * * @category pipeable helper * @since 2.13.0 */ export function bimap( F: Bifunctor4 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind4) => Kind4 export function bimap( F: Bifunctor3 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind3) => Kind3 export function bimap( F: Bifunctor3C ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind3) => Kind3 export function bimap( F: Bifunctor2 ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2) => Kind2 export function bimap( F: Bifunctor2C ): (f: (e: E) => G, g: (a: A) => B) => (fea: Kind2) => Kind2 export function bimap( F: Bifunctor ): (f: (e: E) => G, g: (a: A) => B) => (fea: HKT2) => HKT2 export function bimap( F: Bifunctor ): (f: (e: E) => G, g: (a: A) => B) => (fea: HKT2) => HKT2 { return (f, g) => (fea) => F.bimap(fea, f, g) } /** * Returns a pipeable `mapLeft` * * @category pipeable helper * @since 2.13.0 */ export function mapLeft( F: Bifunctor4 ): (f: (e: E) => G) => (fea: Kind4) => Kind4 export function mapLeft( F: Bifunctor3 ): (f: (e: E) => G) => (fea: Kind3) => Kind3 export function mapLeft( F: Bifunctor3C ): (f: (e: E) => G) => (fea: Kind3) => Kind3 export function mapLeft( F: Bifunctor2 ): (f: (e: E) => G) => (fea: Kind2) => Kind2 export function mapLeft( F: Bifunctor2C ): (f: (e: E) => G) => (fea: Kind2) => Kind2 export function mapLeft(F: Bifunctor): (f: (e: E) => G) => (fea: HKT2) => HKT2 export function mapLeft(F: Bifunctor): (f: (e: E) => G) => (fea: HKT2) => HKT2 { return (f) => (fea) => F.mapLeft(fea, f) } /** * Returns a pipeable `extend` * * @category pipeable helper * @since 2.13.0 */ export function extend( F: Extend4 ): (f: (wa: Kind4) => B) => (wa: Kind4) => Kind4 export function extend( F: Extend3 ): (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 export function extend( F: Extend3C ): (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 export function extend( F: Extend2 ): (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 export function extend( F: Extend2C ): (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 export function extend( F: Extend1 ): (f: (wa: Kind) => B) => (wa: Kind) => Kind export function extend(F: Extend): (f: (wa: HKT) => B) => (wa: HKT) => HKT export function extend(F: Extend): (f: (wa: HKT) => B) => (wa: HKT) => HKT { return (f) => (wa) => F.extend(wa, f) } /** * Returns a pipeable `reduce` * * @category pipeable helper * @since 2.13.0 */ export function reduce( F: Foldable4 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind4) => B export function reduce( F: Foldable3 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B export function reduce( F: Foldable3C ): (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B export function reduce( F: Foldable2 ): (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B export function reduce( F: Foldable2C ): (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B export function reduce(F: Foldable1): (b: B, f: (b: B, a: A) => B) => (fa: Kind) => B export function reduce(F: Foldable): (b: B, f: (b: B, a: A) => B) => (fa: HKT) => B export function reduce(F: Foldable): (b: B, f: (b: B, a: A) => B) => (fa: HKT) => B { return (b, f) => (fa) => F.reduce(fa, b, f) } /** * Returns a pipeable `foldMap` * * @category pipeable helper * @since 2.13.0 */ export function foldMap( F: Foldable4 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind4) => M export function foldMap( F: Foldable3 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M export function foldMap( F: Foldable3C ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M export function foldMap( F: Foldable2 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M export function foldMap( F: Foldable2C ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M export function foldMap( F: Foldable1 ): (M: Monoid) => (f: (a: A) => M) => (fa: Kind) => M export function foldMap(F: Foldable): (M: Monoid) => (f: (a: A) => M) => (fa: HKT) => M export function foldMap(F: Foldable): (M: Monoid) => (f: (a: A) => M) => (fa: HKT) => M { return (M) => { const foldMapM = F.foldMap(M) return (f) => (fa) => foldMapM(fa, f) } } /** * Returns a pipeable `reduceRight` * * @category pipeable helper * @since 2.13.0 */ export function reduceRight( F: Foldable4 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind4) => B export function reduceRight( F: Foldable3 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B export function reduceRight( F: Foldable3C ): (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B export function reduceRight( F: Foldable2 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B export function reduceRight( F: Foldable2C ): (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B export function reduceRight( F: Foldable1 ): (b: B, f: (a: A, b: B) => B) => (fa: Kind) => B export function reduceRight(F: Foldable): (b: B, f: (a: A, b: B) => B) => (fa: HKT) => B export function reduceRight(F: Foldable): (b: B, f: (a: A, b: B) => B) => (fa: HKT) => B { return (b, f) => (fa) => F.reduceRight(fa, b, f) } /** * Returns a pipeable `reduceWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function reduceWithIndex( F: FoldableWithIndex4 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind4) => B export function reduceWithIndex( F: FoldableWithIndex3 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B export function reduceWithIndex( F: FoldableWithIndex3C ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B export function reduceWithIndex( F: FoldableWithIndex2 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B export function reduceWithIndex( F: FoldableWithIndex2C ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B export function reduceWithIndex( F: FoldableWithIndex1 ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind) => B export function reduceWithIndex( F: FoldableWithIndex ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: HKT) => B export function reduceWithIndex( F: FoldableWithIndex ): (b: B, f: (i: I, b: B, a: A) => B) => (fa: HKT) => B { return (b, f) => (fa) => F.reduceWithIndex(fa, b, f) } /** * Returns a pipeable `foldMapWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function foldMapWithIndex( F: FoldableWithIndex4 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind4) => M export function foldMapWithIndex( F: FoldableWithIndex3 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M export function foldMapWithIndex( F: FoldableWithIndex3C ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M export function foldMapWithIndex( F: FoldableWithIndex2 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M export function foldMapWithIndex( F: FoldableWithIndex2C ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M export function foldMapWithIndex( F: FoldableWithIndex1 ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind) => M export function foldMapWithIndex( F: FoldableWithIndex ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: HKT) => M export function foldMapWithIndex( F: FoldableWithIndex ): (M: Monoid) => (f: (i: I, a: A) => M) => (fa: HKT) => M { return (M) => { const foldMapWithIndexM = F.foldMapWithIndex(M) return (f) => (fa) => foldMapWithIndexM(fa, f) } } /** * Returns a pipeable `reduceRightWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function reduceRightWithIndex( F: FoldableWithIndex4 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind4) => B export function reduceRightWithIndex( F: FoldableWithIndex3 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B export function reduceRightWithIndex( F: FoldableWithIndex3C ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B export function reduceRightWithIndex( F: FoldableWithIndex2 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B export function reduceRightWithIndex( F: FoldableWithIndex2C ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B export function reduceRightWithIndex( F: FoldableWithIndex1 ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind) => B export function reduceRightWithIndex( F: FoldableWithIndex ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: HKT) => B export function reduceRightWithIndex( F: FoldableWithIndex ): (b: B, f: (i: I, a: A, b: B) => B) => (fa: HKT) => B { return (b, f) => (fa) => F.reduceRightWithIndex(fa, b, f) } /** * Returns a pipeable `alt` * * @category pipeable helper * @since 2.13.0 */ export function alt( F: Alt4 ): (that: LazyArg>) => (fa: Kind4) => Kind4 export function alt( F: Alt3 ): (that: LazyArg>) => (fa: Kind3) => Kind3 export function alt( F: Alt3C ): (that: LazyArg>) => (fa: Kind3) => Kind3 export function alt( F: Alt2 ): (that: LazyArg>) => (fa: Kind2) => Kind2 export function alt( F: Alt2C ): (that: LazyArg>) => (fa: Kind2) => Kind2 export function alt(F: Alt1): (that: LazyArg>) => (fa: Kind) => Kind export function alt(F: Alt): (that: LazyArg>) => (fa: HKT) => HKT export function alt(F: Alt): (that: LazyArg>) => (fa: HKT) => HKT { return (that) => (fa) => F.alt(fa, that) } /** * Returns a pipeable `filter` * * @category pipeable helper * @since 2.13.0 */ export function filter( F: Filterable4 ): { (refinement: Refinement): (fa: Kind4) => Kind4 (predicate: Predicate): (fa: Kind4) => Kind4 } export function filter( F: Filterable3 ): { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } export function filter( F: Filterable3C ): { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } export function filter( F: Filterable2 ): { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } export function filter( F: Filterable2C ): { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } export function filter( F: Filterable1 ): { (refinement: Refinement): (fa: Kind) => Kind (predicate: Predicate): (fa: Kind) => Kind } export function filter(F: Filterable): { (refinement: Refinement): (fa: HKT) => HKT (predicate: Predicate): (fa: HKT) => HKT } export function filter(F: Filterable): (predicate: Predicate) => (fa: HKT) => HKT { return (predicate) => (fa) => F.filter(fa, predicate) } /** * Returns a pipeable `filterMap` * * @category pipeable helper * @since 2.13.0 */ export function filterMap( F: Filterable4 ): (f: (a: A) => Option) => (fa: Kind4) => Kind4 export function filterMap( F: Filterable3 ): (f: (a: A) => Option) => (fa: Kind3) => Kind3 export function filterMap( F: Filterable3C ): (f: (a: A) => Option) => (fa: Kind3) => Kind3 export function filterMap( F: Filterable2 ): (f: (a: A) => Option) => (fa: Kind2) => Kind2 export function filterMap( F: Filterable2C ): (f: (a: A) => Option) => (fa: Kind2) => Kind2 export function filterMap( F: Filterable1 ): (f: (a: A) => Option) => (fa: Kind) => Kind export function filterMap(F: Filterable): (f: (a: A) => Option) => (fa: HKT) => HKT export function filterMap(F: Filterable): (f: (a: A) => Option) => (fa: HKT) => HKT { return (f) => (fa) => F.filterMap(fa, f) } /** * Returns a pipeable `partition` * * @category pipeable helper * @since 2.13.0 */ export function partition( F: Filterable4 ): { (refinement: Refinement): ( fa: Kind4 ) => Separated, Kind4> (predicate: Predicate): ( fa: Kind4 ) => Separated, Kind4> } export function partition( F: Filterable3 ): { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } export function partition( F: Filterable3C ): { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } export function partition( F: Filterable2 ): { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } export function partition( F: Filterable2C ): { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } export function partition( F: Filterable1 ): { (refinement: Refinement): (fa: Kind) => Separated, Kind> (predicate: Predicate): (fa: Kind) => Separated, Kind> } export function partition(F: Filterable): { (refinement: Refinement): (fa: HKT) => Separated, HKT> (predicate: Predicate): (fa: HKT) => Separated, HKT> } export function partition( F: Filterable ): (predicate: Predicate) => (fa: HKT) => Separated, HKT> { return (f) => (fa) => F.partition(fa, f) } /** * Returns a pipeable `partitionMap` * * @category pipeable helper * @since 2.13.0 */ export function partitionMap( F: Filterable4 ): ( f: (a: A) => Either ) => (fa: Kind4) => Separated, Kind4> export function partitionMap( F: Filterable3 ): ( f: (a: A) => Either ) => (fa: Kind3) => Separated, Kind3> export function partitionMap( F: Filterable3C ): (f: (a: A) => Either) => (fa: Kind3) => Separated, Kind3> export function partitionMap( F: Filterable2 ): (f: (a: A) => Either) => (fa: Kind2) => Separated, Kind2> export function partitionMap( F: Filterable2C ): (f: (a: A) => Either) => (fa: Kind2) => Separated, Kind2> export function partitionMap( F: Filterable1 ): (f: (a: A) => Either) => (fa: Kind) => Separated, Kind> export function partitionMap( F: Filterable ): (f: (a: A) => Either) => (fa: HKT) => Separated, HKT> export function partitionMap( F: Filterable ): (f: (a: A) => Either) => (fa: HKT) => Separated, HKT> { return (f) => (fa) => F.partitionMap(fa, f) } /** * Returns a pipeable `filterWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function filterWithIndex( F: FilterableWithIndex4 ): { (refinement: RefinementWithIndex): ( fa: Kind4 ) => Kind4 (predicate: PredicateWithIndex): (fa: Kind4) => Kind4 } export function filterWithIndex( F: FilterableWithIndex3 ): { (refinement: RefinementWithIndex): (fa: Kind3) => Kind3 (predicate: PredicateWithIndex): (fa: Kind3) => Kind3 } export function filterWithIndex( F: FilterableWithIndex3C ): { (refinement: RefinementWithIndex): (fa: Kind3) => Kind3 (predicate: PredicateWithIndex): (fa: Kind3) => Kind3 } export function filterWithIndex( F: FilterableWithIndex2 ): { (refinement: RefinementWithIndex): (fa: Kind2) => Kind2 (predicate: PredicateWithIndex): (fa: Kind2) => Kind2 } export function filterWithIndex( F: FilterableWithIndex2C ): { (refinement: RefinementWithIndex): (fa: Kind2) => Kind2 (predicate: PredicateWithIndex): (fa: Kind2) => Kind2 } export function filterWithIndex( F: FilterableWithIndex1 ): { (refinement: RefinementWithIndex): (fa: Kind) => Kind (predicate: PredicateWithIndex): (fa: Kind) => Kind } export function filterWithIndex( F: FilterableWithIndex ): { (refinement: RefinementWithIndex): (fa: HKT) => HKT (predicate: PredicateWithIndex): (fa: HKT) => HKT } export function filterWithIndex( F: FilterableWithIndex ): (predicate: PredicateWithIndex) => (fa: HKT) => HKT { return (predicate) => (fa) => F.filterWithIndex(fa, predicate) } /** * Returns a pipeable `filterMapWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function filterMapWithIndex( F: FilterableWithIndex4 ): (f: (i: I, a: A) => Option) => (fa: Kind4) => Kind4 export function filterMapWithIndex( F: FilterableWithIndex3 ): (f: (i: I, a: A) => Option) => (fa: Kind3) => Kind3 export function filterMapWithIndex( F: FilterableWithIndex3C ): (f: (i: I, a: A) => Option) => (fa: Kind3) => Kind3 export function filterMapWithIndex( F: FilterableWithIndex2 ): (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 export function filterMapWithIndex( F: FilterableWithIndex2C ): (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 export function filterMapWithIndex( F: FilterableWithIndex1 ): (f: (i: I, a: A) => Option) => (fa: Kind) => Kind export function filterMapWithIndex( F: FilterableWithIndex ): (f: (i: I, a: A) => Option) => (fa: HKT) => HKT export function filterMapWithIndex( F: FilterableWithIndex ): (f: (i: I, a: A) => Option) => (fa: HKT) => HKT { return (f) => (fa) => F.filterMapWithIndex(fa, f) } /** * Returns a pipeable `partitionWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function partitionWithIndex( F: FilterableWithIndex4 ): { (refinement: RefinementWithIndex): ( fa: Kind4 ) => Separated, Kind4> (predicate: PredicateWithIndex): ( fa: Kind4 ) => Separated, Kind4> } export function partitionWithIndex( F: FilterableWithIndex3 ): { (refinement: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicate: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } export function partitionWithIndex( F: FilterableWithIndex3C ): { (refinement: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicate: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } export function partitionWithIndex( F: FilterableWithIndex2 ): { (refinement: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicate: PredicateWithIndex): (fa: Kind2) => Separated, Kind2> } export function partitionWithIndex( F: FilterableWithIndex2C ): { (refinement: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicate: PredicateWithIndex): (fa: Kind2) => Separated, Kind2> } export function partitionWithIndex( F: FilterableWithIndex1 ): { (refinement: RefinementWithIndex): (fa: Kind) => Separated, Kind> (predicate: PredicateWithIndex): (fa: Kind) => Separated, Kind> } export function partitionWithIndex( F: FilterableWithIndex ): { (refinement: RefinementWithIndex): (fa: HKT) => Separated, HKT> (predicate: PredicateWithIndex): (fa: HKT) => Separated, HKT> } export function partitionWithIndex( F: FilterableWithIndex ): (predicate: PredicateWithIndex) => (fa: HKT) => Separated, HKT> { return (f) => (fa) => F.partitionWithIndex(fa, f) } /** * Returns a pipeable `partitionMapWithIndex` * * @category pipeable helper * @since 2.13.0 */ export function partitionMapWithIndex( F: FilterableWithIndex4 ): ( f: (i: I, a: A) => Either ) => (fa: Kind4) => Separated, Kind4> export function partitionMapWithIndex( F: FilterableWithIndex3 ): ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> export function partitionMapWithIndex( F: FilterableWithIndex3C ): ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> export function partitionMapWithIndex( F: FilterableWithIndex2 ): (f: (i: I, a: A) => Either) => (fa: Kind2) => Separated, Kind2> export function partitionMapWithIndex( F: FilterableWithIndex2C ): (f: (i: I, a: A) => Either) => (fa: Kind2) => Separated, Kind2> export function partitionMapWithIndex( F: FilterableWithIndex1 ): (f: (i: I, a: A) => Either) => (fa: Kind) => Separated, Kind> export function partitionMapWithIndex( F: FilterableWithIndex ): (f: (i: I, a: A) => Either) => (fa: HKT) => Separated, HKT> export function partitionMapWithIndex( F: FilterableWithIndex ): (f: (i: I, a: A) => Either) => (fa: HKT) => Separated, HKT> { return (f) => (fa) => F.partitionMapWithIndex(fa, f) } /** * Returns a pipeable `promap` * * @category pipeable helper * @since 2.13.0 */ export function promap( F: Profunctor4 ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind4) => Kind4 export function promap( F: Profunctor3 ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 export function promap( F: Profunctor3C ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 export function promap( F: Profunctor2 ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 export function promap( F: Profunctor2C ): (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 export function promap( F: Profunctor ): (f: (d: D) => E, g: (a: A) => B) => (fbc: HKT2) => HKT2 export function promap( F: Profunctor ): (f: (d: D) => E, g: (a: A) => B) => (fbc: HKT2) => HKT2 { return (f, g) => (fbc) => F.promap(fbc, f, g) } /** * Returns a pipeable `compose` * * @category pipeable helper * @since 2.13.0 */ export function compose( F: Semigroupoid4 ): (ea: Kind4) => (ab: Kind4) => Kind4 export function compose( F: Semigroupoid3 ): (ea: Kind3) => (ab: Kind3) => Kind3 export function compose( F: Semigroupoid3C ): (ea: Kind3) => (ab: Kind3) => Kind3 export function compose( F: Semigroupoid2 ): (ea: Kind2) => (ab: Kind2) => Kind2 export function compose( F: Semigroupoid2C ): (ea: Kind2) => (ab: Kind2) => Kind2 export function compose(F: Semigroupoid): (ea: HKT2) => (ab: HKT2) => HKT2 export function compose(F: Semigroupoid): (ea: HKT2) => (ab: HKT2) => HKT2 { return (ea) => (ab) => F.compose(ab, ea) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctor { readonly map: (f: (a: A) => B) => (fa: HKT) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctor1 { readonly map: (f: (a: A) => B) => (fa: Kind) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctor2 { readonly map: (f: (a: A) => B) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctor2C { readonly map: (f: (a: A) => B) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctor3 { readonly map: (f: (a: A) => B) => (fa: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableFunctor3C { readonly map: (f: (a: A) => B) => (fa: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctor4 { readonly map: (f: (a: A) => B) => (fa: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableContravariant { readonly contramap: (f: (b: B) => A) => (fa: HKT) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableContravariant1 { readonly contramap: (f: (b: B) => A) => (fa: Kind) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableContravariant2 { readonly contramap: (f: (b: B) => A) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableContravariant2C { readonly contramap: (f: (b: B) => A) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableContravariant3 { readonly contramap: (f: (b: B) => A) => (fa: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableContravariant3C { readonly contramap: (f: (b: B) => A) => (fa: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableContravariant4 { readonly contramap: (f: (b: B) => A) => (fa: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctorWithIndex extends PipeableFunctor { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: HKT) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctorWithIndex1 extends PipeableFunctor1 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctorWithIndex2 extends PipeableFunctor2 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctorWithIndex2C extends PipeableFunctor2C { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctorWithIndex3 extends PipeableFunctor3 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableFunctorWithIndex3C extends PipeableFunctor3C { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFunctorWithIndex4 extends PipeableFunctor4 { readonly mapWithIndex: (f: (i: I, a: A) => B) => (fa: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableApply extends PipeableFunctor { readonly ap: (fa: HKT) => (fab: HKT B>) => HKT readonly apFirst: (fb: HKT) => (fa: HKT) => HKT readonly apSecond: (fb: HKT) => (fa: HKT) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableApply1 extends PipeableFunctor1 { readonly ap: (fa: Kind) => (fab: Kind B>) => Kind readonly apFirst: (fb: Kind) => (fa: Kind) => Kind readonly apSecond: (fb: Kind) => (fa: Kind) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableApply2 extends PipeableFunctor2 { readonly ap: (fa: Kind2) => (fab: Kind2 B>) => Kind2 readonly apFirst: (fb: Kind2) => (fa: Kind2) => Kind2 readonly apSecond: (fb: Kind2) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableApply2C extends PipeableFunctor2C { readonly ap: (fa: Kind2) => (fab: Kind2 B>) => Kind2 readonly apFirst: (fb: Kind2) => (fa: Kind2) => Kind2 readonly apSecond: (fb: Kind2) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableApply3 extends PipeableFunctor3 { readonly ap: (fa: Kind3) => (fab: Kind3 B>) => Kind3 readonly apFirst: (fb: Kind3) => (fa: Kind3) => Kind3 readonly apSecond: (fb: Kind3) => (fa: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableApply3C extends PipeableFunctor3C { readonly ap: (fa: Kind3) => (fab: Kind3 B>) => Kind3 readonly apFirst: (fb: Kind3) => (fa: Kind3) => Kind3 readonly apSecond: (fb: Kind3) => (fa: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableApply4 extends PipeableFunctor4 { readonly ap: ( fa: Kind4 ) => (fab: Kind4 B>) => Kind4 readonly apFirst: (fb: Kind4) => (fa: Kind4) => Kind4 readonly apSecond: (fb: Kind4) => (fa: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableChain extends PipeableApply { readonly chain: (f: (a: A) => HKT) => (ma: HKT) => HKT readonly chainFirst: (f: (a: A) => HKT) => (ma: HKT) => HKT readonly flatten: (mma: HKT>) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableChain1 extends PipeableApply1 { readonly chain: (f: (a: A) => Kind) => (ma: Kind) => Kind readonly chainFirst: (f: (a: A) => Kind) => (ma: Kind) => Kind readonly flatten: (mma: Kind>) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableChain2 extends PipeableApply2 { readonly chain: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly chainFirst: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly flatten: (mma: Kind2>) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableChain2C extends PipeableApply2C { readonly chain: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly chainFirst: (f: (a: A) => Kind2) => (ma: Kind2) => Kind2 readonly flatten: (mma: Kind2>) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableChain3 extends PipeableApply3 { readonly chain: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly chainFirst: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly flatten: (mma: Kind3>) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableChain3C extends PipeableApply3C { readonly chain: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly chainFirst: (f: (a: A) => Kind3) => (ma: Kind3) => Kind3 readonly flatten: (mma: Kind3>) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableChain4 extends PipeableApply4 { readonly chain: ( f: (a: A) => Kind4 ) => (ma: Kind4) => Kind4 readonly chainFirst: ( f: (a: A) => Kind4 ) => (ma: Kind4) => Kind4 readonly flatten: (mma: Kind4>) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableExtend extends PipeableFunctor { readonly extend: (f: (wa: HKT) => B) => (wa: HKT) => HKT readonly duplicate: (wa: HKT) => HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableExtend1 extends PipeableFunctor1 { readonly extend: (f: (wa: Kind) => B) => (wa: Kind) => Kind readonly duplicate: (wa: Kind) => Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableExtend2 extends PipeableFunctor2 { readonly extend: (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 readonly duplicate: (wa: Kind2) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableExtend2C extends PipeableFunctor2C { readonly extend: (f: (wa: Kind2) => B) => (wa: Kind2) => Kind2 readonly duplicate: (wa: Kind2) => Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableExtend3 extends PipeableFunctor3 { readonly extend: (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 readonly duplicate: (wa: Kind3) => Kind3> } /** * @since 2.2.0 * @deprecated */ export interface PipeableExtend3C extends PipeableFunctor3C { readonly extend: (f: (wa: Kind3) => B) => (wa: Kind3) => Kind3 readonly duplicate: (wa: Kind3) => Kind3> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableExtend4 extends PipeableFunctor4 { readonly extend: ( f: (wa: Kind4) => B ) => (wa: Kind4) => Kind4 readonly duplicate: (wa: Kind4) => Kind4> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableBifunctor { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: HKT2) => HKT2 readonly mapLeft: (f: (e: E) => G) => (fa: HKT2) => HKT2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableBifunctor2 { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Kind2) => Kind2 readonly mapLeft: (f: (e: E) => G) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableBifunctor3 { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Kind3) => Kind3 readonly mapLeft: (f: (e: E) => G) => (fa: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableBifunctor3C { readonly bimap: (f: (e: E) => G, g: (a: A) => B) => (fa: Kind3) => Kind3 readonly mapLeft: (f: (e: E) => G) => (fa: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableBifunctor4 { readonly bimap: ( f: (e: E) => G, g: (a: A) => B ) => (fa: Kind4) => Kind4 readonly mapLeft: (f: (e: E) => G) => (fa: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldable { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: HKT) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: HKT) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: HKT) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldable1 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldable2 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldable2C { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind2) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind2) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind2) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldable3 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B } /** * @since 2.2.0 * @deprecated */ export interface PipeableFoldable3C { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind3) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind3) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind3) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldable4 { readonly reduce: (b: B, f: (b: B, a: A) => B) => (fa: Kind4) => B readonly foldMap: (M: Monoid) => (f: (a: A) => M) => (fa: Kind4) => M readonly reduceRight: (b: B, f: (a: A, b: B) => B) => (fa: Kind4) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldableWithIndex extends PipeableFoldable { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: HKT) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: HKT) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: HKT) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldableWithIndex1 extends PipeableFoldable1 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldableWithIndex2 extends PipeableFoldable2 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldableWithIndex2C extends PipeableFoldable2C { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind2) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind2) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind2) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldableWithIndex3 extends PipeableFoldable3 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B } /** * @since 2.2.0 * @deprecated */ export interface PipeableFoldableWithIndex3C extends PipeableFoldable3C { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind3) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind3) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind3) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFoldableWithIndex4 extends PipeableFoldable4 { readonly reduceWithIndex: (b: B, f: (i: I, b: B, a: A) => B) => (fa: Kind4) => B readonly foldMapWithIndex: (M: Monoid) => (f: (i: I, a: A) => M) => (fa: Kind4) => M readonly reduceRightWithIndex: (b: B, f: (i: I, a: A, b: B) => B) => (fa: Kind4) => B } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableAlt { readonly alt: (that: LazyArg>) => (fa: HKT) => HKT } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableAlt1 { readonly alt: (that: LazyArg>) => (fa: Kind) => Kind } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableAlt2 { readonly alt: (that: LazyArg>) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableAlt2C { readonly alt: (that: LazyArg>) => (fa: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableAlt3 { readonly alt: (that: LazyArg>) => (fa: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableAlt3C { readonly alt: (that: LazyArg>) => (fa: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableAlt4 { readonly alt: (that: LazyArg>) => (fa: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableCompactable { readonly compact: (fa: HKT>) => HKT readonly separate: (fa: HKT>) => Separated, HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableCompactable1 { readonly compact: (fa: Kind>) => Kind readonly separate: (fa: Kind>) => Separated, Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableCompactable2 { readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => Separated, Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableCompactable2C { readonly compact: (fa: Kind2>) => Kind2 readonly separate: (fa: Kind2>) => Separated, Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableCompactable3 { readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => Separated, Kind3> } /** * @since 2.2.0 * @deprecated */ export interface PipeableCompactable3C { readonly compact: (fa: Kind3>) => Kind3 readonly separate: (fa: Kind3>) => Separated, Kind3> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableCompactable4 { readonly compact: (fa: Kind4>) => Kind4 readonly separate: ( fa: Kind4> ) => Separated, Kind4> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterable extends PipeableCompactable { readonly filter: { (refinement: Refinement): (fa: HKT) => HKT (predicate: Predicate): (fa: HKT) => HKT } readonly filterMap: (f: (a: A) => Option) => (fa: HKT) => HKT readonly partition: { (refinement: Refinement): (fa: HKT) => Separated, HKT> (predicate: Predicate): (fa: HKT) => Separated, HKT> } readonly partitionMap: (f: (a: A) => Either) => (fa: HKT) => Separated, HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterable1 extends PipeableCompactable1 { readonly filter: { (refinement: Refinement): (fa: Kind) => Kind (predicate: Predicate): (fa: Kind) => Kind } readonly filterMap: (f: (a: A) => Option) => (fa: Kind) => Kind readonly partition: { (refinement: Refinement): (fa: Kind) => Separated, Kind> (predicate: Predicate): (fa: Kind) => Separated, Kind> } readonly partitionMap: (f: (a: A) => Either) => (fa: Kind) => Separated, Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterable2 extends PipeableCompactable2 { readonly filter: { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind2) => Kind2 readonly partition: { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterable2C extends PipeableCompactable2C { readonly filter: { (refinement: Refinement): (fa: Kind2) => Kind2 (predicate: Predicate): (fa: Kind2) => Kind2 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind2) => Kind2 readonly partition: { (refinement: Refinement): (fa: Kind2) => Separated, Kind2> (predicate: Predicate): (fa: Kind2) => Separated, Kind2> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterable3 extends PipeableCompactable3 { readonly filter: { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind3) => Kind3 readonly partition: { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } /** * @since 2.2.0 * @deprecated */ export interface PipeableFilterable3C extends PipeableCompactable3C { readonly filter: { (refinement: Refinement): (fa: Kind3) => Kind3 (predicate: Predicate): (fa: Kind3) => Kind3 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind3) => Kind3 readonly partition: { (refinement: Refinement): ( fa: Kind3 ) => Separated, Kind3> (predicate: Predicate): (fa: Kind3) => Separated, Kind3> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterable4 extends PipeableCompactable4 { readonly filter: { (refinement: Refinement): (fa: Kind4) => Kind4 (predicate: Predicate): (fa: Kind4) => Kind4 } readonly filterMap: (f: (a: A) => Option) => (fa: Kind4) => Kind4 readonly partition: { (refinement: Refinement): ( fa: Kind4 ) => Separated, Kind4> (predicate: Predicate): ( fa: Kind4 ) => Separated, Kind4> } readonly partitionMap: ( f: (a: A) => Either ) => (fa: Kind4) => Separated, Kind4> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterableWithIndex extends PipeableFilterable { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: HKT) => HKT (predicateWithIndex: PredicateWithIndex): (fa: HKT) => HKT } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: HKT) => HKT readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: HKT ) => Separated, HKT> (predicateWithIndex: PredicateWithIndex): (fa: HKT) => Separated, HKT> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: HKT) => Separated, HKT> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterableWithIndex1 extends PipeableFilterable1 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind) => Kind (predicateWithIndex: PredicateWithIndex): (fa: Kind) => Kind } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind) => Kind readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind ) => Separated, Kind> (predicateWithIndex: PredicateWithIndex): (fa: Kind) => Separated, Kind> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind) => Separated, Kind> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterableWithIndex2 extends PipeableFilterable2 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind2) => Kind2 (predicateWithIndex: PredicateWithIndex): (fa: Kind2) => Kind2 } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicateWithIndex: PredicateWithIndex): ( fa: Kind2 ) => Separated, Kind2> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterableWithIndex2C extends PipeableFilterable2C { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind2) => Kind2 (predicateWithIndex: PredicateWithIndex): (fa: Kind2) => Kind2 } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind2) => Kind2 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind2 ) => Separated, Kind2> (predicateWithIndex: PredicateWithIndex): (fa: Kind2) => Separated, Kind2> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind2) => Separated, Kind2> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterableWithIndex3 extends PipeableFilterable3 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind3 ) => Kind3 (predicateWithIndex: PredicateWithIndex): (fa: Kind3) => Kind3 } readonly filterMapWithIndex: ( f: (i: I, a: A) => Option ) => (fa: Kind3) => Kind3 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicateWithIndex: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } /** * @since 2.2.0 * @deprecated */ export interface PipeableFilterableWithIndex3C extends PipeableFilterable3C { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): (fa: Kind3) => Kind3 (predicateWithIndex: PredicateWithIndex): (fa: Kind3) => Kind3 } readonly filterMapWithIndex: (f: (i: I, a: A) => Option) => (fa: Kind3) => Kind3 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind3 ) => Separated, Kind3> (predicateWithIndex: PredicateWithIndex): ( fa: Kind3 ) => Separated, Kind3> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind3) => Separated, Kind3> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableFilterableWithIndex4 extends PipeableFilterable4 { readonly filterWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind4 ) => Kind4 (predicateWithIndex: PredicateWithIndex): (fa: Kind4) => Kind4 } readonly filterMapWithIndex: ( f: (i: I, a: A) => Option ) => (fa: Kind4) => Kind4 readonly partitionWithIndex: { (refinementWithIndex: RefinementWithIndex): ( fa: Kind4 ) => Separated, Kind4> (predicateWithIndex: PredicateWithIndex): ( fa: Kind4 ) => Separated, Kind4> } readonly partitionMapWithIndex: ( f: (i: I, a: A) => Either ) => (fa: Kind4) => Separated, Kind4> } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableProfunctor { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: HKT2) => HKT2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableProfunctor2 extends PipeableFunctor2 { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableProfunctor2C extends PipeableFunctor2C { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableProfunctor3 extends PipeableFunctor3 { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableProfunctor3C extends PipeableFunctor3C { readonly promap: (f: (d: D) => E, g: (a: A) => B) => (fbc: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableProfunctor4 extends PipeableFunctor4 { readonly promap: ( f: (d: D) => E, g: (a: A) => B ) => (fbc: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableSemigroupoid { readonly compose: (la: HKT2) => (ab: HKT2) => HKT2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableSemigroupoid2 { readonly compose: (la: Kind2) => (ab: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableSemigroupoid2C { readonly compose: (la: Kind2) => (ab: Kind2) => Kind2 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableSemigroupoid3 { readonly compose: (la: Kind3) => (ab: Kind3) => Kind3 } /** * @since 2.2.0 * @deprecated */ export interface PipeableSemigroupoid3C { readonly compose: (la: Kind3) => (ab: Kind3) => Kind3 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableSemigroupoid4 { readonly compose: (la: Kind4) => (ab: Kind4) => Kind4 } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableMonadThrow { readonly fromOption: (onNone: LazyArg) => (ma: Option) => HKT readonly fromEither: (ma: Either) => HKT readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => HKT (predicate: Predicate, onFalse: (a: A) => E): (a: A) => HKT } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: HKT) => HKT (predicate: Predicate, onFalse: (a: A) => E): (ma: HKT) => HKT } } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableMonadThrow1 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind readonly fromEither: (ma: Either) => Kind readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind) => Kind (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind) => Kind } } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableMonadThrow2 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind2 readonly fromEither: (ma: Either) => Kind2 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableMonadThrow2C { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind2 readonly fromEither: (ma: Either) => Kind2 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind2 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): (ma: Kind2) => Kind2 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind2) => Kind2 } } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableMonadThrow3 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind3 readonly fromEither: (ma: Either) => Kind3 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind3 ) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } } /** * @since 2.2.0 * @deprecated */ export interface PipeableMonadThrow3C { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind3 readonly fromEither: (ma: Either) => Kind3 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind3 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind3 ) => Kind3 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind3) => Kind3 } } /** * @category zone of death * @since 2.0.0 * @deprecated */ export interface PipeableMonadThrow4 { readonly fromOption: (onNone: LazyArg) => (ma: Option) => Kind4 readonly fromEither: (ma: Either) => Kind4 readonly fromPredicate: { (refinement: Refinement, onFalse: (a: A) => E): (a: A) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (a: A) => Kind4 } readonly filterOrElse: { (refinement: Refinement, onFalse: (a: A) => E): ( ma: Kind4 ) => Kind4 (predicate: Predicate, onFalse: (a: A) => E): (ma: Kind4) => Kind4 } } const isFunctor = (I: any): I is Functor => typeof I.map === 'function' const isContravariant = (I: any): I is Contravariant => typeof I.contramap === 'function' const isFunctorWithIndex = (I: any): I is FunctorWithIndex => typeof I.mapWithIndex === 'function' const isApply = (I: any): I is Apply => typeof I.ap === 'function' const isChain = (I: any): I is Chain => typeof I.chain === 'function' const isBifunctor = (I: any): I is Bifunctor => typeof I.bimap === 'function' const isExtend = (I: any): I is Extend => typeof I.extend === 'function' const isFoldable = (I: any): I is Foldable => typeof I.reduce === 'function' const isFoldableWithIndex = (I: any): I is FoldableWithIndex => typeof I.reduceWithIndex === 'function' const isAlt = (I: any): I is Alt => typeof I.alt === 'function' const isCompactable = (I: any): I is Compactable => typeof I.compact === 'function' const isFilterable = (I: any): I is Filterable => typeof I.filter === 'function' const isFilterableWithIndex = (I: any): I is FilterableWithIndex => typeof I.filterWithIndex === 'function' const isProfunctor = (I: any): I is Profunctor => typeof I.promap === 'function' const isSemigroupoid = (I: any): I is Semigroupoid => typeof I.compose === 'function' const isMonadThrow = (I: any): I is MonadThrow => typeof I.throwError === 'function' /** * @category zone of death * @since 2.0.0 * @deprecated */ export function pipeable( I: { readonly URI: F } & I ): (I extends Chain4 ? PipeableChain4 : I extends Apply4 ? PipeableApply4 : I extends Functor4 ? PipeableFunctor4 : {}) & (I extends Contravariant4 ? PipeableContravariant4 : {}) & (I extends FunctorWithIndex4 ? PipeableFunctorWithIndex4 : {}) & (I extends Bifunctor4 ? PipeableBifunctor4 : {}) & (I extends Extend4 ? PipeableExtend4 : {}) & (I extends FoldableWithIndex4 ? PipeableFoldableWithIndex4 : I extends Foldable4 ? PipeableFoldable4 : {}) & (I extends Alt4 ? PipeableAlt4 : {}) & (I extends FilterableWithIndex4 ? PipeableFilterableWithIndex4 : I extends Filterable4 ? PipeableFilterable4 : I extends Compactable4 ? PipeableCompactable4 : {}) & (I extends Profunctor4 ? PipeableProfunctor4 : {}) & (I extends Semigroupoid4 ? PipeableSemigroupoid4 : {}) & (I extends MonadThrow4 ? PipeableMonadThrow4 : {}) /** @deprecated */ export function pipeable( I: { readonly URI: F } & I ): (I extends Chain3 ? PipeableChain3 : I extends Apply3 ? PipeableApply3 : I extends Functor3 ? PipeableFunctor3 : {}) & (I extends Contravariant3 ? PipeableContravariant3 : {}) & (I extends FunctorWithIndex3 ? PipeableFunctorWithIndex3 : {}) & (I extends Bifunctor3 ? PipeableBifunctor3 : {}) & (I extends Extend3 ? PipeableExtend3 : {}) & (I extends FoldableWithIndex3 ? PipeableFoldableWithIndex3 : I extends Foldable3 ? PipeableFoldable3 : {}) & (I extends Alt3 ? PipeableAlt3 : {}) & (I extends FilterableWithIndex3 ? PipeableFilterableWithIndex3 : I extends Filterable3 ? PipeableFilterable3 : I extends Compactable3 ? PipeableCompactable3 : {}) & (I extends Profunctor3 ? PipeableProfunctor3 : {}) & (I extends Semigroupoid3 ? PipeableSemigroupoid3 : {}) & (I extends MonadThrow3 ? PipeableMonadThrow3 : {}) /** @deprecated */ export function pipeable( I: { readonly URI: F } & I ): (I extends Chain3C ? PipeableChain3C : I extends Apply3C ? PipeableApply3C : I extends Functor3C ? PipeableFunctor3C : {}) & (I extends Contravariant3C ? PipeableContravariant3C : {}) & (I extends FunctorWithIndex3C ? PipeableFunctorWithIndex3C : {}) & (I extends Bifunctor3C ? PipeableBifunctor3C : {}) & (I extends Extend3C ? PipeableExtend3C : {}) & (I extends FoldableWithIndex3C ? PipeableFoldableWithIndex3C : I extends Foldable3C ? PipeableFoldable3C : {}) & (I extends Alt3C ? PipeableAlt3C : {}) & (I extends FilterableWithIndex3C ? PipeableFilterableWithIndex3C : I extends Filterable3C ? PipeableFilterable3C : I extends Compactable3C ? PipeableCompactable3C : {}) & (I extends Profunctor3C ? PipeableProfunctor3C : {}) & (I extends Semigroupoid3C ? PipeableSemigroupoid3C : {}) & (I extends MonadThrow3C ? PipeableMonadThrow3C : {}) /** @deprecated */ export function pipeable( I: { readonly URI: F; readonly _E: E } & I ): (I extends Chain2C ? PipeableChain2C : I extends Apply2C ? PipeableApply2C : I extends Functor2C ? PipeableFunctor2C : {}) & (I extends Contravariant2C ? PipeableContravariant2C : {}) & (I extends FunctorWithIndex2C ? PipeableFunctorWithIndex2C : {}) & (I extends Extend2C ? PipeableExtend2C : {}) & (I extends FoldableWithIndex2C ? PipeableFoldableWithIndex2C : I extends Foldable2C ? PipeableFoldable2C : {}) & (I extends Alt2C ? PipeableAlt2C : {}) & (I extends FilterableWithIndex2C ? PipeableFilterableWithIndex2C : I extends Filterable2C ? PipeableFilterable2C : I extends Compactable2C ? PipeableCompactable2C : {}) & (I extends Profunctor2C ? PipeableProfunctor2C : {}) & (I extends Semigroupoid2C ? PipeableSemigroupoid2C : {}) & (I extends MonadThrow2C ? PipeableMonadThrow2C : {}) /** @deprecated */ export function pipeable( I: { readonly URI: F } & I ): (I extends Chain2 ? PipeableChain2 : I extends Apply2 ? PipeableApply2 : I extends Functor2 ? PipeableFunctor2 : {}) & (I extends Contravariant2 ? PipeableContravariant2 : {}) & (I extends FunctorWithIndex2 ? PipeableFunctorWithIndex2 : {}) & (I extends Bifunctor2 ? PipeableBifunctor2 : {}) & (I extends Extend2 ? PipeableExtend2 : {}) & (I extends FoldableWithIndex2 ? PipeableFoldableWithIndex2 : I extends Foldable2 ? PipeableFoldable2 : {}) & (I extends Alt2 ? PipeableAlt2 : {}) & (I extends FilterableWithIndex2 ? PipeableFilterableWithIndex2 : I extends Filterable2 ? PipeableFilterable2 : I extends Compactable2 ? PipeableCompactable2 : {}) & (I extends Profunctor2 ? PipeableProfunctor2 : {}) & (I extends Semigroupoid2 ? PipeableSemigroupoid2 : {}) & (I extends MonadThrow2 ? PipeableMonadThrow2 : {}) /** @deprecated */ export function pipeable( I: { readonly URI: F } & I ): (I extends Chain1 ? PipeableChain1 : I extends Apply1 ? PipeableApply1 : I extends Functor1 ? PipeableFunctor1 : {}) & (I extends Contravariant1 ? PipeableContravariant1 : {}) & (I extends FunctorWithIndex1 ? PipeableFunctorWithIndex1 : {}) & (I extends Extend1 ? PipeableExtend1 : {}) & (I extends FoldableWithIndex1 ? PipeableFoldableWithIndex1 : I extends Foldable1 ? PipeableFoldable1 : {}) & (I extends Alt1 ? PipeableAlt1 : {}) & (I extends FilterableWithIndex1 ? PipeableFilterableWithIndex1 : I extends Filterable1 ? PipeableFilterable1 : I extends Compactable1 ? PipeableCompactable1 : {}) & (I extends MonadThrow1 ? PipeableMonadThrow1 : {}) /** @deprecated */ export function pipeable( I: { readonly URI: F } & I ): (I extends Chain ? PipeableChain : I extends Apply ? PipeableApply : I extends Functor ? PipeableFunctor : {}) & (I extends Contravariant ? PipeableContravariant : {}) & (I extends FunctorWithIndex ? PipeableFunctorWithIndex : {}) & (I extends Bifunctor ? PipeableBifunctor : {}) & (I extends Extend ? PipeableExtend : {}) & (I extends FoldableWithIndex ? PipeableFoldableWithIndex : I extends Foldable ? PipeableFoldable : {}) & (I extends Alt ? PipeableAlt : {}) & (I extends FilterableWithIndex ? PipeableFilterableWithIndex : I extends Filterable ? PipeableFilterable : I extends Compactable ? PipeableCompactable : {}) & (I extends Profunctor ? PipeableProfunctor : {}) & (I extends Semigroupoid ? PipeableSemigroupoid : {}) & (I extends MonadThrow ? PipeableMonadThrow : {}) /** @deprecated */ export function pipeable(I: { readonly URI: F } & I): Record { const r: any = {} if (isFunctor(I)) { r.map = map(I) } if (isContravariant(I)) { r.contramap = contramap(I) } if (isFunctorWithIndex(I)) { r.mapWithIndex = mapWithIndex(I) } if (isApply(I)) { r.ap = ap(I) r.apFirst = apFirst_(I) r.apSecond = apSecond_(I) } if (isChain(I)) { r.chain = chain(I) r.chainFirst = chainFirst_(I) r.flatten = r.chain(identity) } if (isBifunctor(I)) { r.bimap = bimap(I) r.mapLeft = mapLeft(I) } if (isExtend(I)) { r.extend = extend(I) r.duplicate = r.extend(identity) } if (isFoldable(I)) { r.reduce = reduce(I) r.foldMap = foldMap(I) r.reduceRight = reduceRight(I) } if (isFoldableWithIndex(I)) { r.reduceWithIndex = reduceWithIndex(I) r.foldMapWithIndex = foldMapWithIndex(I) r.reduceRightWithIndex = reduceRightWithIndex(I) } if (isAlt(I)) { r.alt = alt(I) } if (isCompactable(I)) { r.compact = I.compact r.separate = I.separate } if (isFilterable(I)) { r.filter = filter(I) r.filterMap = filterMap(I) r.partition = partition(I) r.partitionMap = partitionMap(I) } if (isFilterableWithIndex(I)) { r.filterWithIndex = filterWithIndex(I) r.filterMapWithIndex = filterMapWithIndex(I) r.partitionWithIndex = partitionWithIndex(I) r.partitionMapWithIndex = partitionMapWithIndex(I) } if (isProfunctor(I)) { r.promap = promap(I) } if (isSemigroupoid(I)) { r.compose = compose(I) } if (isMonadThrow(I)) { const fromOption: PipeableMonadThrow['fromOption'] = (onNone) => (ma) => ma._tag === 'None' ? I.throwError(onNone()) : I.of(ma.value) const fromEither: PipeableMonadThrow['fromEither'] = (ma) => ma._tag === 'Left' ? I.throwError(ma.left) : I.of(ma.right) const fromPredicate: PipeableMonadThrow['fromPredicate'] = (predicate: Predicate, onFalse: (a: A) => E) => (a: A) => predicate(a) ? I.of(a) : I.throwError(onFalse(a)) const filterOrElse: PipeableMonadThrow['filterOrElse'] = (predicate: Predicate, onFalse: (a: A) => E) => (ma: HKT) => I.chain(ma, (a) => (predicate(a) ? I.of(a) : I.throwError(onFalse(a)))) r.fromOption = fromOption r.fromEither = fromEither r.fromPredicate = fromPredicate r.filterOrElse = filterOrElse } return r } /** * Use [`pipe`](https://gcanti.github.io/fp-ts/modules/function.ts.html#pipe) from `function` module instead. * * @since 2.0.0 * @deprecated */ export const pipe = pipeFromFunctionModule ================================================ FILE: src/string.ts ================================================ /** * @since 2.10.0 */ import * as E from './Eq' import * as M from './Monoid' import * as O from './Ord' import { isNonEmpty, ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' import { Refinement } from './Refinement' import * as S from './Semigroup' import * as Sh from './Show' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @example * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(S.Eq.equals('a', 'a'), true) * assert.deepStrictEqual(S.Eq.equals('a', 'b'), false) * * @category instances * @since 2.10.0 */ export const Eq: E.Eq = { equals: (first, second) => first === second } /** * `string` semigroup under concatenation. * * @example * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(S.Semigroup.concat('a', 'b'), 'ab') * * @category instances * @since 2.10.0 */ export const Semigroup: S.Semigroup = { concat: (first, second) => first + second } /** * An empty `string`. * * @since 2.10.0 */ export const empty = '' /** * `string` monoid under concatenation. * * The `empty` value is `''`. * * @example * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(S.Monoid.concat('a', 'b'), 'ab') * assert.deepStrictEqual(S.Monoid.concat('a', S.Monoid.empty), 'a') * * @category instances * @since 2.10.0 */ export const Monoid: M.Monoid = { concat: Semigroup.concat, empty } /** * @example * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(S.Ord.compare('a', 'a'), 0) * assert.deepStrictEqual(S.Ord.compare('a', 'b'), -1) * assert.deepStrictEqual(S.Ord.compare('b', 'a'), 1) * * @category instances * @since 2.10.0 */ export const Ord: O.Ord = { equals: Eq.equals, compare: (first, second) => (first < second ? -1 : first > second ? 1 : 0) } /** * @example * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(S.Show.show('a'), '"a"') * * @category instances * @since 2.10.0 */ export const Show: Sh.Show = { show: (s) => JSON.stringify(s) } // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * @example * import * as S from 'fp-ts/string' * * assert.deepStrictEqual(S.isString('a'), true) * assert.deepStrictEqual(S.isString(1), false) * * @category refinements * @since 2.11.0 */ export const isString: Refinement = (u: unknown): u is string => typeof u === 'string' // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('a', S.toUpperCase), 'A') * * @since 2.11.0 */ export const toUpperCase = (s: string): string => s.toUpperCase() /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('A', S.toLowerCase), 'a') * * @since 2.11.0 */ export const toLowerCase = (s: string): string => s.toLowerCase() /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abc', S.replace('b', 'd')), 'adc') * * @since 2.11.0 */ export const replace = (searchValue: string | RegExp, replaceValue: string) => (s: string): string => s.replace(searchValue, replaceValue) /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(' a ', S.trim), 'a') * * @since 2.11.0 */ export const trim = (s: string): string => s.trim() /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(' a ', S.trimLeft), 'a ') * * @since 2.11.0 */ export const trimLeft = (s: string): string => s.trimLeft() /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(' a ', S.trimRight), ' a') * * @since 2.11.0 */ export const trimRight = (s: string): string => s.trimRight() /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abcd', S.slice(1, 3)), 'bc') * * @since 2.11.0 */ export const slice = (start: number, end: number) => (s: string): string => s.slice(start, end) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Test whether a `string` is empty. * * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('', S.isEmpty), true) * assert.deepStrictEqual(pipe('a', S.isEmpty), false) * * @since 2.10.0 */ export const isEmpty = (s: string): boolean => s.length === 0 /** * Calculate the number of characters in a `string`. * * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abc', S.size), 3) * * @since 2.10.0 */ export const size = (s: string): number => s.length /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abc', S.split('')), ['a', 'b', 'c']) * assert.deepStrictEqual(pipe('', S.split('')), ['']) * * @since 2.11.0 */ export const split = (separator: string | RegExp) => (s: string): ReadonlyNonEmptyArray => { const out = s.split(separator) return isNonEmpty(out) ? out : [s] } /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abc', S.includes('b')), true) * assert.deepStrictEqual(pipe('abc', S.includes('d')), false) * * @since 2.11.0 */ export const includes = (searchString: string, position?: number) => (s: string): boolean => s.includes(searchString, position) /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abc', S.startsWith('a')), true) * assert.deepStrictEqual(pipe('bc', S.startsWith('a')), false) * * @since 2.11.0 */ export const startsWith = (searchString: string, position?: number) => (s: string): boolean => s.startsWith(searchString, position) /** * @example * import * as S from 'fp-ts/string' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe('abc', S.endsWith('c')), true) * assert.deepStrictEqual(pipe('ab', S.endsWith('c')), false) * * @since 2.11.0 */ export const endsWith = (searchString: string, position?: number) => (s: string): boolean => s.endsWith(searchString, position) ================================================ FILE: src/struct.ts ================================================ /** * @since 2.10.0 */ import * as _ from './internal' import { Semigroup } from './Semigroup' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * Return a semigroup which works like `Object.assign`. * * @example * import { getAssignSemigroup } from 'fp-ts/struct' * * interface Person { * readonly name: string * readonly age: number * } * * const S = getAssignSemigroup() * assert.deepStrictEqual(S.concat({ name: 'name', age: 23 }, { name: 'name', age: 24 }), { name: 'name', age: 24 }) * * @category instances * @since 2.10.0 */ export const getAssignSemigroup = (): Semigroup => ({ concat: (first, second) => Object.assign({}, first, second) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Creates a new object by recursively evolving a shallow copy of `a`, according to the `transformation` functions. * * @example * import { pipe } from 'fp-ts/function' * import { evolve } from 'fp-ts/struct' * * assert.deepStrictEqual( * pipe( * { a: 'a', b: 1 }, * evolve({ * a: (a) => a.length, * b: (b) => b * 2 * }) * ), * { a: 1, b: 2 } * ) * * @since 2.11.0 */ export const evolve = unknown }>(transformations: F) => (a: A): { [K in keyof F]: ReturnType } => { const out: Record = {} for (const k in a) { if (_.has.call(a, k)) { out[k] = transformations[k](a[k]) } } return out as any } ================================================ FILE: src/void.ts ================================================ /** * @since 2.11.0 */ import * as M from './Monoid' import * as Se from './Semigroup' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.11.0 */ export const Semigroup: Se.Semigroup = Se.constant(undefined) /** * @category instances * @since 2.11.0 */ export const Monoid: M.Monoid = { concat: Semigroup.concat, empty: undefined } ================================================ FILE: test/Alternative.ts ================================================ import * as _ from '../src/Alternative' import * as M from '../src/Monoid' import * as NEA from '../src/NonEmptyArray' import * as O from '../src/Option' import * as S from '../src/Semigroup' import * as U from './util' describe('Alternative', () => { it('altAll', () => { const altAll = _.altAll(O.Alternative) U.deepStrictEqual(altAll([]), O.none) U.deepStrictEqual(altAll([O.none]), O.none) U.deepStrictEqual(altAll([O.none, O.some(1)]), O.some(1)) }) it('getAlternativeMonoid', () => { const altConcatAll = M.concatAll(_.getAlternativeMonoid(O.Alternative)(NEA.getSemigroup())) U.deepStrictEqual(altConcatAll([]), O.none) U.deepStrictEqual(altConcatAll([O.none]), O.none) U.deepStrictEqual(altConcatAll([O.none, O.some([1]), O.some([2])]), O.some([1, 2])) const pickFirst = _.getAlternativeMonoid(O.Alternative)(S.first()) U.deepStrictEqual(pickFirst.concat(O.some('a'), O.some('b')), O.some('a')) U.deepStrictEqual(pickFirst.concat(O.none, O.some('b')), O.some('b')) U.deepStrictEqual(pickFirst.concat(O.some('a'), O.none), O.some('a')) const pickLast = _.getAlternativeMonoid(O.Alternative)(S.last()) U.deepStrictEqual(pickLast.concat(O.some('a'), O.some('b')), O.some('b')) U.deepStrictEqual(pickLast.concat(O.none, O.some('b')), O.some('b')) U.deepStrictEqual(pickLast.concat(O.some('a'), O.none), O.some('a')) }) }) ================================================ FILE: test/Applicative.ts ================================================ import { getApplicativeComposition } from '../src/Applicative' import { increment } from '../src/function' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as U from './util' describe('Applicative', () => { it('getApplicativeComposition', () => { const AC = getApplicativeComposition(RA.Applicative, O.Applicative) U.deepStrictEqual(AC.of(1), [O.some(1)]) U.deepStrictEqual(AC.map(AC.of(1), increment), [O.some(2)]) U.deepStrictEqual(AC.ap([O.some(U.double), O.some(increment)], [O.some(1), O.some(2)]), [ O.some(2), O.some(4), O.some(2), O.some(3) ]) U.deepStrictEqual(AC.ap([O.some(U.double), O.none], [O.some(1), O.some(2)]), [O.some(2), O.some(4), O.none, O.none]) }) }) ================================================ FILE: test/Apply.ts ================================================ import { sequenceS, sequenceT } from '../src/Apply' import * as E from '../src/Either' import { pipe } from '../src/function' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as U from './util' describe('Apply', () => { it('sequenceT', () => { const sequenceTOption = sequenceT(O.Applicative) U.deepStrictEqual(sequenceTOption(O.some(1)), O.some([1])) U.deepStrictEqual(sequenceTOption(O.some(1), O.some('a')), O.some([1, 'a'])) U.deepStrictEqual(sequenceTOption(O.some(1), O.some('a'), O.some(true)), O.some([1, 'a', true])) U.deepStrictEqual(sequenceTOption(O.some(1), O.some('a'), O.some(true), O.some(2)), O.some([1, 'a', true, 2])) U.deepStrictEqual( sequenceTOption(O.some(1), O.some('a'), O.some(true), O.some(2), O.some('b')), O.some([1, 'a', true, 2, 'b']) ) U.deepStrictEqual( sequenceTOption(O.some(1), O.some('a'), O.some(true), O.some(2), O.some('b'), O.some(false)), O.some([1, 'a', true, 2, 'b', false]) ) U.deepStrictEqual(sequenceTOption(O.some(1), O.some('a'), O.none), O.none) // #914 const a1: ReadonlyArray = [1, 2, 3] const a2: ReadonlyArray = ['a', 'b', 'c'] const a3: ReadonlyArray = [true, false] U.deepStrictEqual( pipe(sequenceT(RA.Applicative)(a1, a2, a3), (arr) => arr.map(([x, y, z]) => `(${x}, ${y}, ${z})`)), [ '(1, a, true)', '(1, a, false)', '(1, b, true)', '(1, b, false)', '(1, c, true)', '(1, c, false)', '(2, a, true)', '(2, a, false)', '(2, b, true)', '(2, b, false)', '(2, c, true)', '(2, c, false)', '(3, a, true)', '(3, a, false)', '(3, b, true)', '(3, b, false)', '(3, c, true)', '(3, c, false)' ] ) }) it('sequenceS', () => { const adoOption = sequenceS(O.Applicative) U.deepStrictEqual(adoOption({ a: O.some(1) }), O.some({ a: 1 })) U.deepStrictEqual(adoOption({ a: O.some(1), b: O.some('a') }), O.some({ a: 1, b: 'a' })) U.deepStrictEqual(adoOption({ a: O.some(1), b: O.some('a'), c: O.some(true) }), O.some({ a: 1, b: 'a', c: true })) U.deepStrictEqual( adoOption({ a: O.some(1), b: O.some('a'), c: O.some(true), d: O.some(2) }), O.some({ a: 1, b: 'a', c: true, d: 2 }) ) U.deepStrictEqual( adoOption({ a: O.some(1), b: O.some('a'), c: O.some(true), d: O.some(2), e: O.some('b') }), O.some({ a: 1, b: 'a', c: true, d: 2, e: 'b' }) ) U.deepStrictEqual( adoOption({ a: O.some(1), b: O.some('a'), c: O.some(true), d: O.some(2), e: O.some('b'), f: O.some(false) }), O.some({ a: 1, b: 'a', c: true, d: 2, e: 'b', f: false }) ) U.deepStrictEqual(adoOption({ a: O.some(1), b: O.none }), O.none) const adoEither = sequenceS(E.Applicative) U.deepStrictEqual(adoEither({ a: E.right(1) }), E.right({ a: 1 })) U.deepStrictEqual(adoEither({ a: E.right(1), b: E.right(2) }), E.right({ a: 1, b: 2 })) U.deepStrictEqual(adoEither({ a: E.right(1), b: E.left('error') }), E.left('error')) const adoValidation = sequenceS(E.getApplicativeValidation(RA.getMonoid())) U.deepStrictEqual(adoValidation({ a: E.right(1) }), E.right({ a: 1 })) U.deepStrictEqual(adoValidation({ a: E.right(1), b: E.right(2) }), E.right({ a: 1, b: 2 })) U.deepStrictEqual(adoValidation({ a: E.right(1), b: E.left(['error']) }), E.left(['error'])) U.deepStrictEqual(adoValidation({ a: E.left(['error1']), b: E.left(['error2']) }), E.left(['error1', 'error2'])) // #914 const a1: ReadonlyArray = [1, 2, 3] const a2: ReadonlyArray = ['a', 'b', 'c'] const a3: ReadonlyArray = [true, false] U.deepStrictEqual( pipe(sequenceS(RA.Applicative)({ a1, a2, a3 }), (arr) => arr.map(({ a1, a2, a3 }) => `(${a1}, ${a2}, ${a3})`)), [ '(1, a, true)', '(1, a, false)', '(1, b, true)', '(1, b, false)', '(1, c, true)', '(1, c, false)', '(2, a, true)', '(2, a, false)', '(2, b, true)', '(2, b, false)', '(2, c, true)', '(2, c, false)', '(3, a, true)', '(3, a, false)', '(3, b, true)', '(3, b, false)', '(3, c, true)', '(3, c, false)' ] ) }) }) ================================================ FILE: test/Array.ts ================================================ import * as fc from 'fast-check' import { isDeepStrictEqual } from 'util' import * as _ from '../src/Array' import * as B from '../src/boolean' import * as E from '../src/Either' import * as Eq from '../src/Eq' import { identity, pipe, tuple } from '../src/function' import * as M from '../src/Monoid' import * as N from '../src/number' import * as O from '../src/Option' import * as Ord from '../src/Ord' import { Predicate } from '../src/Predicate' import { Refinement } from '../src/Refinement' import { separated } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' /* tslint:disable:readonly-array */ describe('Array', () => { describe('pipeables', () => { it('traverse', () => { const traverse = _.traverse(O.Applicative)((n: number): O.Option => (n % 2 === 0 ? O.none : O.some(n))) U.deepStrictEqual(traverse([1, 2]), O.none) U.deepStrictEqual(traverse([1, 3]), O.some([1, 3])) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence([O.some(1), O.some(3)]), O.some([1, 3])) U.deepStrictEqual(sequence([O.some(1), O.none]), O.none) }) it('traverseWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length >= 1 ? O.some(s + i) : O.none)) ), O.some(['a0', 'bb1']) ) U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length > 1 ? O.some(s + i) : O.none)) ), O.none ) }) it('lookup', () => { U.deepStrictEqual(_.lookup(0, [1, 2, 3]), O.some(1)) U.deepStrictEqual(_.lookup(3, [1, 2, 3]), O.none) U.deepStrictEqual(pipe([1, 2, 3], _.lookup(0)), O.some(1)) U.deepStrictEqual(pipe([1, 2, 3], _.lookup(3)), O.none) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(2, [1, 2, 3]), true) U.deepStrictEqual(_.elem(N.Eq)(0, [1, 2, 3]), false) U.deepStrictEqual(pipe([1, 2, 3], _.elem(N.Eq)(2)), true) U.deepStrictEqual(pipe([1, 2, 3], _.elem(N.Eq)(0)), false) }) it('unfold', () => { const as = _.unfold(5, (n) => (n > 0 ? O.some([n, n - 1]) : O.none)) U.deepStrictEqual(as, [5, 4, 3, 2, 1]) }) it('wither', async () => { const wither = _.wither(T.ApplicativePar)((n: number) => T.of(n > 2 ? O.some(n + 1) : O.none)) U.deepStrictEqual(await pipe([], wither)(), []) U.deepStrictEqual(await pipe([1, 3], wither)(), [4]) }) it('wilt', async () => { const wilt = _.wilt(T.ApplicativePar)((n: number) => T.of(n > 2 ? E.right(n + 1) : E.left(n - 1))) U.deepStrictEqual(await pipe([], wilt)(), separated([], [])) U.deepStrictEqual(await pipe([1, 3], wilt)(), separated([0], [4])) }) }) describe('pipeables', () => { it('map', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.map((n) => n * 2) ), [2, 4, 6] ) }) it('mapWithIndex', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.mapWithIndex((i, n) => n + i) ), [1, 3, 5] ) }) it('alt', () => { U.deepStrictEqual( pipe( [1, 2], _.alt(() => [3, 4]) ), [1, 2, 3, 4] ) }) it('ap', () => { U.deepStrictEqual(pipe([(x: number) => x * 2, (x: number) => x * 3], _.ap([1, 2, 3])), [2, 4, 6, 3, 6, 9]) }) it('apFirst', () => { U.deepStrictEqual(pipe([1, 2], _.apFirst(['a', 'b', 'c'])), [1, 1, 1, 2, 2, 2]) }) it('apSecond', () => { U.deepStrictEqual(pipe([1, 2], _.apSecond(['a', 'b', 'c'])), ['a', 'b', 'c', 'a', 'b', 'c']) }) it('flatMap', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.flatMap((n) => [n, n + 1]) ), [1, 2, 2, 3, 3, 4] ) U.deepStrictEqual( _.flatMap([1, 2, 3], (n) => [n, n + 1]), [1, 2, 2, 3, 3, 4] ) }) it('chain', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.chain((n) => [n, n + 1]) ), [1, 2, 2, 3, 3, 4] ) }) it('chainWithIndex', () => { const f = _.chainWithIndex((i, n: number) => [n + i]) U.deepStrictEqual(pipe([1, 2, 3], f), [1, 3, 5]) U.deepStrictEqual(pipe([], f), []) }) it('chainFirst', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.chainFirst((n) => [n, n + 1]) ), [1, 1, 2, 2, 3, 3] ) }) it('extend', () => { const sum = (as: Array) => M.concatAll(N.MonoidSum)(as) U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(sum)), [10, 9, 7, 4]) U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(identity)), [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]) }) it('foldMap', () => { U.deepStrictEqual(pipe(['a', 'b', 'c'], _.foldMap(S.Monoid)(identity)), 'abc') U.deepStrictEqual(pipe([], _.foldMap(S.Monoid)(identity)), '') }) it('compact', () => { U.deepStrictEqual(_.compact([]), []) U.deepStrictEqual(_.compact([O.some(1), O.some(2), O.some(3)]), [1, 2, 3]) U.deepStrictEqual(_.compact([O.some(1), O.none, O.some(3)]), [1, 3]) }) it('separate', () => { U.deepStrictEqual(_.separate([]), separated([], [])) U.deepStrictEqual(_.separate([E.left(123), E.right('123')]), separated([123], ['123'])) }) it('filter', () => { const g = (n: number) => n % 2 === 1 U.deepStrictEqual(pipe([1, 2, 3], _.filter(g)), [1, 3]) const x = pipe([O.some(3), O.some(2), O.some(1)], _.filter(O.isSome)) U.deepStrictEqual(x, [O.some(3), O.some(2), O.some(1)]) const y = pipe([O.some(3), O.none, O.some(1)], _.filter(O.isSome)) U.deepStrictEqual(y, [O.some(3), O.some(1)]) }) it('filterWithIndex', () => { const f = (n: number) => n % 2 === 0 U.deepStrictEqual(pipe(['a', 'b', 'c'], _.filterWithIndex(f)), ['a', 'c']) }) it('filterMap', () => { const f = (n: number) => (n % 2 === 0 ? O.none : O.some(n)) U.deepStrictEqual(pipe([1, 2, 3], _.filterMap(f)), [1, 3]) U.deepStrictEqual(pipe([], _.filterMap(f)), []) }) it('foldMapWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.foldMapWithIndex(S.Monoid)((i, a) => i + a) ), '0a1b' ) }) it('filterMapWithIndex', () => { const f = (i: number, n: number) => ((i + n) % 2 === 0 ? O.none : O.some(n)) U.deepStrictEqual(pipe([1, 2, 4], _.filterMapWithIndex(f)), [1, 2]) U.deepStrictEqual(pipe([], _.filterMapWithIndex(f)), []) }) it('partitionMap', () => { U.deepStrictEqual(pipe([], _.partitionMap(identity)), separated([], [])) U.deepStrictEqual( pipe([E.right(1), E.left('foo'), E.right(2)], _.partitionMap(identity)), separated(['foo'], [1, 2]) ) }) it('partition', () => { U.deepStrictEqual( pipe( [], _.partition((n) => n > 2) ), separated([], []) ) U.deepStrictEqual( pipe( [1, 3], _.partition((n) => n > 2) ), separated([1], [3]) ) }) it('partitionMapWithIndex', () => { U.deepStrictEqual( pipe( [], _.partitionMapWithIndex((_, a) => a) ), separated([], []) ) U.deepStrictEqual( pipe( [E.right(1), E.left('foo'), E.right(2)], _.partitionMapWithIndex((i, a) => pipe( a, E.filterOrElse( (n) => n > i, () => 'err' ) ) ) ), separated(['foo', 'err'], [1]) ) }) it('partitionWithIndex', () => { U.deepStrictEqual( pipe( [], _.partitionWithIndex((i, n) => i + n > 2) ), separated([], []) ) U.deepStrictEqual( pipe( [1, 2], _.partitionWithIndex((i, n) => i + n > 2) ), separated([1], [2]) ) }) it('reduce', () => { U.deepStrictEqual( pipe( ['a', 'b', 'c'], _.reduce('', (acc, a) => acc + a) ), 'abc' ) }) it('reduceWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceWithIndex('', (i, b, a) => b + i + a) ), '0a1b' ) }) it('reduceRight', () => { const as: Array = ['a', 'b', 'c'] const b = '' const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(as, _.reduceRight(b, f)), 'cba') const x2: Array = [] U.deepStrictEqual(pipe(x2, _.reduceRight(b, f)), '') }) it('reduceRightWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceRightWithIndex('', (i, a, b) => b + i + a) ), '1b0a' ) }) it('duplicate', () => { U.deepStrictEqual(pipe(['a', 'b'], _.duplicate), [['a', 'b'], ['b']]) }) }) it('getMonoid', () => { const M = _.getMonoid() U.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(M.concat([1, 2], M.empty), [1, 2]) U.deepStrictEqual(M.concat(M.empty, [1, 2]), [1, 2]) }) it('getEq', () => { const O = _.getEq(S.Ord) U.deepStrictEqual(O.equals([], []), true) U.deepStrictEqual(O.equals(['a'], ['a']), true) U.deepStrictEqual(O.equals(['a', 'b'], ['a', 'b']), true) U.deepStrictEqual(O.equals(['a'], []), false) U.deepStrictEqual(O.equals([], ['a']), false) U.deepStrictEqual(O.equals(['a'], ['b']), false) U.deepStrictEqual(O.equals(['a', 'b'], ['b', 'a']), false) U.deepStrictEqual(O.equals(['a', 'a'], ['a']), false) }) it('getOrd', () => { const O = _.getOrd(S.Ord) U.deepStrictEqual(O.compare([], []), 0) U.deepStrictEqual(O.compare(['a'], ['a']), 0) U.deepStrictEqual(O.compare(['b'], ['a']), 1) U.deepStrictEqual(O.compare(['a'], ['b']), -1) U.deepStrictEqual(O.compare(['a'], []), 1) U.deepStrictEqual(O.compare([], ['a']), -1) U.deepStrictEqual(O.compare(['a', 'a'], ['a']), 1) U.deepStrictEqual(O.compare(['a', 'a'], ['b']), -1) U.deepStrictEqual(O.compare(['a', 'a'], ['a', 'a']), 0) U.deepStrictEqual(O.compare(['a', 'b'], ['a', 'b']), 0) U.deepStrictEqual(O.compare(['a', 'a'], ['a', 'b']), -1) U.deepStrictEqual(O.compare(['a', 'b'], ['a', 'a']), 1) U.deepStrictEqual(O.compare(['a', 'b'], ['b', 'a']), -1) U.deepStrictEqual(O.compare(['b', 'a'], ['a', 'a']), 1) U.deepStrictEqual(O.compare(['b', 'a'], ['a', 'b']), 1) U.deepStrictEqual(O.compare(['b', 'b'], ['b', 'a']), 1) U.deepStrictEqual(O.compare(['b', 'a'], ['b', 'b']), -1) }) it('isEmpty', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.isEmpty(as), false) U.deepStrictEqual(_.isEmpty([]), true) }) it('isNotEmpty', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.isNonEmpty(as), true) U.deepStrictEqual(_.isNonEmpty([]), false) }) it('cons', () => { U.deepStrictEqual(_.cons(0, [1, 2, 3]), [0, 1, 2, 3]) U.deepStrictEqual(_.cons([1], [[2]]), [[1], [2]]) U.deepStrictEqual(pipe([1, 2, 3], _.cons(0)), [0, 1, 2, 3]) U.deepStrictEqual(pipe([[2]], _.cons([1])), [[1], [2]]) }) it('snoc', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.snoc(as, 4), [1, 2, 3, 4]) U.deepStrictEqual(_.snoc([[1]], [2]), [[1], [2]]) }) it('head', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.head(as), O.some(1)) U.deepStrictEqual(_.head([]), O.none) }) it('last', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.last(as), O.some(3)) U.deepStrictEqual(_.last([]), O.none) }) it('tail', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.tail(as), O.some([2, 3])) U.deepStrictEqual(_.tail([]), O.none) }) it('takeLeft', () => { // empty const empty: Array = [] U.deepStrictEqual(_.takeLeft(0)(empty), empty) const full: Array = [1, 2] // non empty U.deepStrictEqual(_.takeLeft(0)(full), []) U.deepStrictEqual(_.takeLeft(1)(full), [1]) // full U.deepStrictEqual(_.takeLeft(2)(full), full) // out of bound U.deepStrictEqual(_.takeLeft(1)(empty), empty) U.deepStrictEqual(_.takeLeft(3)(full), full) U.deepStrictEqual(_.takeLeft(-1)(empty), empty) U.deepStrictEqual(_.takeLeft(-1)(full), full) }) it('takeRight', () => { // empty const empty: Array = [] U.deepStrictEqual(_.takeRight(0)(empty), empty) const full: Array = [1, 2] // non empty U.deepStrictEqual(_.takeRight(0)(full), []) U.deepStrictEqual(_.takeRight(1)(full), [2]) // full U.deepStrictEqual(_.takeRight(2)(full), full) // out of bound U.deepStrictEqual(_.takeRight(1)(empty), empty) U.deepStrictEqual(_.takeRight(3)(full), full) U.deepStrictEqual(_.takeRight(-1)(empty), empty) U.deepStrictEqual(_.takeRight(-1)(full), full) }) it('spanLeft', () => { const f = _.spanLeft((n: number) => n % 2 === 1) const assertSpanLeft = (input: Array, expectedInit: Array, expectedRest: Array) => { const { init, rest } = f(input) U.deepStrictEqual(init, expectedInit) U.deepStrictEqual(rest, expectedRest) } U.deepStrictEqual(f([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] }) const empty: Array = [] assertSpanLeft(empty, empty, []) assertSpanLeft([], [], []) const inputAll: Array = [1, 3] assertSpanLeft(inputAll, inputAll, []) const inputNone: Array = [2, 4] assertSpanLeft(inputNone, [], inputNone) }) it('takeLeftWhile', () => { const f = (n: number) => n % 2 === 0 U.deepStrictEqual(_.takeLeftWhile(f)([2, 4, 3, 6]), [2, 4]) U.deepStrictEqual(_.takeLeftWhile(f)([]), []) U.deepStrictEqual(_.takeLeftWhile(f)([1, 2, 4]), []) U.deepStrictEqual(_.takeLeftWhile(f)([2, 4]), [2, 4]) }) it('dropLeft', () => { // empty const empty: Array = [] U.deepStrictEqual(_.dropLeft(0)(empty), empty) const full: Array = [1, 2] // non empty U.deepStrictEqual(_.dropLeft(0)(full), full) U.deepStrictEqual(_.dropLeft(1)(full), [2]) // full U.deepStrictEqual(_.dropLeft(2)(full), []) // out of bound U.deepStrictEqual(_.dropLeft(1)(empty), empty) U.deepStrictEqual(_.dropLeft(3)(full), []) U.deepStrictEqual(_.dropLeft(-1)(empty), empty) U.deepStrictEqual(_.dropLeft(-1)(full), full) }) it('dropRight', () => { // empty const empty: Array = [] U.deepStrictEqual(_.dropRight(0)(empty), empty) const full: Array = [1, 2] // non empty U.deepStrictEqual(_.dropRight(0)(full), full) U.deepStrictEqual(_.dropRight(1)(full), [1]) // full U.deepStrictEqual(_.dropRight(2)(full), []) // out of bound U.deepStrictEqual(_.dropRight(1)(empty), empty) U.deepStrictEqual(_.dropRight(3)(full), []) U.deepStrictEqual(_.dropRight(-1)(empty), empty) U.deepStrictEqual(_.dropRight(-1)(full), full) }) it('dropLeftWhile', () => { const f = _.dropLeftWhile((n: number) => n > 0) U.deepStrictEqual(f([]), []) U.deepStrictEqual(f([1, 2]), []) U.deepStrictEqual(f([-1, -2]), [-1, -2]) U.deepStrictEqual(f([-1, 2]), [-1, 2]) U.deepStrictEqual(f([1, -2, 3]), [-2, 3]) }) it('init', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.init(as), O.some([1, 2])) U.deepStrictEqual(_.init([]), O.none) }) it('findIndex', () => { U.deepStrictEqual(_.findIndex((x) => x === 2)([1, 2, 3]), O.some(1)) U.deepStrictEqual(_.findIndex((x) => x === 2)([]), O.none) }) it('findFirst', () => { U.deepStrictEqual( pipe( [], _.findFirst((x: { readonly a: number }) => x.a > 1) ), O.none ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findFirst((x) => x.a > 1) ), O.some({ a: 2 }) ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findFirst((x) => x.a > 3) ), O.none ) }) it('findFirstMap', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.findFirstMap((n) => (n > 1 ? O.some(n * 2) : O.none)) ), O.some(4) ) U.deepStrictEqual( pipe( [1], _.findFirstMap((n) => (n < 1 ? O.some(n * 2) : O.none)) ), O.none ) }) it('findLast', () => { U.deepStrictEqual( pipe( [], _.findLast((x: { readonly a: number }) => x.a > 1) ), O.none ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findLast((x) => x.a > 1) ), O.some({ a: 3 }) ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findLast((x) => x.a > 3) ), O.none ) }) it('findLastMap', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.findLastMap((n) => (n > 1 ? O.some(n * 2) : O.none)) ), O.some(6) ) U.deepStrictEqual( pipe( [1], _.findLastMap((n) => (n > 1 ? O.some(n * 2) : O.none)) ), O.none ) }) it('findLastIndex', () => { interface X { readonly a: number readonly b: number } const xs: Array = [ { a: 1, b: 0 }, { a: 1, b: 1 } ] U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 1)(xs), O.some(1)) U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 4)(xs), O.none) U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 1)([]), O.none) }) it('insertAt', () => { U.deepStrictEqual(_.insertAt(1, 1)([]), O.none) U.deepStrictEqual(_.insertAt(0, 1)([]), O.some([1])) U.deepStrictEqual(_.insertAt(2, 5)([1, 2, 3, 4]), O.some([1, 2, 5, 3, 4])) }) it('unsafeUpdateAt', () => { U.deepStrictEqual(pipe(_.unsafeUpdateAt(1, 2, []), _.isEmpty), true) // should not return the same reference if nothing changed const input: Array = [1, 2, 3] U.deepStrictEqual( pipe(_.unsafeUpdateAt(1, 2, input), (out) => out === input), false ) }) it('updateAt', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.updateAt(1, 1)(as), O.some([1, 1, 3])) U.deepStrictEqual(_.updateAt(1, 1)([]), O.none) }) it('deleteAt', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.deleteAt(0)(as), O.some([2, 3])) U.deepStrictEqual(_.deleteAt(1)([]), O.none) }) it('modifyAt', () => { const as: Array = [1, 2, 3] U.deepStrictEqual(_.modifyAt(1, U.double)(as), O.some([1, 4, 3])) U.deepStrictEqual(_.modifyAt(1, U.double)([]), O.none) // should not return the same reference if nothing changed const input: Array = [1, 2, 3] U.deepStrictEqual( pipe( input, _.modifyAt(1, identity), O.map((out) => out === input) ), O.some(false) ) }) it('sort', () => { U.deepStrictEqual(_.sort(N.Ord)([3, 2, 1]), [1, 2, 3]) U.deepStrictEqual(_.sort(N.Ord)([]), []) const byName = pipe( S.Ord, Ord.contramap((x: { readonly name: string }) => x.name) ) U.deepStrictEqual( _.sort(byName)([ { name: 'b', age: 0 }, { name: 'a', age: 1 }, { name: 'c', age: 2 } ]), [ { name: 'a', age: 1 }, { name: 'b', age: 0 }, { name: 'c', age: 2 } ] ) }) it('prependAll', () => { U.deepStrictEqual(_.prependAll(0)([1, 2, 3]), [0, 1, 0, 2, 0, 3]) U.deepStrictEqual(_.prependAll(0)([]), []) U.deepStrictEqual(_.prependAll(0)([1]), [0, 1]) U.deepStrictEqual(_.prependAll(0)([1, 2, 3, 4]), [0, 1, 0, 2, 0, 3, 0, 4]) }) it('intersperse', () => { U.deepStrictEqual(_.intersperse(0)([]), []) U.deepStrictEqual(_.intersperse(0)([1]), [1]) U.deepStrictEqual(_.intersperse(0)([1, 2, 3]), [1, 0, 2, 0, 3]) U.deepStrictEqual(_.intersperse(0)([1, 2]), [1, 0, 2]) U.deepStrictEqual(_.intersperse(0)([1, 2, 3, 4]), [1, 0, 2, 0, 3, 0, 4]) }) it('intercalate', () => { U.deepStrictEqual(_.intercalate(S.Monoid)('-')([]), '') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a']), 'a') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', '', 'c']), 'a--c') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', 'b']), 'a-b') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', 'b', 'c', 'd']), 'a-b-c-d') }) it('zipWith', () => { U.deepStrictEqual( _.zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3'] ) }) it('zip', () => { U.deepStrictEqual(_.zip([1, 2, 3], ['a', 'b', 'c', 'd']), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) U.deepStrictEqual(pipe([1, 2, 3], _.zip(['a', 'b', 'c', 'd'])), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) }) it('unzip', () => { U.deepStrictEqual( _.unzip([ [1, 'a'], [2, 'b'], [3, 'c'] ]), [ [1, 2, 3], ['a', 'b', 'c'] ] ) }) it('rights', () => { U.deepStrictEqual(_.rights([E.right(1), E.left('foo'), E.right(2)]), [1, 2]) U.deepStrictEqual(_.rights([]), []) }) it('lefts', () => { U.deepStrictEqual(_.lefts([E.right(1), E.left('foo'), E.right(2)]), ['foo']) U.deepStrictEqual(_.lefts([]), []) }) it('flatten', () => { U.deepStrictEqual(_.flatten([[1], [2], [3]]), [1, 2, 3]) }) it('rotate', () => { U.deepStrictEqual(_.rotate(0)([]), []) U.deepStrictEqual(_.rotate(1)([]), []) U.deepStrictEqual(_.rotate(1)([1]), [1]) U.deepStrictEqual(_.rotate(1)([1, 2]), [2, 1]) U.deepStrictEqual(_.rotate(2)([1, 2]), [1, 2]) U.deepStrictEqual(_.rotate(0)([1, 2]), [1, 2]) U.deepStrictEqual(_.rotate(1)([1, 2, 3, 4, 5]), [5, 1, 2, 3, 4]) U.deepStrictEqual(_.rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-1)([1, 2, 3, 4, 5]), [2, 3, 4, 5, 1]) U.deepStrictEqual(_.rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) U.deepStrictEqual(_.rotate(7)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-7)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) U.deepStrictEqual(_.rotate(2.2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-2.2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) }) it('reverse', () => { U.deepStrictEqual(_.reverse([1, 2, 3]), [3, 2, 1]) U.deepStrictEqual(_.reverse([]), []) }) it('foldLeft', () => { const len: (as: Array) => number = _.foldLeft( () => 0, (_, tail) => 1 + len(tail) ) U.deepStrictEqual(len([1, 2, 3]), 3) }) it('foldRight', () => { const len: (as: Array) => number = _.foldRight( () => 0, (init, _) => 1 + len(init) ) U.deepStrictEqual(len([1, 2, 3]), 3) }) it('scanLeft', () => { const f = (b: number, a: number) => b - a U.deepStrictEqual(_.scanLeft(10, f)([1, 2, 3]), [10, 9, 7, 4]) U.deepStrictEqual(_.scanLeft(10, f)([0]), [10, 10]) U.deepStrictEqual(_.scanLeft(10, f)([]), [10]) }) it('scanRight', () => { const f = (b: number, a: number) => b - a U.deepStrictEqual(_.scanRight(10, f)([1, 2, 3]), [-8, 9, -7, 10]) U.deepStrictEqual(_.scanRight(10, f)([0]), [-10, 10]) U.deepStrictEqual(_.scanRight(10, f)([]), [10]) }) it('uniq', () => { interface A { readonly a: string readonly b: number } const eqA = pipe( N.Ord, Eq.contramap((f: A) => f.b) ) const arrA: A = { a: 'a', b: 1 } const arrB: A = { a: 'b', b: 1 } const arrC: A = { a: 'c', b: 2 } const arrD: A = { a: 'd', b: 2 } const arrUniq: Array = [arrA, arrC] U.deepStrictEqual(_.uniq(eqA)(arrUniq), arrUniq) U.deepStrictEqual(_.uniq(eqA)([arrA, arrB, arrC, arrD]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrB, arrA, arrC, arrD]), [arrB, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrA, arrA, arrC, arrD, arrA]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrA, arrC]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrC, arrA]), [arrC, arrA]) U.deepStrictEqual(_.uniq(B.Eq)([true, false, true, false]), [true, false]) U.deepStrictEqual(_.uniq(N.Eq)([]), []) U.deepStrictEqual(_.uniq(N.Eq)([-0, -0]), [-0]) U.deepStrictEqual(_.uniq(N.Eq)([0, -0]), [0]) U.deepStrictEqual(_.uniq(N.Eq)([1]), [1]) U.deepStrictEqual(_.uniq(N.Eq)([2, 1, 2]), [2, 1]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 1]), [1, 2]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(N.Eq)([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'a']), ['a', 'b']) U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'A']), ['a', 'b', 'A']) }) it('sortBy', () => { interface Person { readonly name: string readonly age: number } const byName = pipe( S.Ord, Ord.contramap((p: Person) => p.name) ) const byAge = pipe( N.Ord, Ord.contramap((p: Person) => p.age) ) const f = _.sortBy([byName, byAge]) const persons: Array = [ { name: 'a', age: 1 }, { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 } ] U.deepStrictEqual(f(persons), [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'b', age: 3 }, { name: 'c', age: 2 } ]) const sortByAgeByName = _.sortBy([byAge, byName]) U.deepStrictEqual(sortByAgeByName(persons), [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'c', age: 2 }, { name: 'b', age: 3 } ]) U.deepStrictEqual(f([]), []) U.deepStrictEqual(_.sortBy([])(persons), persons) }) it('chop', () => { const group = (E: Eq.Eq): ((as: Array) => Array>) => { return _.chop((as) => { const { init, rest } = _.spanLeft((a: A) => E.equals(a, as[0]))(as) return [init, rest] }) } const f = group(N.Eq) U.deepStrictEqual(f([]), []) U.deepStrictEqual(f([1, 1, 2, 3, 3, 4]), [[1, 1], [2], [3, 3], [4]]) }) it('splitAt', () => { const assertSplitAt = ( input: Array, index: number, expectedInit: Array, expectedRest: Array ) => { const [init, rest] = _.splitAt(index)(input) U.deepStrictEqual(init, expectedInit) U.deepStrictEqual(rest, expectedRest) } U.deepStrictEqual(_.splitAt(1)([1, 2]), [[1], [2]]) const two: Array = [1, 2] assertSplitAt(two, 2, two, []) U.deepStrictEqual(_.splitAt(2)([1, 2, 3, 4, 5]), [ [1, 2], [3, 4, 5] ]) // zero const empty: Array = [] assertSplitAt([], 0, [], []) assertSplitAt(empty, 0, empty, []) assertSplitAt(two, 0, [], two) // out of bounds assertSplitAt([], -1, [], []) assertSplitAt(empty, -1, empty, []) assertSplitAt(two, -1, [], two) assertSplitAt(two, 3, two, []) assertSplitAt([], 3, [], []) assertSplitAt(empty, 3, empty, []) }) describe('chunksOf', () => { it('should split an array into length-n pieces', () => { U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5, 6]), [ [1, 2], [3, 4], [5, 6] ]) U.deepStrictEqual(_.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]]) // out of bounds U.deepStrictEqual(_.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) const assertSingleChunk = (input: Array, n: number) => { const chunks = _.chunksOf(n)(input) U.deepStrictEqual(chunks.length, 1) U.deepStrictEqual(chunks[0], input) } // n = length assertSingleChunk([1, 2], 2) // n out of bounds assertSingleChunk([1, 2], 3) }) // #897 it('returns an empty array if provided an empty array', () => { U.deepStrictEqual(_.chunksOf(1)([]), []) U.deepStrictEqual(_.chunksOf(2)([]), []) U.deepStrictEqual(_.chunksOf(0)([]), []) }) // #897 it('should respect the law: RA.chunksOf(n)(xs).concat(RA.chunksOf(n)(ys)) == RA.chunksOf(n)(xs.concat(ys)))', () => { const xs: Array = [] const ys: Array = [1, 2] U.deepStrictEqual(_.chunksOf(2)(xs).concat(_.chunksOf(2)(ys)), _.chunksOf(2)(xs.concat(ys))) fc.assert( fc.property( fc.array(fc.integer()).filter((xs) => xs.length % 2 === 0), // Ensures `xs.length` is even fc.array(fc.integer()), fc.integer({ min: 1, max: 1 }).map((x) => x * 2), // Generates `n` to be even so that it evenly divides `xs` (xs, ys, n) => { const as = _.chunksOf(n)(xs).concat(_.chunksOf(n)(ys)) const bs = _.chunksOf(n)(xs.concat(ys)) isDeepStrictEqual(as, bs) } ) ) }) }) it('prepend', () => { U.deepStrictEqual(pipe(['a', 'b'], _.prepend('c')), ['c', 'a', 'b']) U.deepStrictEqual(pipe(['a', 'b'], _.prependW(3)), [3, 'a', 'b']) }) it('append', () => { U.deepStrictEqual(pipe(['a', 'b'], _.append('c')), ['a', 'b', 'c']) U.deepStrictEqual(pipe(['a', 'b'], _.appendW(3)), ['a', 'b', 3]) }) it('makeBy', () => { U.deepStrictEqual(_.makeBy(5, U.double), [0, 2, 4, 6, 8]) U.deepStrictEqual(_.makeBy(0, U.double), []) U.deepStrictEqual(_.makeBy(-1, U.double), []) }) it('range', () => { U.deepStrictEqual(_.range(0, 0), [0]) U.deepStrictEqual(_.range(0, 1), [0, 1]) U.deepStrictEqual(_.range(1, 5), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.range(10, 15), [10, 11, 12, 13, 14, 15]) U.deepStrictEqual(_.range(-1, 0), [-1, 0]) U.deepStrictEqual(_.range(-5, -1), [-5, -4, -3, -2, -1]) // out of bound U.deepStrictEqual(_.range(2, 1), [2]) U.deepStrictEqual(_.range(-1, -2), [-1]) }) it('replicate', () => { U.deepStrictEqual(_.replicate(0, 'a'), []) U.deepStrictEqual(_.replicate(3, 'a'), ['a', 'a', 'a']) }) it('comprehension', () => { U.deepStrictEqual( _.comprehension([[1, 2, 3]], (a) => a * 2), [2, 4, 6] ) U.deepStrictEqual( _.comprehension( [ [1, 2, 3], ['a', 'b'] ], tuple ), [ [1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'], [3, 'a'], [3, 'b'] ] ) U.deepStrictEqual( _.comprehension( [ [1, 2, 3], ['a', 'b'] ], tuple, (a, b) => (a + b.length) % 2 === 0 ), [ [1, 'a'], [1, 'b'], [3, 'a'], [3, 'b'] ] ) }) it('union', () => { const concat = _.union(N.Eq) const two: Array = [1, 2] U.deepStrictEqual(concat(two, [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(concat(two, [2, 3]), [1, 2, 3]) U.deepStrictEqual(concat(two, [1, 2]), [1, 2]) U.deepStrictEqual(pipe(two, concat([3, 4])), [1, 2, 3, 4]) U.deepStrictEqual(pipe(two, concat([2, 3])), [1, 2, 3]) U.deepStrictEqual(pipe(two, concat([1, 2])), [1, 2]) U.deepStrictEqual(pipe(two, concat([])), two) U.deepStrictEqual(pipe([], concat(two)), two) U.deepStrictEqual(pipe([], concat([])), []) }) it('intersection', () => { U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [3, 4]), []) U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [2, 3]), [2]) U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [1, 2]), [1, 2]) U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([3, 4])), []) U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([2, 3])), [2]) U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([1, 2])), [1, 2]) }) it('difference', () => { U.deepStrictEqual(_.difference(N.Eq)([1, 2], [3, 4]), [1, 2]) U.deepStrictEqual(_.difference(N.Eq)([1, 2], [2, 3]), [1]) U.deepStrictEqual(_.difference(N.Eq)([1, 2], [1, 2]), []) U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([3, 4])), [1, 2]) U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([2, 3])), [1]) U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([1, 2])), []) }) it('getUnionMonoid', () => { const concat = _.getUnionMonoid(N.Eq).concat const two: Array = [1, 2] U.deepStrictEqual(concat(two, [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(concat(two, [2, 3]), [1, 2, 3]) U.deepStrictEqual(concat(two, [1, 2]), [1, 2]) U.deepStrictEqual(concat(two, []), two) U.deepStrictEqual(concat([], two), two) U.deepStrictEqual(concat([], []), []) }) it('getIntersectionSemigroup', () => { const concat = _.getIntersectionSemigroup(N.Eq).concat U.deepStrictEqual(concat([1, 2], [3, 4]), []) U.deepStrictEqual(concat([1, 2], [2, 3]), [2]) U.deepStrictEqual(concat([1, 2], [1, 2]), [1, 2]) }) it('getDifferenceMagma', () => { const concat = _.getDifferenceMagma(N.Eq).concat U.deepStrictEqual(concat([1, 2], [3, 4]), [1, 2]) U.deepStrictEqual(concat([1, 2], [2, 3]), [1]) U.deepStrictEqual(concat([1, 2], [1, 2]), []) }) it('should be safe when calling map with a binary function', () => { interface Foo { readonly bar: () => number } const f = (a: number, x?: Foo) => (x !== undefined ? `${a}${x.bar()}` : `${a}`) U.deepStrictEqual(_.Functor.map([1, 2], f), ['1', '2']) U.deepStrictEqual(pipe([1, 2], _.map(f)), ['1', '2']) }) it('getShow', () => { const Sh = _.getShow(S.Show) U.deepStrictEqual(Sh.show([]), `[]`) U.deepStrictEqual(Sh.show(['a']), `["a"]`) U.deepStrictEqual(Sh.show(['a', 'b']), `["a", "b"]`) }) it('size', () => { U.deepStrictEqual(_.size([]), 0) U.deepStrictEqual(_.size(['a']), 1) }) it('every', () => { const isPositive: Predicate = (n) => n > 0 U.deepStrictEqual(pipe([1, 2, 3], _.every(isPositive)), true) U.deepStrictEqual(pipe([1, 2, -3], _.every(isPositive)), false) }) it('some', () => { const isPositive: Predicate = (n) => n > 0 U.deepStrictEqual(pipe([-1, -2, 3], _.some(isPositive)), true) U.deepStrictEqual(pipe([-1, -2, -3], _.some(isPositive)), false) }) it('copy', () => { U.deepStrictEqual(pipe([1, 2, 3], _.copy), [1, 2, 3]) }) describe('fromPredicate', () => { it('can create an array from a Refinement', () => { const refinement: Refinement = (a): a is string => typeof a === 'string' U.deepStrictEqual(_.fromPredicate(refinement)('hello'), ['hello']) U.deepStrictEqual(_.fromPredicate(refinement)(null), []) }) it('can create an array from a Predicate', () => { const predicate = (a: string) => a.length > 0 U.deepStrictEqual(_.fromPredicate(predicate)('hi'), ['hi']) U.deepStrictEqual(_.fromPredicate(predicate)(''), []) }) }) it('fromOption', () => { U.deepStrictEqual(_.fromOption(O.some('hello')), ['hello']) U.deepStrictEqual(_.fromOption(O.none), []) }) it('fromEither', () => { U.deepStrictEqual(_.fromEither(E.right(1)), [1]) U.deepStrictEqual(_.fromEither(E.left('a')), []) }) it('match', () => { const f = _.match( () => 'empty', (as) => `nonEmpty ${as.length}` ) U.deepStrictEqual(pipe([], f), 'empty') U.deepStrictEqual(pipe([1, 2, 3], f), 'nonEmpty 3') }) it('concatW', () => { U.deepStrictEqual(pipe([1], _.concatW(['a'])), [1, 'a']) const as = [1, 2, 3] const empty: Array = [] U.deepStrictEqual(pipe(empty, _.concatW(as)), as) U.deepStrictEqual(pipe(as, _.concatW(empty)), as) }) it('fromOptionK', () => { const f = (n: number) => (n > 0 ? O.some(n) : O.none) const g = _.fromOptionK(f) U.deepStrictEqual(g(0), []) U.deepStrictEqual(g(1), [1]) }) it('isOutOfBound', () => { U.deepStrictEqual(_.isOutOfBound(0, ['a']), false) U.deepStrictEqual(_.isOutOfBound(100, ['a']), true) U.deepStrictEqual(_.isOutOfBound(-1, ['a']), true) }) }) ================================================ FILE: test/BooleanAlgebra.ts ================================================ import * as B from '../src/boolean' import * as _ from '../src/BooleanAlgebra' import * as U from './util' describe('BooleanAlgebra', () => { it('booleanAlgebraBoolean', () => { const BA = _.booleanAlgebraBoolean U.deepStrictEqual(BA.implies(true, true), true) U.deepStrictEqual(BA.implies(true, false), false) U.deepStrictEqual(BA.implies(false, true), true) U.deepStrictEqual(BA.implies(false, false), true) U.deepStrictEqual(BA.join(true, true), true) U.deepStrictEqual(BA.join(true, false), true) U.deepStrictEqual(BA.join(false, true), true) U.deepStrictEqual(BA.join(false, false), false) U.deepStrictEqual(BA.meet(true, true), true) U.deepStrictEqual(BA.meet(true, false), false) U.deepStrictEqual(BA.not(true), false) U.deepStrictEqual(BA.not(false), true) U.deepStrictEqual(BA.one, true) U.deepStrictEqual(BA.zero, false) }) it('booleanAlgebraVoid', () => { const BA = _.booleanAlgebraVoid U.deepStrictEqual(BA.implies(undefined, undefined), undefined) U.deepStrictEqual(BA.join(undefined, undefined), undefined) U.deepStrictEqual(BA.meet(undefined, undefined), undefined) U.deepStrictEqual(BA.not(undefined), undefined) U.deepStrictEqual(BA.one, undefined) U.deepStrictEqual(BA.zero, undefined) }) it('reverse', () => { const BA = _.reverse(B.BooleanAlgebra) U.deepStrictEqual(BA.implies(true, true), true) U.deepStrictEqual(BA.implies(true, false), false) U.deepStrictEqual(BA.implies(false, true), true) U.deepStrictEqual(BA.implies(false, false), true) U.deepStrictEqual(BA.join(true, true), true) U.deepStrictEqual(BA.join(true, false), false) U.deepStrictEqual(BA.join(false, true), false) U.deepStrictEqual(BA.join(false, false), false) U.deepStrictEqual(BA.meet(true, true), true) U.deepStrictEqual(BA.meet(true, false), true) U.deepStrictEqual(BA.not(true), false) U.deepStrictEqual(BA.not(false), true) U.deepStrictEqual(BA.one, false) U.deepStrictEqual(BA.zero, true) }) }) ================================================ FILE: test/Bounded.ts ================================================ import * as _ from '../src/Bounded' import * as N from '../src/number' import * as U from './util' describe('Bounded', () => { it('clamp', () => { const B: _.Bounded = { ...N.Ord, top: 10, bottom: 0 } const clamp = _.clamp(B) U.deepStrictEqual(clamp(5), 5) U.deepStrictEqual(clamp(-1), 0) U.deepStrictEqual(clamp(11), 10) }) it('reverse', () => { const B: _.Bounded = _.reverse({ ...N.Ord, top: 10, bottom: 0 }) U.deepStrictEqual(B.top, 0) U.deepStrictEqual(B.bottom, 10) }) }) ================================================ FILE: test/BoundedDistributiveLattice.ts ================================================ import { getMinMaxBoundedDistributiveLattice } from '../src/BoundedDistributiveLattice' import * as N from '../src/number' import * as U from './util' describe('BoundedDistributiveLattice', () => { it('getMinMaxBoundedDistributiveLattice', () => { const BDL = getMinMaxBoundedDistributiveLattice(N.Ord)(0, 1) U.deepStrictEqual(BDL.join(0.2, 0.4), 0.4) U.deepStrictEqual(BDL.meet(0.2, 0.4), 0.2) U.deepStrictEqual(BDL.one, 1) U.deepStrictEqual(BDL.zero, 0) }) }) ================================================ FILE: test/Choice.ts ================================================ import { fanin, splitChoice } from '../src/Choice' import { left, right } from '../src/Either' import * as R from '../src/Reader' import * as U from './util' describe('Choice', () => { it('splitChoice', () => { const ab = (s: string) => s.length const cd = (n: number) => n >= 2 U.deepStrictEqual(splitChoice({ ...R.Choice, ...R.Category })(ab, cd)(right(3)), right(true)) U.deepStrictEqual(splitChoice({ ...R.Choice, ...R.Category })(ab, cd)(right(1)), right(false)) U.deepStrictEqual(splitChoice({ ...R.Choice, ...R.Category })(ab, cd)(left('foo')), left(3)) }) it('fanin', () => { const ac = (s: string) => s === s.toLowerCase() const bc = (n: number) => n >= 2 U.deepStrictEqual(fanin({ ...R.Choice, ...R.Category })(ac, bc)(right(3)), true) U.deepStrictEqual(fanin({ ...R.Choice, ...R.Category })(ac, bc)(right(1)), false) U.deepStrictEqual(fanin({ ...R.Choice, ...R.Category })(ac, bc)(left('foo')), true) U.deepStrictEqual(fanin({ ...R.Choice, ...R.Category })(ac, bc)(left('A')), false) }) }) ================================================ FILE: test/Compactable.ts ================================================ import { getCompactableComposition } from '../src/Compactable' import { left, right } from '../src/Either' import { none, some } from '../src/Option' import * as RA from '../src/ReadonlyArray' import { separated } from '../src/Separated' import * as U from './util' describe('Compactable', () => { it('getCompactableComposition', () => { const C = getCompactableComposition(RA.Functor, { ...RA.Functor, ...RA.Compactable }) U.deepStrictEqual( C.map([[1], [2]], (n) => n * 2), [[2], [4]] ) U.deepStrictEqual( C.compact([ [some(1), none], [none, some(2)] ]), [[1], [2]] ) U.deepStrictEqual( C.separate([ [left('a'), right(1)], [right(2), left('b')] ]), separated([['a'], ['b']], [[1], [2]]) ) }) }) ================================================ FILE: test/Console.ts ================================================ import { error, info, log, warn } from '../src/Console' import * as U from './util' describe('Console', () => { it('log', () => { const log_ = console.log const logger: Array = [] console.log = (a: any) => { logger.push(a) } log('log')() U.deepStrictEqual(logger, ['log']) console.log = log_ }) it('info', () => { const info_ = console.info const logger: Array = [] console.info = (a: any) => { logger.push(a) } info('info')() U.deepStrictEqual(logger, ['info']) console.info = info_ }) it('error', () => { const error_ = console.error const logger: Array = [] console.error = (a: any) => { logger.push(a) } error('error')() U.deepStrictEqual(logger, ['error']) console.error = error_ }) it('warn', () => { const warn_ = console.warn const logger: Array = [] console.warn = (a: any) => { logger.push(a) } warn('warn')() U.deepStrictEqual(logger, ['warn']) console.warn = warn_ }) }) ================================================ FILE: test/Const.ts ================================================ import * as _ from '../src/Const' import { pipe } from '../src/function' import * as N from '../src/number' import * as S from '../src/string' import * as U from './util' describe('Const', () => { describe('pipeables', () => { it('map', () => { const fa = _.make('foo') U.deepStrictEqual(pipe(fa, _.map(U.double)), fa) }) it('contramap', () => { const fa: _.Const = _.make('foo') U.deepStrictEqual(pipe(fa, _.contramap(U.double)), fa) }) it('bimap', () => { const fa: _.Const = _.make('a') const f = (s: string): string => s.toUpperCase() const g = (n: number): number => n * 2 U.deepStrictEqual(pipe(fa, _.bimap(f, g)), _.make('A')) }) it('mapLeft', () => { const fa: _.Const = _.make('a') const f = (s: string): string => s.toUpperCase() U.deepStrictEqual(pipe(fa, _.mapLeft(f)), _.make('A')) }) }) it('getApplicative', () => { const F = _.getApplicative(S.Monoid) U.deepStrictEqual(F.of(1), _.make('')) }) it('getEq', () => { const S = _.getEq(N.Eq) U.deepStrictEqual(S.equals(_.make(1), _.make(1)), true) U.deepStrictEqual(S.equals(_.make(1), _.make(2)), false) }) it('getApplicative', () => { const F = _.getApply(S.Semigroup) const fa = _.make('foo') U.deepStrictEqual(F.ap(fa, _.make('bar')), _.make('foobar')) }) it('getShow', () => { const Sh = _.getShow(S.Show) const x: _.Const = _.make('a') U.deepStrictEqual(Sh.show(x), `make("a")`) }) }) ================================================ FILE: test/Date.ts ================================================ import * as _ from '../src/Date' import * as U from './util' describe('Date', () => { // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('Eq', () => { U.deepStrictEqual(_.Eq.equals(new Date(0), new Date(0)), true) U.deepStrictEqual(_.Eq.equals(new Date(0), new Date(1)), false) U.deepStrictEqual(_.Eq.equals(new Date(1), new Date(0)), false) }) it('eqDate', () => { U.deepStrictEqual(_.eqDate.equals(new Date(2000, 10, 1), new Date(2000, 11, 1)), true) U.deepStrictEqual(_.eqDate.equals(new Date(2000, 10, 1), new Date(2000, 11, 2)), false) }) it('eqMonth', () => { U.deepStrictEqual(_.eqMonth.equals(new Date(2000, 10, 1), new Date(2000, 10, 7)), true) U.deepStrictEqual(_.eqMonth.equals(new Date(2000, 10, 1), new Date(2000, 11, 7)), false) }) it('eqYear', () => { U.deepStrictEqual(_.eqYear.equals(new Date(2000, 10, 1), new Date(2000, 11, 7)), true) U.deepStrictEqual(_.eqYear.equals(new Date(2000, 10, 1), new Date(2001, 11, 7)), false) }) it('Ord', () => { U.deepStrictEqual(_.Ord.compare(new Date(0), new Date(0)), 0) U.deepStrictEqual(_.Ord.compare(new Date(0), new Date(1)), -1) U.deepStrictEqual(_.Ord.compare(new Date(1), new Date(0)), 1) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('create', () => { const d1 = _.create() U.deepStrictEqual(d1 instanceof Date, true) }) it('now', () => { const m1 = _.now() U.deepStrictEqual(typeof m1, 'number') }) }) ================================================ FILE: test/Either.ts ================================================ import { sequenceT } from '../src/Apply' import * as _ from '../src/Either' import { identity, pipe } from '../src/function' import * as N from '../src/number' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { separated } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' describe('Either', () => { describe('pipeables', () => { it('mapLeft', () => { U.deepStrictEqual(pipe(_.right('bar'), _.mapLeft(U.double)), _.right('bar')) U.deepStrictEqual(pipe(_.left(2), _.mapLeft(U.double)), _.left(4)) }) it('alt', () => { U.deepStrictEqual( pipe( _.right(1), _.alt(() => _.right(2)) ), _.right(1) ) U.deepStrictEqual( pipe( _.right(1), _.alt(() => _.left('a')) ), _.right(1) ) U.deepStrictEqual( pipe( _.left('a'), _.alt(() => _.right(2)) ), _.right(2) ) U.deepStrictEqual( pipe( _.left('a'), _.alt(() => _.left('b')) ), _.left('b') ) }) it('map', () => { const f = (s: string): number => s.length U.deepStrictEqual(pipe(_.right('abc'), _.map(f)), _.right(3)) U.deepStrictEqual(pipe(_.left('s'), _.map(f)), _.left('s')) }) it('ap', () => { const f = (s: string): number => s.length U.deepStrictEqual(pipe(_.right(f), _.ap(_.right('abc'))), _.right(3)) U.deepStrictEqual(pipe(_.right(f), _.ap(_.left('maError'))), _.left('maError')) U.deepStrictEqual( pipe(_.left number>('mabError'), _.ap(_.right('abc'))), _.left('mabError') ) U.deepStrictEqual(pipe(_.left('mabError'), _.ap(_.left('maError'))), _.left('mabError')) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.right('a'), _.apFirst(_.right(1))), _.right('a')) }) it('apFirstW', () => { const f = _.right(true) U.deepStrictEqual(pipe(_.right('abc'), _.apFirstW(f)), _.right('abc')) U.deepStrictEqual(pipe(_.left('maError'), _.apFirstW(f)), _.left('maError')) }) it('apSecond', () => { U.deepStrictEqual(pipe(_.right('a'), _.apSecond(_.right(1))), _.right(1)) }) it('apSecondW', () => { const f = _.right(true) U.deepStrictEqual(pipe(_.right('abc'), _.apSecondW(f)), _.right(true)) U.deepStrictEqual(pipe(_.left('maError'), _.apSecondW(f)), _.left('maError')) }) it('flatMap', () => { const f = (s: string) => _.right(s.length) U.deepStrictEqual(pipe(_.right('abc'), _.flatMap(f)), _.right(3)) U.deepStrictEqual(_.flatMap(_.right('abc'), f), _.right(3)) U.deepStrictEqual(pipe(_.left('maError'), _.flatMap(f)), _.left('maError')) U.deepStrictEqual(_.flatMap(_.left('maError'), f), _.left('maError')) }) it('chain', () => { const f = (s: string) => _.right(s.length) U.deepStrictEqual(pipe(_.right('abc'), _.chain(f)), _.right(3)) U.deepStrictEqual(pipe(_.left('maError'), _.chain(f)), _.left('maError')) }) it('tap', () => { const f = (s: string) => _.right(s.length) U.deepStrictEqual(pipe(_.right('abc'), _.tap(f)), _.right('abc')) U.deepStrictEqual(pipe(_.left('maError'), _.tap(f)), _.left('maError')) U.deepStrictEqual(_.tap(_.right('abc'), f), _.right('abc')) U.deepStrictEqual(_.tap(_.left('maError'), f), _.left('maError')) }) it('chainFirst', () => { const f = (s: string) => _.right(s.length) U.deepStrictEqual(pipe(_.right('abc'), _.chainFirst(f)), _.right('abc')) U.deepStrictEqual(pipe(_.left('maError'), _.chainFirst(f)), _.left('maError')) }) it('chainFirstW', () => { const f = (s: string) => _.right(s.length) U.deepStrictEqual(pipe(_.right('abc'), _.chainFirstW(f)), _.right('abc')) U.deepStrictEqual(pipe(_.left('maError'), _.chainFirstW(f)), _.left('maError')) }) it('duplicate', () => { U.deepStrictEqual(pipe(_.right('a'), _.duplicate), _.right(_.right('a'))) }) it('extend', () => { U.deepStrictEqual( pipe( _.right(1), _.extend(() => 2) ), _.right(2) ) U.deepStrictEqual( pipe( _.left('err'), _.extend(() => 2) ), _.left('err') ) }) it('flatten', () => { U.deepStrictEqual(pipe(_.right(_.right('a')), _.flatten), _.right('a')) }) it('flattenW', () => { U.deepStrictEqual(pipe(_.right<'left1', _.Either<'left2', 'a'>>(_.right('a')), _.flattenW), _.right('a')) }) it('bimap', () => { const f = (s: string): number => s.length const g = (n: number): boolean => n > 2 U.deepStrictEqual(pipe(_.right(1), _.bimap(f, g)), _.right(false)) }) it('foldMap', () => { U.deepStrictEqual(pipe(_.right('a'), _.foldMap(S.Monoid)(identity)), 'a') U.deepStrictEqual(pipe(_.left(1), _.foldMap(S.Monoid)(identity)), '') }) it('reduce', () => { U.deepStrictEqual( pipe( _.right('bar'), _.reduce('foo', (b, a) => b + a) ), 'foobar' ) U.deepStrictEqual( pipe( _.left('bar'), _.reduce('foo', (b, a) => b + a) ), 'foo' ) }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(_.right('a'), _.reduceRight('', f)), 'a') U.deepStrictEqual(pipe(_.left(1), _.reduceRight('', f)), '') }) it('traverse', () => { const traverse = _.traverse(O.Applicative)((n: number) => (n >= 2 ? O.some(n) : O.none)) U.deepStrictEqual(pipe(_.left('a'), traverse), O.some(_.left('a'))) U.deepStrictEqual(pipe(_.right(1), traverse), O.none) U.deepStrictEqual(pipe(_.right(3), traverse), O.some(_.right(3))) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence(_.right(O.some(1))), O.some(_.right(1))) U.deepStrictEqual(sequence(_.left('a')), O.some(_.left('a'))) U.deepStrictEqual(sequence(_.right(O.none)), O.none) }) }) it('fold', () => { const f = (s: string) => `left${s.length}` const g = (s: string) => `right${s.length}` const fold = _.fold(f, g) U.deepStrictEqual(fold(_.left('abc')), 'left3') U.deepStrictEqual(fold(_.right('abc')), 'right3') }) it('getOrElse', () => { U.deepStrictEqual( pipe( _.right(12), _.getOrElse(() => 17) ), 12 ) U.deepStrictEqual( pipe( _.left('a'), _.getOrElse(() => 17) ), 17 ) U.deepStrictEqual( pipe( _.left('a'), _.getOrElse((l: string) => l.length + 1) ), 2 ) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(2, _.left('a')), false) U.deepStrictEqual(_.elem(N.Eq)(2, _.right(2)), true) U.deepStrictEqual(_.elem(N.Eq)(1, _.right(2)), false) U.deepStrictEqual(pipe(_.left('a'), _.elem(N.Eq)(2)), false) U.deepStrictEqual(pipe(_.right(2), _.elem(N.Eq)(2)), true) U.deepStrictEqual(pipe(_.right(2), _.elem(N.Eq)(1)), false) }) it('filterOrElse', () => { const gt10 = (n: number): boolean => n > 10 U.deepStrictEqual( pipe( _.right(12), _.filterOrElse(gt10, () => -1) ), _.right(12) ) U.deepStrictEqual( pipe( _.right(7), _.filterOrElse(gt10, () => -1) ), _.left(-1) ) U.deepStrictEqual( pipe( _.left(12), _.filterOrElse(gt10, () => -1) ), _.left(12) ) U.deepStrictEqual( pipe( _.right(7), _.filterOrElse(gt10, (n) => `invalid ${n}`) ), _.left('invalid 7') ) type Color = 'red' | 'blue' const isColor = (s: string): s is Color => s === 'red' || s === 'blue' const errorHandler = (s: string) => `invalid color ${s}` U.deepStrictEqual(pipe(_.right('red'), _.filterOrElse(isColor, errorHandler)), _.right('red')) U.deepStrictEqual(pipe(_.right('foo'), _.filterOrElse(isColor, errorHandler)), _.left('invalid color foo')) U.deepStrictEqual(pipe(_.left('err'), _.filterOrElse(isColor, errorHandler)), _.left('err')) }) it('isLeft', () => { U.deepStrictEqual(_.isLeft(_.right(1)), false) U.deepStrictEqual(_.isLeft(_.left(1)), true) }) it('isRight', () => { U.deepStrictEqual(_.isRight(_.right(1)), true) U.deepStrictEqual(_.isRight(_.left(1)), false) }) it('orElse', () => { U.deepStrictEqual( pipe( _.right(1), _.orElse(() => _.right(2)) ), _.right(1) ) U.deepStrictEqual( pipe( _.right(1), _.orElse(() => _.left('foo')) ), _.right(1) ) U.deepStrictEqual( pipe( _.left('a'), _.orElse(() => _.right(1)) ), _.right(1) ) U.deepStrictEqual( pipe( _.left('a'), _.orElse(() => _.left('b')) ), _.left('b') ) }) it('swap', () => { U.deepStrictEqual(_.swap(_.right('a')), _.left('a')) U.deepStrictEqual(_.swap(_.left('b')), _.right('b')) }) it('parseJSON', () => { U.deepStrictEqual(_.parseJSON('{"a":1}', _.toError), _.right({ a: 1 })) U.deepStrictEqual( _.parseJSON('{"a":}', _.toError), _.left(new SyntaxError(`Unexpected token '}', "{"a":}" is not valid JSON`)) ) }) it('stringifyJSON', () => { U.deepStrictEqual(_.stringifyJSON({ a: 1 }, _.toError), _.right('{"a":1}')) const circular: any = { ref: null } circular.ref = circular U.deepStrictEqual( pipe( _.stringifyJSON(circular, _.toError), _.mapLeft((e) => e.message.includes('Converting circular structure to JSON')) ), _.left(true) ) interface Person { readonly name: string readonly age: number } const person: Person = { name: 'Giulio', age: 45 } U.deepStrictEqual(_.stringifyJSON(person, _.toError), _.right('{"name":"Giulio","age":45}')) // #1397 U.deepStrictEqual( _.stringifyJSON(undefined, _.toError), _.left(new Error('Converting unsupported structure to JSON')) ) }) it('fromPredicate', () => { const gt2 = _.fromPredicate( (n: number) => n >= 2, (n) => `Invalid number ${n}` ) U.deepStrictEqual(gt2(3), _.right(3)) U.deepStrictEqual(gt2(1), _.left('Invalid number 1')) // refinements type Color = 'red' | 'blue' const isColor = (s: string): s is Color => s === 'red' || s === 'blue' const from = _.fromPredicate(isColor, (s) => `invalid color ${s}`) U.deepStrictEqual(from('red'), _.right('red')) U.deepStrictEqual(from('foo'), _.left('invalid color foo')) }) it('fromNullable', () => { U.deepStrictEqual(_.fromNullable('default')(null), _.left('default')) U.deepStrictEqual(_.fromNullable('default')(undefined), _.left('default')) U.deepStrictEqual(_.fromNullable('default')(1), _.right(1)) }) it('tryCatch', () => { U.deepStrictEqual( _.tryCatch(() => { return 1 }, _.toError), _.right(1) ) U.deepStrictEqual( _.tryCatch(() => { throw 'string error' }, _.toError), _.left(new Error('string error')) ) U.deepStrictEqual( _.tryCatch(() => { throw Object.create(null) }, _.toError), _.left(new Error()) ) U.deepStrictEqual( _.tryCatch(() => { throw { toString: [] } }, _.toError), _.left(new Error()) ) }) describe('getEq', () => { it('equals', () => { const equals = _.getEq(S.Eq, N.Eq).equals U.deepStrictEqual(equals(_.right(1), _.right(1)), true) U.deepStrictEqual(equals(_.right(1), _.right(2)), false) U.deepStrictEqual(equals(_.right(1), _.left('foo')), false) U.deepStrictEqual(equals(_.left('foo'), _.left('foo')), true) U.deepStrictEqual(equals(_.left('foo'), _.left('bar')), false) U.deepStrictEqual(equals(_.left('foo'), _.right(1)), false) }) }) describe('ChainRec', () => { it('chainRec', () => { const chainRec = _.ChainRec.chainRec U.deepStrictEqual( chainRec(1, () => _.left('foo')), _.left('foo') ) U.deepStrictEqual( chainRec(1, () => _.right(_.right(1))), _.right(1) ) U.deepStrictEqual( chainRec(1, (a) => { if (a < 5) { return _.right(_.left(a + 1)) } else { return _.right(_.right(a)) } }), _.right(5) ) }) }) describe('getWitherable', () => { const W = _.getWitherable(S.Monoid) const p = (n: number) => n > 2 it('compact', () => { U.deepStrictEqual(W.compact(_.left('1')), _.left('1')) U.deepStrictEqual(W.compact(_.right(O.none)), _.left(S.Monoid.empty)) U.deepStrictEqual(W.compact(_.right(O.some(123))), _.right(123)) }) it('separate', () => { U.deepStrictEqual(W.separate(_.left('123')), separated(_.left('123'), _.left('123'))) U.deepStrictEqual(W.separate(_.right(_.left('123'))), separated(_.right('123'), _.left(S.Monoid.empty))) U.deepStrictEqual(W.separate(_.right(_.right('123'))), separated(_.left(S.Monoid.empty), _.right('123'))) }) it('partition', () => { U.deepStrictEqual(W.partition(_.left('123'), p), separated(_.left('123'), _.left('123'))) U.deepStrictEqual(W.partition(_.right(1), p), separated(_.right(1), _.left(S.Monoid.empty))) U.deepStrictEqual(W.partition(_.right(3), p), separated(_.left(S.Monoid.empty), _.right(3))) }) it('partitionMap', () => { const f = (n: number) => (p(n) ? _.right(n + 1) : _.left(n - 1)) U.deepStrictEqual(W.partitionMap(_.left('123'), f), separated(_.left('123'), _.left('123'))) U.deepStrictEqual(W.partitionMap(_.right(1), f), separated(_.right(0), _.left(S.Monoid.empty))) U.deepStrictEqual(W.partitionMap(_.right(3), f), separated(_.left(S.Monoid.empty), _.right(4))) }) it('filter', () => { U.deepStrictEqual(W.filter(_.left('123'), p), _.left('123')) U.deepStrictEqual(W.filter(_.right(1), p), _.left(S.Monoid.empty)) U.deepStrictEqual(W.filter(_.right(3), p), _.right(3)) }) it('filterMap', () => { const f = (n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(W.filterMap(_.left('123'), f), _.left('123')) U.deepStrictEqual(W.filterMap(_.right(1), f), _.left(S.Monoid.empty)) U.deepStrictEqual(W.filterMap(_.right(3), f), _.right(4)) }) it('wither', async () => { const wither = W.wither(T.ApplicativePar) const f = (n: number) => T.of(p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(await wither(_.left('foo'), f)(), _.left('foo')) U.deepStrictEqual(await wither(_.right(1), f)(), _.left(S.Monoid.empty)) U.deepStrictEqual(await wither(_.right(3), f)(), _.right(4)) }) it('wilt', async () => { const wilt = W.wilt(T.ApplicativePar) const f = (n: number) => T.of(p(n) ? _.right(n + 1) : _.left(n - 1)) U.deepStrictEqual(await wilt(_.left('foo'), f)(), separated(_.left('foo'), _.left('foo'))) U.deepStrictEqual(await wilt(_.right(1), f)(), separated(_.right(0), _.left(S.Monoid.empty))) U.deepStrictEqual(await wilt(_.right(3), f)(), separated(_.left(S.Monoid.empty), _.right(4))) }) }) describe('getSemigroup', () => { it('concat', () => { const S = _.getSemigroup(N.SemigroupSum) U.deepStrictEqual(S.concat(_.left('a'), _.left('b')), _.left('a')) U.deepStrictEqual(S.concat(_.left('a'), _.right(2)), _.right(2)) U.deepStrictEqual(S.concat(_.right(1), _.left('b')), _.right(1)) U.deepStrictEqual(S.concat(_.right(1), _.right(2)), _.right(3)) }) }) describe('getApplySemigroup', () => { it('concat', () => { const S = _.getApplySemigroup(N.SemigroupSum) U.deepStrictEqual(S.concat(_.left('a'), _.left('b')), _.left('a')) U.deepStrictEqual(S.concat(_.left('a'), _.right(2)), _.left('a')) U.deepStrictEqual(S.concat(_.right(1), _.left('b')), _.left('b')) U.deepStrictEqual(S.concat(_.right(1), _.right(2)), _.right(3)) }) }) describe('getApplyMonoid', () => { it('concat', () => { const M = _.getApplyMonoid(N.MonoidSum) U.deepStrictEqual(M.concat(_.left('a'), M.empty), _.left('a')) U.deepStrictEqual(M.concat(M.empty, _.left('b')), _.left('b')) U.deepStrictEqual(M.concat(_.right(1), M.empty), _.right(1)) U.deepStrictEqual(M.concat(M.empty, _.right(2)), _.right(2)) }) }) describe('getShow', () => { it('show', () => { const Sh = _.getShow(S.Show, S.Show) U.deepStrictEqual(Sh.show(_.left('a')), `left("a")`) U.deepStrictEqual(Sh.show(_.right('a')), `right("a")`) }) }) it('getApplicativeValidation', () => { const A = _.getApplicativeValidation(S.Monoid) U.deepStrictEqual(sequenceT(A)(_.left('a'), _.left('b')), _.left('ab')) const AV = _.getValidation(S.Monoid) U.deepStrictEqual(sequenceT(AV)(_.left('a'), _.left('b')), _.left('ab')) }) it('getAltValidation', () => { const A = _.getAltValidation(S.Monoid) U.deepStrictEqual( A.alt(_.left('a'), () => _.left('b')), _.left('ab') ) U.deepStrictEqual( A.alt(_.right(1), () => _.left('b')), _.right(1) ) U.deepStrictEqual( A.alt(_.left('a'), () => _.right(2)), _.right(2) ) const AV = _.getValidation(S.Monoid) U.deepStrictEqual( AV.alt(_.left('a'), () => _.left('b')), _.left('ab') ) }) it('getValidationSemigroup', () => { const VS = _.getValidationSemigroup(S.Monoid, N.MonoidSum) U.deepStrictEqual(VS.concat(_.right(1), _.right(2)), _.right(3)) U.deepStrictEqual(VS.concat(_.right(1), _.left('foo')), _.left('foo')) U.deepStrictEqual(VS.concat(_.left('foo'), _.right(1)), _.left('foo')) U.deepStrictEqual(VS.concat(_.left('foo'), _.left('bar')), _.left('foobar')) }) it('getValidationMonoid', () => { const M = _.getValidationMonoid(S.Monoid, N.MonoidSum) U.deepStrictEqual(M.concat(_.right(1), M.empty), _.right(1)) U.deepStrictEqual(M.concat(M.empty, _.right(1)), _.right(1)) }) it('fromOption', () => { U.deepStrictEqual(_.fromOption(() => 'none')(O.none), _.left('none')) U.deepStrictEqual(_.fromOption(() => 'none')(O.some(1)), _.right(1)) }) it('fromOptionK', () => { const f = _.fromOptionK(() => 'a')((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(1), _.right(1)) U.deepStrictEqual(f(-1), _.left('a')) }) it('flatMapOption', () => { const f = _.flatMapOption( (n: number) => (n > 0 ? O.some(n) : O.none), () => 'a' ) U.deepStrictEqual(f(_.right(1)), _.right(1)) U.deepStrictEqual(f(_.right(-1)), _.left('a')) U.deepStrictEqual(f(_.left('b')), _.left('b')) }) it('chainOptionK', () => { const f = _.chainOptionK(() => 'a')((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(_.right(1)), _.right(1)) U.deepStrictEqual(f(_.right(-1)), _.left('a')) U.deepStrictEqual(f(_.left('b')), _.left('b')) }) it('exists', () => { const gt2 = _.exists((n: number) => n > 2) U.deepStrictEqual(gt2(_.left('a')), false) U.deepStrictEqual(gt2(_.right(1)), false) U.deepStrictEqual(gt2(_.right(3)), true) }) it('do notation', () => { U.deepStrictEqual( pipe( _.right(1), _.bindTo('a'), _.bind('b', () => _.right('b')), _.let('c', ({ a, b }) => [a, b]) ), _.right({ a: 1, b: 'b', c: [1, 'b'] }) ) }) it('apS', () => { U.deepStrictEqual( pipe(_.right(1), _.bindTo('a'), _.apS('b', _.right('b'))), _.right({ a: 1, b: 'b' }) ) }) it('fromNullableK', () => { const f = _.fromNullableK('error')((n: number) => (n > 0 ? n : null)) U.deepStrictEqual(f(1), _.right(1)) U.deepStrictEqual(f(-1), _.left('error')) }) it('flatMapNullable', () => { const f = _.flatMapNullable( (n: number) => (n > 0 ? n : null), () => 'error' ) U.deepStrictEqual(f(_.right(1)), _.right(1)) U.deepStrictEqual(f(_.right(-1)), _.left('error')) U.deepStrictEqual(f(_.left('a')), _.left('a')) }) it('chainNullableK', () => { const f = _.chainNullableK('error')((n: number) => (n > 0 ? n : null)) U.deepStrictEqual(f(_.right(1)), _.right(1)) U.deepStrictEqual(f(_.right(-1)), _.left('error')) U.deepStrictEqual(f(_.left('a')), _.left('a')) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(pipe(RA.empty, f), _.right(RA.empty)) U.deepStrictEqual(pipe(input, f), _.right(['a0', 'b1'])) U.deepStrictEqual(pipe(['a', ''], f), _.left('e')) }) // old it('sequenceArray', () => { U.deepStrictEqual(pipe([_.right(1), _.right(2)], _.sequenceArray), _.right([1, 2])) U.deepStrictEqual(pipe([_.right(1), _.left('a')], _.sequenceArray), _.left('a')) }) }) describe('getCompactable', () => { const C = _.getCompactable(S.Monoid) it('compact', () => { U.deepStrictEqual(C.compact(_.left('1')), _.left('1')) U.deepStrictEqual(C.compact(_.right(O.none)), _.left(S.Monoid.empty)) U.deepStrictEqual(C.compact(_.right(O.some(123))), _.right(123)) }) it('separate', () => { U.deepStrictEqual(C.separate(_.left('123')), separated(_.left('123'), _.left('123'))) U.deepStrictEqual(C.separate(_.right(_.left('123'))), separated(_.right('123'), _.left(S.Monoid.empty))) U.deepStrictEqual(C.separate(_.right(_.right('123'))), separated(_.left(S.Monoid.empty), _.right('123'))) }) }) it('toUnion', () => { U.deepStrictEqual(_.toUnion(_.right(1)), 1) U.deepStrictEqual(_.toUnion(_.left('a')), 'a') }) it('tryCatchK', () => { const f = _.tryCatchK((s: string) => { const len = s.length if (len > 0) { return len } throw new Error('empty string') }, identity) U.deepStrictEqual(f('a'), _.right(1)) U.deepStrictEqual(f(''), _.left(new Error('empty string'))) }) it('as', () => { U.deepStrictEqual(pipe(_.right('a'), _.as('b')), _.right('b')) U.deepStrictEqual(_.as(_.of('a'), 'b'), _.right('b')) U.deepStrictEqual(_.as(_.left('error'), 'b'), _.left('error')) }) it('asUnit', () => { U.deepStrictEqual(pipe(_.of('a'), _.asUnit), _.of(undefined)) }) }) ================================================ FILE: test/EitherT.ts ================================================ import * as E from '../src/Either' import { getEitherM } from '../src/EitherT' import * as I from '../src/IO' import * as U from './util' describe('EitherT', () => { const T = getEitherM(I.Monad) it('fold', () => { const onLeft = (s: string) => I.of(`left(${s})`) const onRight = (n: number) => I.of(`right(${n})`) U.deepStrictEqual(T.fold(I.of(E.right(1)), onLeft, onRight)(), 'right(1)') U.deepStrictEqual(T.fold(I.of(E.left('bb')), onLeft, onRight)(), 'left(bb)') }) it('getOrElse', () => { const onLeft = (s: string) => I.of(`left(${s})`) U.deepStrictEqual(T.getOrElse(I.of(E.right('a')), onLeft)(), 'a') U.deepStrictEqual(T.getOrElse(I.of(E.left('bb')), onLeft)(), 'left(bb)') }) }) ================================================ FILE: test/Endomorphism.ts ================================================ import * as _ from '../src/Endomorphism' import * as U from './util' describe('Endomorphism', () => { it('getMonoid', () => { const M = _.getMonoid() const inc = (n: number) => n + 1 const f = M.concat(inc, U.double) U.deepStrictEqual(f(3), 8) }) }) ================================================ FILE: test/Eq.ts ================================================ import * as B from '../src/boolean' import * as _ from '../src/Eq' import { pipe } from '../src/function' import { concatAll } from '../src/Monoid' import * as N from '../src/number' import * as S from '../src/string' import * as U from './util' describe('Eq', () => { describe('pipeables', () => { it('contramap', () => { const E = pipe( S.Eq, _.contramap((p: Person) => p.name) ) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'a', age: 2 }), true) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'a', age: 1 }), true) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'b', age: 1 }), false) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'b', age: 2 }), false) }) }) it('tuple', () => { const E = _.tuple(S.Eq, N.Eq, B.Eq) U.deepStrictEqual(E.equals(['a', 1, true], ['a', 1, true]), true) U.deepStrictEqual(E.equals(['a', 1, true], ['b', 1, true]), false) U.deepStrictEqual(E.equals(['a', 1, true], ['a', 2, true]), false) U.deepStrictEqual(E.equals(['a', 1, true], ['a', 1, false]), false) }) interface Person { readonly name: string readonly age: number } it('fromEquals', () => { interface A { readonly x: number } let nbCall = 0 const S1 = _.fromEquals((a, b) => { nbCall += 1 return a.x === b.x }) const a1 = { x: 1 } const a2 = { x: 1 } S1.equals(a1, a1) U.deepStrictEqual(nbCall, 0) S1.equals(a1, a2) U.deepStrictEqual(nbCall, 1) }) it('struct', () => { const E = _.struct({ name: S.Eq, age: N.Eq }) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'a', age: 1 }), true) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'a', age: 2 }), false) U.deepStrictEqual(E.equals({ name: 'a', age: 1 }, { name: 'b', age: 1 }), false) }) it('eqStrict', () => { U.deepStrictEqual(_.eqStrict.equals(1, 1), true) U.deepStrictEqual(_.eqStrict.equals(1, 'a'), false) }) it('getMonoid', () => { type T = readonly [string, number, boolean] const M = _.getMonoid() const eqFst: _.Eq = _.contramap((x: T) => x[0])(S.Eq) const eqSnd: _.Eq = _.contramap((x: T) => x[1])(N.Eq) const eq3rd: _.Eq = _.contramap((x: T) => x[2])(B.Eq) const eq = concatAll(M)([eqFst, eqSnd, eq3rd]) U.deepStrictEqual(eq.equals(['a', 1, true], ['a', 1, true]), true) U.deepStrictEqual(eq.equals(['a', 1, true], ['b', 1, true]), false) U.deepStrictEqual(eq.equals(['a', 1, true], ['a', 2, true]), false) U.deepStrictEqual(eq.equals(['a', 1, true], ['a', 1, false]), false) }) it('eqDate', () => { const E = _.eqDate U.deepStrictEqual(E.equals(new Date(0), new Date(0)), true) U.deepStrictEqual(E.equals(new Date(0), new Date(1)), false) U.deepStrictEqual(E.equals(new Date(1), new Date(0)), false) }) }) ================================================ FILE: test/Field.ts ================================================ import * as _ from '../src/Field' import * as N from '../src/number' import * as U from './util' describe('Field', () => { it('gcd', () => { const gcdNumber = _.gcd(N.Eq, N.Field) U.deepStrictEqual(gcdNumber(10, 5), 5) U.deepStrictEqual(gcdNumber(10, 2), 2) U.deepStrictEqual(gcdNumber(10, 3), 1) }) it('lcm', () => { const lcmNumber = _.lcm(N.Eq, N.Field) U.deepStrictEqual(lcmNumber(4, 6), 12) U.deepStrictEqual(lcmNumber(4, 0), 0) }) it('fieldNumber', () => { const F = _.fieldNumber U.deepStrictEqual(F.add(1, 2), 3) U.deepStrictEqual(F.div(4, 2), 2) U.deepStrictEqual(F.mod(4, 2), 0) U.deepStrictEqual(F.mul(4, 2), 8) U.deepStrictEqual(F.sub(3, 2), 1) U.deepStrictEqual(F.degree(0), 1) U.deepStrictEqual(F.degree(1), 1) U.deepStrictEqual(F.degree(2), 1) }) }) ================================================ FILE: test/Filterable.ts ================================================ import { left, right } from '../src/Either' import { getFilterableComposition } from '../src/Filterable' import { increment } from '../src/function' import { none, some } from '../src/Option' import * as RA from '../src/ReadonlyArray' import { separated } from '../src/Separated' import * as U from './util' describe('Filterable', () => { it('getFilterableComposition', () => { const F = getFilterableComposition(RA.Functor, RA.Filterable) U.deepStrictEqual(F.map([[1]], increment), [[2]]) U.deepStrictEqual( F.filter( [ [1, 2], [3, 4] ], (a) => a > 1 ), [[2], [3, 4]] ) U.deepStrictEqual( F.filterMap( [ ['a', 'bb'], ['ccc', 'dddd'] ], (a) => (a.length > 1 ? some(a.length) : none) ), [[2], [3, 4]] ) U.deepStrictEqual( F.partition( [ ['a', 'bb'], ['ccc', 'dddd'] ], (a) => a.length % 2 === 0 ), separated([['a'], ['ccc']], [['bb'], ['dddd']]) ) U.deepStrictEqual( F.partitionMap( [ ['a', 'bb'], ['ccc', 'dddd'] ], (a) => (a.length % 2 === 0 ? right(a.length) : left(a)) ), separated([['a'], ['ccc']], [[2], [4]]) ) }) }) ================================================ FILE: test/Foldable.ts ================================================ import * as _ from '../src/Foldable' import { pipe } from '../src/function' import * as I from '../src/IO' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as S from '../src/string' import * as T from '../src/Tree' import * as U from './util' export const ArrayOptionURI = 'ArrayOption' export type ArrayOptionURI = typeof ArrayOptionURI describe('Foldable', () => { it('getFoldableComposition', () => { const F = _.getFoldableComposition(RA.Foldable, O.Foldable) // reduce U.deepStrictEqual(F.reduce([O.some('a'), O.some('b'), O.some('c')], '', S.Semigroup.concat), 'abc') U.deepStrictEqual(F.reduce([O.none, O.some('b'), O.none], '', S.Semigroup.concat), 'b') U.deepStrictEqual(F.reduce([O.none, O.none, O.none], '', S.Semigroup.concat), '') U.deepStrictEqual(F.reduce([], '', S.Semigroup.concat), '') // foldMap U.deepStrictEqual( F.foldMap(S.Monoid)([O.some('a'), O.some('b'), O.some('c')], (a) => a), 'abc' ) U.deepStrictEqual( F.foldMap(S.Monoid)([O.none, O.some('b'), O.none], (a) => a), 'b' ) U.deepStrictEqual( F.foldMap(S.Monoid)([O.none, O.none, O.none], (a) => a), '' ) U.deepStrictEqual( F.foldMap(S.Monoid)([], (a: string) => a), '' ) // reduceRight U.deepStrictEqual(F.reduceRight([O.some('a'), O.some('b'), O.some('c')], '', S.Semigroup.concat), 'abc') U.deepStrictEqual(F.reduceRight([O.none, O.some('b'), O.none], '', S.Semigroup.concat), 'b') U.deepStrictEqual(F.reduceRight([O.none, O.none, O.none], '', S.Semigroup.concat), '') U.deepStrictEqual(F.reduceRight([], '', S.Semigroup.concat), '') }) it('intercalate', () => { U.deepStrictEqual(_.intercalate(S.Monoid, RA.Foldable)(',', ['a', 'b', 'c']), 'a,b,c') }) it('toReadonlyArray', () => { // Option const optionToArray = _.toReadonlyArray(O.Foldable) U.deepStrictEqual(optionToArray(O.some(1)), [1]) U.deepStrictEqual(optionToArray(O.none), []) // Tree const treeToArray = _.toReadonlyArray(T.Foldable) U.deepStrictEqual(treeToArray(T.make(1, [T.make(2, []), T.make(3, []), T.make(4, [])])), [1, 2, 3, 4]) }) it('traverse_', () => { let log = '' const append = (s: String) => () => (log += s) _.traverse_(I.Applicative, RA.Foldable)(['a', 'b', 'c'], append)() U.deepStrictEqual(log, 'abc') }) it('foldM', () => { U.deepStrictEqual( _.foldM(O.Monad, RA.Foldable)([], 1, () => O.none), O.some(1) ) U.deepStrictEqual( _.foldM(O.Monad, RA.Foldable)([2], 1, () => O.none), O.none ) U.deepStrictEqual( _.foldM(O.Monad, RA.Foldable)([2], 1, (b, a) => O.some(b + a)), O.some(3) ) }) it('reduceM', () => { U.deepStrictEqual( pipe( [], _.reduceM(O.Monad, RA.Foldable)(1, () => O.none) ), O.some(1) ) U.deepStrictEqual( pipe( [2], _.reduceM(O.Monad, RA.Foldable)(1, () => O.none) ), O.none ) U.deepStrictEqual( pipe( [2], _.reduceM(O.Monad, RA.Foldable)(1, (b, a) => O.some(b + a)) ), O.some(3) ) }) }) ================================================ FILE: test/FoldableWithIndex.ts ================================================ import { getFoldableWithIndexComposition } from '../src/FoldableWithIndex' import * as RA from '../src/ReadonlyArray' import * as S from '../src/string' import * as U from './util' describe('FoldableWithIndex', () => { it('getFoldableWithIndexComposition', () => { const arrayOfArray = getFoldableWithIndexComposition(RA.FoldableWithIndex, RA.FoldableWithIndex) const fa: ReadonlyArray> = [ ['a', 'b'], ['c', 'd'] ] U.deepStrictEqual( arrayOfArray.reduceWithIndex(fa, '', ([i, j], b: string, a: string) => b + a + i + j), 'a00b01c10d11' ) U.deepStrictEqual( arrayOfArray.foldMapWithIndex(S.Monoid)(fa, ([i, j], a) => a + i + j), 'a00b01c10d11' ) U.deepStrictEqual( arrayOfArray.reduceRightWithIndex(fa, '', ([i, j], a: string, b: string) => b + a + i + j), 'd11c10b01a00' ) }) }) ================================================ FILE: test/Functor.ts ================================================ import { getFunctorComposition } from '../src/Functor' import * as option from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as U from './util' describe('Functor', () => { it('getFunctorComposition', () => { const arrayOption = getFunctorComposition(RA.Functor, option.Functor) U.deepStrictEqual(arrayOption.map([option.some(1)], U.double), [option.some(2)]) }) }) ================================================ FILE: test/FunctorWithIndex.ts ================================================ import { getFunctorWithIndexComposition } from '../src/FunctorWithIndex' import * as RA from '../src/ReadonlyArray' import * as U from './util' describe('FunctorWithIndex', () => { it('getFunctorComposition', () => { const FWI = getFunctorWithIndexComposition(RA.FunctorWithIndex, RA.FunctorWithIndex) const f = ([i, j]: readonly [number, number], a: string) => a + i + j U.deepStrictEqual( FWI.map([[1], [2]], (n) => n * 2), [[2], [4]] ) U.deepStrictEqual( FWI.mapWithIndex( [ ['a', 'b'], ['c', 'd'] ], f ), [ ['a00', 'b01'], ['c10', 'd11'] ] ) }) }) ================================================ FILE: test/IO.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as _ from '../src/IO' import * as N from '../src/number' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import * as U from './util' describe('IO', () => { describe('pipeables', () => { it('map', () => { U.deepStrictEqual(pipe(_.of(1), _.map(U.double))(), 2) }) it('ap', () => { U.deepStrictEqual(pipe(_.of(U.double), _.ap(_.of(1)))(), 2) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.of('a'), _.apFirst(_.of('b')))(), 'a') }) it('apSecond', () => { U.deepStrictEqual(pipe(_.of('a'), _.apSecond(_.of('b')))(), 'b') }) it('flatMap', () => { const f = (n: number) => _.of(n * 2) U.deepStrictEqual(pipe(_.of(1), _.flatMap(f))(), 2) U.deepStrictEqual(_.flatMap(_.of(1), f)(), 2) }) it('chain', () => { const f = (n: number) => _.of(n * 2) U.deepStrictEqual(pipe(_.of(1), _.chain(f))(), 2) }) it('flatten', () => { U.deepStrictEqual(pipe(_.of(_.of(1)), _.flatten)(), 1) }) it('tap', () => { const f = (n: number) => _.of(n * 2) U.deepStrictEqual(pipe(_.of(1), _.tap(f))(), 1) U.deepStrictEqual(_.tap(_.of(1), f)(), 1) }) it('chainFirst', () => { const f = (n: number) => _.of(n * 2) U.deepStrictEqual(pipe(_.of(1), _.chainFirst(f))(), 1) }) }) it('getSemigroup', () => { const S = _.getSemigroup(N.SemigroupSum) const log: Array = [] const append = (message: string): _.IO => () => log.push(message) U.deepStrictEqual(S.concat(append('a'), append('b'))(), 3) U.deepStrictEqual(log, ['a', 'b']) }) it('getMonoid', () => { const M = _.getMonoid(N.MonoidSum) const log: Array = [] const append = (message: string): _.IO => () => log.push(message) U.deepStrictEqual(M.concat(append('a'), M.empty)(), 1) U.deepStrictEqual(M.concat(M.empty, append('b'))(), 2) U.deepStrictEqual(log, ['a', 'b']) }) it('chainRec', () => { const f = (n: number) => (n < 15000 ? _.of(E.left(n + 1)) : _.of(E.right('ok ' + n))) U.deepStrictEqual(_.ChainRec.chainRec(0, f)(), 'ok 15000') }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) )(), { a: 1, b: 'b', c: [1, 'b'] } ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b')))(), { a: 1, b: 'b' }) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => _.of(a + i)) U.strictEqual(pipe(RA.empty, f)(), RA.empty) U.deepStrictEqual(pipe(input, f)(), ['a0', 'b1']) }) // old it('sequenceArray', () => { const log: Array = [] const append = (n: number): _.IO => () => { log.push(n) return n } U.deepStrictEqual(pipe([append(1), append(2)], _.sequenceArray)(), [1, 2]) U.deepStrictEqual(log, [1, 2]) }) }) it('as', () => { U.deepStrictEqual(pipe(_.of('a'), _.as('b'))(), 'b') }) it('asUnit', () => { U.deepStrictEqual(pipe(_.of('a'), _.asUnit)(), undefined) }) }) ================================================ FILE: test/IOEither.ts ================================================ import { sequenceT } from '../src/Apply' import * as E from '../src/Either' import { constVoid, identity, pipe, SK } from '../src/function' import * as I from '../src/IO' import * as _ from '../src/IOEither' import * as N from '../src/number' import * as O from '../src/Option' import { pipeable } from '../src/pipeable' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { left, right } from '../src/Separated' import * as S from '../src/string' import * as U from './util' describe('IOEither', () => { describe('pipeables', () => { it('alt', () => { const r1 = _.right(1) const r2 = _.right(2) const l1 = _.left('foo') const l2 = _.left('bar') U.deepStrictEqual( pipe( l1, _.alt(() => l2) )(), E.left('bar') ) U.deepStrictEqual( pipe( l1, _.alt(() => r1) )(), E.right(1) ) U.deepStrictEqual( pipe( r1, _.alt(() => l1) )(), E.right(1) ) U.deepStrictEqual( pipe( r1, _.alt(() => r2) )(), E.right(1) ) }) it('map', () => { U.deepStrictEqual(pipe(_.right(1), _.map(U.double))(), E.right(2)) }) it('ap', () => { U.deepStrictEqual(pipe(_.right(U.double), _.ap(_.right(1)))(), E.right(2)) }) it('ApplicativePar', () => { const log: Array = [] const x = sequenceT(_.ApplicativePar)( _.rightIO(() => log.push('a')), _.leftIO(() => { log.push('b') return 'error' }), _.rightIO(() => log.push('c')) )() U.deepStrictEqual(x, E.left('error')) U.deepStrictEqual(log, ['a', 'b', 'c']) }) it('ApplicativeSeq', () => { const log: Array = [] const x = sequenceT(_.ApplicativeSeq)( _.rightIO(() => log.push('a')), _.leftIO(() => { log.push('b') return 'error' }), _.rightIO(() => log.push('c')) )() U.deepStrictEqual(x, E.left('error')) U.deepStrictEqual(log, ['a', 'b']) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.right('a'), _.apFirst(_.right('b')))(), E.right('a')) }) it('apFirstW', () => { const fa = _.right<'Foo', string>('a') const fb = _.right<'Bar', number>(1) U.deepStrictEqual(pipe(fa, _.apFirstW(fb))(), E.right('a')) }) it('apSecond', () => { U.deepStrictEqual(pipe(_.right('a'), _.apSecond(_.right('b')))(), E.right('b')) }) it('apSecondW', () => { const fa = _.right<'Foo', string>('a') const fb = _.right<'Bar', number>(1) U.deepStrictEqual(pipe(fa, _.apSecondW(fb))(), E.right(1)) }) it('flatMap', () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('foo')) U.deepStrictEqual(pipe(_.right('foo'), _.flatMap(f))(), E.right(3)) U.deepStrictEqual(_.flatMap(_.right('foo'), f)(), E.right(3)) U.deepStrictEqual(pipe(_.right('a'), _.flatMap(f))(), E.left('foo')) U.deepStrictEqual(_.flatMap(_.right('a'), f)(), E.left('foo')) }) it('chain', () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('foo')) U.deepStrictEqual(pipe(_.right('foo'), _.chain(f))(), E.right(3)) U.deepStrictEqual(pipe(_.right('a'), _.chain(f))(), E.left('foo')) }) it('tap', () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('foo')) U.deepStrictEqual(pipe(_.right('foo'), _.tap(f))(), E.right('foo')) U.deepStrictEqual(pipe(_.right('a'), _.tap(f))(), E.left('foo')) U.deepStrictEqual(_.tap(_.right('foo'), f)(), E.right('foo')) U.deepStrictEqual(_.tap(_.right('a'), f)(), E.left('foo')) }) it('chainFirst', () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('foo')) U.deepStrictEqual(pipe(_.right('foo'), _.chainFirst(f))(), E.right('foo')) U.deepStrictEqual(pipe(_.right('a'), _.chainFirst(f))(), E.left('foo')) }) it('chainFirstW', () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('foo')) U.deepStrictEqual(pipe(_.right('foo'), _.chainFirstW(f))(), E.right('foo')) U.deepStrictEqual(pipe(_.right('a'), _.chainFirstW(f))(), E.left('foo')) }) it('flatten', () => { U.deepStrictEqual(pipe(_.right(_.right('a')), _.flatten)(), E.right('a')) }) it('flattenW', () => { U.deepStrictEqual(pipe(_.right<'left1', _.IOEither<'left2', 'a'>>(_.right('a')), _.flattenW)(), E.right('a')) }) it('bimap', () => { const f = (s: string): number => s.length const g = (n: number): boolean => n > 2 U.deepStrictEqual(pipe(_.right(1), _.bimap(f, g))(), E.right(false)) U.deepStrictEqual(pipe(_.left('foo'), _.bimap(f, g))(), E.left(3)) }) it('mapLeft', () => { U.deepStrictEqual(pipe(_.left(1), _.mapLeft(U.double))(), E.left(2)) }) it('filterOrElse', () => { const isNumber = (u: string | number): u is number => typeof u === 'number' U.deepStrictEqual( pipe( _.right(12), _.filterOrElse( (n) => n > 10, () => 'bar' ) )(), E.right(12) ) U.deepStrictEqual( pipe( _.right(7), _.filterOrElse( (n) => n > 10, () => 'bar' ) )(), E.left('bar') ) U.deepStrictEqual( pipe( _.left('foo'), _.filterOrElse( (n) => n > 10, () => 'bar' ) )(), E.left('foo') ) U.deepStrictEqual( pipe( _.right(7), _.filterOrElse( (n) => n > 10, (n) => `invalid ${n}` ) )(), E.left('invalid 7') ) U.deepStrictEqual( pipe( _.right(12), _.filterOrElse(isNumber, () => 'not a number') )(), E.right(12) ) }) it('fromOption', () => { U.deepStrictEqual(_.fromOption(() => 'a')(O.none)(), E.left('a')) U.deepStrictEqual(_.fromOption(() => 'a')(O.some(1))(), E.right(1)) }) it('fromOptionK', () => { const f = _.fromOptionK(() => 'a')((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(1)(), E.right(1)) U.deepStrictEqual(f(-1)(), E.left('a')) }) it('flatMapOption', () => { const f = _.flatMapOption( (n: number) => (n > 0 ? O.some(n) : O.none), () => 'a' ) U.deepStrictEqual(f(_.right(1))(), E.right(1)) U.deepStrictEqual(f(_.right(-1))(), E.left('a')) U.deepStrictEqual(f(_.left('b'))(), E.left('b')) }) it('chainOptionK', () => { const f = _.chainOptionK(() => 'a')((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(_.right(1))(), E.right(1)) U.deepStrictEqual(f(_.right(-1))(), E.left('a')) U.deepStrictEqual(f(_.left('b'))(), E.left('b')) }) it('flatMapEither', () => { const f = _.flatMapEither((n: number) => (n > 0 ? E.right(n) : E.left('a'))) U.deepStrictEqual(f(_.right(1))(), E.right(1)) U.deepStrictEqual(f(_.right(-1))(), E.left('a')) U.deepStrictEqual(f(_.left('b'))(), E.left('b')) }) it('chainEitherK', () => { const f = _.chainEitherK((n: number) => (n > 0 ? E.right(n) : E.left('a'))) U.deepStrictEqual(f(_.right(1))(), E.right(1)) U.deepStrictEqual(f(_.right(-1))(), E.left('a')) U.deepStrictEqual(f(_.left('b'))(), E.left('b')) }) it('fromEither', () => { U.deepStrictEqual(_.fromEither(E.right('a'))(), E.right('a')) U.deepStrictEqual(_.fromEither(E.left('a'))(), E.left('a')) }) it('fromPredicate', () => { const gt2 = _.fromPredicate( (n: number) => n >= 2, (n) => `Invalid number ${n}` ) U.deepStrictEqual(gt2(3)(), E.right(3)) U.deepStrictEqual(gt2(1)(), E.left('Invalid number 1')) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const from = _.fromPredicate(isNumber, () => 'not a number') U.deepStrictEqual(from(4)(), E.right(4)) }) }) it('fold', () => { U.deepStrictEqual( _.fold( () => I.of('left'), () => I.of('right') )(_.right(1))(), 'right' ) U.deepStrictEqual( _.fold( () => I.of('left'), () => I.of('right') )(_.left('a'))(), 'left' ) }) it('getOrElse', () => { U.deepStrictEqual(_.getOrElse(() => I.of(2))(_.right(1))(), 1) U.deepStrictEqual(_.getOrElse(() => I.of(2))(_.left(1))(), 2) }) it('orElse', () => { U.deepStrictEqual(_.orElse(() => _.right(2))(_.right(1))(), E.right(1)) }) it('orElseW', () => { U.deepStrictEqual(_.orElseW(() => _.right(2))(_.right(1))(), E.right(1)) }) it('tapError', () => { const f = (e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!')) U.deepStrictEqual(pipe(_.right(1), _.tapError(f))(), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), _.tapError(f))(), E.left('a')) U.deepStrictEqual(pipe(_.left('aa'), _.tapError(f))(), E.left('aa!')) U.deepStrictEqual(_.tapError(_.right(1), f)(), E.right(1)) U.deepStrictEqual(_.tapError(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(_.tapError(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirst', () => { const f = _.orElseFirst((e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!'))) U.deepStrictEqual(pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(pipe(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirstW', () => { const f = _.orElseFirstW((e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!'))) U.deepStrictEqual(pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(pipe(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirstIOK', () => { const f = _.orElseFirstIOK((e: string) => I.of(e.length)) U.deepStrictEqual(pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)(), E.left('a')) }) it('orLeft', () => { const f = _.orLeft((e: string) => I.of(e + '!')) U.deepStrictEqual(pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)(), E.left('a!')) }) it('tryCatch', () => { U.deepStrictEqual(_.tryCatch(() => 1, E.toError)(), E.right(1)) U.deepStrictEqual( _.tryCatch(() => { throw new Error('error') }, E.toError)(), E.left(new Error('error')) ) }) describe('getSemigroup', () => { it('concat', () => { const S = _.getSemigroup(N.SemigroupSum) U.deepStrictEqual(S.concat(_.leftIO(I.of('a')), _.leftIO(I.of('b')))(), E.left('a')) U.deepStrictEqual(S.concat(_.leftIO(I.of('a')), _.rightIO(I.of(2)))(), E.right(2)) U.deepStrictEqual(S.concat(_.rightIO(I.of(1)), _.leftIO(I.of('b')))(), E.right(1)) U.deepStrictEqual(S.concat(_.rightIO(I.of(1)), _.rightIO(I.of(2)))(), E.right(3)) }) }) describe('getApplyMonoid', () => { it('concat', () => { const M = _.getApplyMonoid(S.Monoid) U.deepStrictEqual(M.concat(_.rightIO(I.of('a')), _.rightIO(I.of('b')))(), E.right('ab')) U.deepStrictEqual(M.concat(_.rightIO(I.of('a')), _.leftIO(I.of('b')))(), E.left('b')) U.deepStrictEqual(M.concat(_.rightIO(I.of('a')), M.empty)(), E.right('a')) U.deepStrictEqual(M.concat(M.empty, _.rightIO(I.of('a')))(), E.right('a')) }) }) describe('bracket', () => { let log: Array = [] const acquireFailure = _.left('acquire failure') const acquireSuccess = _.right({ res: 'acquire success' }) const useSuccess = () => _.right('use success') const useFailure = () => _.left('use failure') const releaseSuccess = () => _.rightIO(() => { log.push('release success') }) const releaseFailure = () => _.left('release failure') beforeEach(() => { log = [] }) it('should return the acquire error if acquire fails', () => { const e = _.bracket(acquireFailure, useSuccess, releaseSuccess)() U.deepStrictEqual(e, E.left('acquire failure')) }) it('body and release must not be called if acquire fails', () => { _.bracket(acquireFailure, useSuccess, releaseSuccess)() U.deepStrictEqual(log, []) }) it('should return the use error if use fails and release does not', () => { const e = _.bracket(acquireSuccess, useFailure, releaseSuccess)() U.deepStrictEqual(e, E.left('use failure')) }) it('should return the release error if both use and release fail', () => { const e = _.bracket(acquireSuccess, useFailure, releaseFailure)() U.deepStrictEqual(e, E.left('release failure')) }) it('release must be called if the body returns', () => { _.bracket(acquireSuccess, useSuccess, releaseSuccess)() U.deepStrictEqual(log, ['release success']) }) it('release must be called if the body throws', () => { _.bracket(acquireSuccess, useFailure, releaseSuccess)() U.deepStrictEqual(log, ['release success']) }) it('should return the release error if release fails', () => { const e = _.bracket(acquireSuccess, useSuccess, releaseFailure)() U.deepStrictEqual(e, E.left('release failure')) }) }) it('bracketW', async () => { const res = _.bracketW( _.right('string'), (_a: string) => _.right('test'), (_a: string, _e: E.Either) => _.right(constVoid()) )() U.deepStrictEqual(res, E.right('test')) }) it('getApplicativeIOValidation', () => { const A = _.getApplicativeIOValidation(S.Monoid) U.deepStrictEqual(sequenceT(A)(_.left('a'), _.left('b'))(), E.left('ab')) U.deepStrictEqual(sequenceT(A)(_.left('a'), _.right(1))(), E.left('a')) const AV = _.getIOValidation(S.Monoid) U.deepStrictEqual(sequenceT(AV)(_.left('a'), _.left('b'))(), E.left('ab')) }) it('getAltIOValidation', () => { const A = _.getAltIOValidation(S.Monoid) U.deepStrictEqual(A.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) const AV = _.getIOValidation(S.Monoid) U.deepStrictEqual(AV.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) }) describe('getCompactable', () => { const C = _.getCompactable(S.Monoid) it('compact', () => { U.deepStrictEqual(C.compact(_.right(O.some(1)))(), E.right(1)) }) it('separate', () => { const s1 = C.separate(_.left('a')) U.deepStrictEqual(left(s1)(), E.left('a')) U.deepStrictEqual(right(s1)(), E.left('a')) const s2 = C.separate(_.right(E.left('a'))) U.deepStrictEqual(left(s2)(), E.right('a')) U.deepStrictEqual(right(s2)(), E.left('')) const s3 = C.separate(_.right(E.right(1))) U.deepStrictEqual(left(s3)(), E.left('')) U.deepStrictEqual(right(s3)(), E.right(1)) }) }) describe('getFilterable', () => { const F_ = _.getFilterable(RA.getMonoid()) const { filter, filterMap, partition, partitionMap } = pipeable(F_) it('filter', async () => { const r1 = pipe( _.right(1), filter((n) => n > 0) ) U.deepStrictEqual(r1(), _.right(1)()) const r2 = pipe( _.right(-1), filter((n) => n > 0) ) U.deepStrictEqual(r2(), _.left([])()) const r3 = pipe( _.left(['a']), filter((n) => n > 0) ) U.deepStrictEqual(r3(), _.left(['a'])()) }) it('filterMap', () => { U.deepStrictEqual( pipe( _.right('aaa'), filterMap((s) => (s.length > 1 ? O.some(s.length) : O.none)) )(), E.right(3) ) U.deepStrictEqual( pipe( _.right('a'), filterMap((s) => (s.length > 1 ? O.some(s.length) : O.none)) )(), E.left([]) ) U.deepStrictEqual( pipe( _.left, string>(['e']), filterMap((s) => (s.length > 1 ? O.some(s.length) : O.none)) )(), E.left(['e']) ) }) it('partition', () => { const s = pipe( _.right('a'), partition((s) => s.length > 2) ) U.deepStrictEqual(left(s)(), E.right('a')) U.deepStrictEqual(right(s)(), E.left([])) }) it('partitionMap', () => { const s = pipe( _.right('a'), partitionMap((s) => (s.length > 2 ? E.right(s.length) : E.left(false))) ) U.deepStrictEqual(left(s)(), E.right(false)) U.deepStrictEqual(right(s)(), E.left([])) }) }) it('do notation', () => { U.deepStrictEqual( pipe( _.right(1), _.bindTo('a'), _.bind('b', () => _.right('b')), _.let('c', ({ a, b }) => [a, b]) )(), E.right({ a: 1, b: 'b', c: [1, 'b'] }) ) }) it('apS', () => { U.deepStrictEqual( pipe(_.right(1), _.bindTo('a'), _.apS('b', _.right('b')))(), E.right({ a: 1, b: 'b' }) ) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(pipe(RA.empty, f)(), E.right(RA.empty)) U.deepStrictEqual(pipe(input, f)(), E.right(['a0', 'b1'])) U.deepStrictEqual(pipe(['a', ''], f)(), E.left('e')) }) it('sequenceReadonlyArray', () => { U.deepStrictEqual(pipe(RA.empty, _.traverseReadonlyArrayWithIndex(SK))(), E.right(RA.empty)) const log: Array = [] const right = (n: number): _.IOEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.IOEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndex(SK))(), E.right([1, 2])) U.deepStrictEqual(pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndex(SK))(), E.left('a')) U.deepStrictEqual(pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndex(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceReadonlyArraySeq', () => { U.deepStrictEqual(pipe(RA.empty, _.traverseReadonlyArrayWithIndexSeq(SK))(), E.right(RA.empty)) const log: Array = [] const right = (n: number): _.IOEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.IOEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.right([1, 2])) U.deepStrictEqual(pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.left('a')) U.deepStrictEqual(pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) // old it('sequenceArray', () => { const log: Array = [] const right = (n: number): _.IOEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.IOEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(pipe([right(1), right(2)], _.sequenceArray)(), E.right([1, 2])) U.deepStrictEqual(pipe([right(3), left('a')], _.sequenceArray)(), E.left('a')) U.deepStrictEqual(pipe([left('b'), right(4)], _.sequenceArray)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceSeqArray', () => { const log: Array = [] const right = (n: number): _.IOEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.IOEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(pipe([right(1), right(2)], _.sequenceSeqArray)(), E.right([1, 2])) U.deepStrictEqual(pipe([right(3), left('a')], _.sequenceSeqArray)(), E.left('a')) U.deepStrictEqual(pipe([left('b'), right(4)], _.sequenceSeqArray)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) }) it('tryCatchK', () => { const f = (n: number) => { if (n > 0) { return n * 2 } throw new Error('negative') } const g = _.tryCatchK(f, identity) U.deepStrictEqual(g(1)(), E.right(2)) U.deepStrictEqual(g(-1)(), E.left(new Error('negative'))) }) it('toUnion', () => { U.deepStrictEqual(_.toUnion(_.right(1))(), 1) U.deepStrictEqual(_.toUnion(_.left('a'))(), 'a') }) // ------------------------------------------------------------------------------------- // destructors // ------------------------------------------------------------------------------------- it('match', () => { const f = _.match( () => 'left', () => 'right' ) U.deepStrictEqual(f(_.right(1))(), 'right') U.deepStrictEqual(f(_.left(1))(), 'left') }) it('matchE', () => { const f = _.matchE( () => I.of('left'), () => I.of('right') ) U.deepStrictEqual(f(_.right(1))(), 'right') U.deepStrictEqual(f(_.left(1))(), 'left') }) it('tapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(pipe(_.right('a'), _.tapEither(f))(), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(pipe(_.right('a'), _.tapEither(g))(), E.left(1)) }) it('chainFirstEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(pipe(_.right('a'), _.chainFirstEitherK(f))(), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(pipe(_.right('a'), _.chainFirstEitherK(g))(), E.left(1)) }) it('tapIO', () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(pipe(_.of(1), _.tapIO(add))(), E.of(1)) U.deepStrictEqual(pipe(_.left('error'), _.tapIO(add))(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('as', () => { U.deepStrictEqual(pipe(_.right('a'), _.as('b'))(), E.right('b')) U.deepStrictEqual(_.as(_.of('a'), 'b')(), E.right('b')) U.deepStrictEqual(_.as(_.left('error'), 'b')(), E.left('error')) }) it('asUnit', () => { U.deepStrictEqual(pipe(_.of('a'), _.asUnit)(), E.of(undefined)) }) it('flatMapIO', () => { U.deepStrictEqual( pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(), E.of(2) ) }) }) ================================================ FILE: test/IOOption.ts ================================================ import * as E from '../src/Either' import { pipe, SK } from '../src/function' import * as I from '../src/IO' import * as IE from '../src/IOEither' import * as _ from '../src/IOOption' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import * as U from './util' describe('IOOption', () => { // ------------------------------------------------------------------------------------- // type class members // ------------------------------------------------------------------------------------- it('map', () => { U.deepStrictEqual(pipe(_.some(1), _.map(U.double))(), O.some(2)) }) it('ap', () => { U.deepStrictEqual(pipe(_.some(U.double), _.ap(_.some(2)))(), O.some(4)) U.deepStrictEqual(pipe(_.some(U.double), _.ap(_.none))(), O.none) U.deepStrictEqual(pipe(_.none, _.ap(_.some(2)))(), O.none) U.deepStrictEqual(pipe(_.none, _.ap(_.none))(), O.none) }) it('flatMap', () => { const f = (n: number) => _.some(n * 2) const g = () => _.none U.deepStrictEqual(pipe(_.some(1), _.flatMap(f))(), O.some(2)) U.deepStrictEqual(pipe(_.none, _.flatMap(f))(), O.none) U.deepStrictEqual(pipe(_.some(1), _.flatMap(g))(), O.none) U.deepStrictEqual(pipe(_.none, _.flatMap(g))(), O.none) U.deepStrictEqual(_.flatMap(_.some(1), f)(), O.some(2)) U.deepStrictEqual(_.flatMap(_.none, f)(), O.none) U.deepStrictEqual(_.flatMap(_.some(1), g)(), O.none) U.deepStrictEqual(_.flatMap(_.none, g)(), O.none) }) it('chain', () => { const f = (n: number) => _.some(n * 2) const g = () => _.none U.deepStrictEqual(pipe(_.some(1), _.chain(f))(), O.some(2)) U.deepStrictEqual(pipe(_.none, _.chain(f))(), O.none) U.deepStrictEqual(pipe(_.some(1), _.chain(g))(), O.none) U.deepStrictEqual(pipe(_.none, _.chain(g))(), O.none) }) it('alt', () => { U.deepStrictEqual( pipe( _.some(1), _.alt(() => _.some(2)) )(), O.some(1) ) U.deepStrictEqual( pipe( _.some(2), _.alt(() => _.none as _.IOOption) )(), O.some(2) ) U.deepStrictEqual( pipe( _.none, _.alt(() => _.some(1)) )(), O.some(1) ) U.deepStrictEqual( pipe( _.none, _.alt(() => _.none) )(), O.none ) }) it('zero', () => { U.deepStrictEqual(_.zero()(), O.none) }) it('fromIO', () => { U.deepStrictEqual(_.fromIO(() => 1)(), O.some(1)) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('fromNullable', () => { U.deepStrictEqual(_.fromNullable(1)(), O.some(1)) U.deepStrictEqual(_.fromNullable(null)(), O.none) U.deepStrictEqual(_.fromNullable(undefined)(), O.none) }) it('fromNullableK', () => { const f = _.fromNullableK((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(f(1)(), O.some(1)) U.deepStrictEqual(f(0)(), O.none) U.deepStrictEqual(f(-1)(), O.none) }) it('chainNullableK', () => { const f = _.chainNullableK((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(f(_.of(1))(), O.some(1)) U.deepStrictEqual(f(_.of(0))(), O.none) U.deepStrictEqual(f(_.of(-1))(), O.none) }) it('fromPredicate', () => { const p = (n: number): boolean => n > 2 const f = _.fromPredicate(p) U.deepStrictEqual(f(1)(), O.none) U.deepStrictEqual(f(3)(), O.some(3)) }) it('fromIOEither', () => { const pl = IE.left('a') const pr = IE.right('a') const fl = _.fromIOEither(pl) const fr = _.fromIOEither(pr) U.deepStrictEqual(fl(), O.none) U.deepStrictEqual(fr(), O.some('a')) }) // ------------------------------------------------------------------------------------- // destructors // ------------------------------------------------------------------------------------- it('getOrElse', () => { U.deepStrictEqual( pipe( _.some(1), _.getOrElse(() => I.of(2)) )(), 1 ) U.deepStrictEqual( pipe( _.none, _.getOrElse(() => I.of(2)) )(), 2 ) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('fromOptionK', () => { const f = _.fromOptionK((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(1)(), O.some(1)) U.deepStrictEqual(f(-1)(), O.none) }) it('chainOptionK', () => { const f = _.chainOptionK((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(_.some(1))(), O.some(1)) U.deepStrictEqual(f(_.some(-1))(), O.none) U.deepStrictEqual(f(_.none)(), O.none) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none)) U.deepStrictEqual(pipe(RA.empty, f)(), O.some(RA.empty)) U.deepStrictEqual(pipe(input, f)(), O.some(['a0', 'b1'])) U.deepStrictEqual(pipe(['a', ''], f)(), O.none) }) it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none)) U.deepStrictEqual(pipe(RA.empty, f)(), O.some(RA.empty)) U.deepStrictEqual(pipe(input, f)(), O.some(['a0', 'b1'])) U.deepStrictEqual(pipe(['a', ''], f)(), O.none) }) it('sequenceReadonlyArray', () => { const log: Array = [] const some = (n: number): _.IOOption => _.fromIO(() => { log.push(n) return n }) const none = (s: string): _.IOOption => pipe( () => { log.push(s) return s }, I.map(() => O.none) ) U.deepStrictEqual(pipe([some(1), some(2)], _.traverseReadonlyArrayWithIndex(SK))(), O.some([1, 2])) U.deepStrictEqual(pipe([some(3), none('a')], _.traverseReadonlyArrayWithIndex(SK))(), O.none) U.deepStrictEqual(pipe([none('b'), some(4)], _.traverseReadonlyArrayWithIndex(SK))(), O.none) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) }) it('match', () => { const f = _.match( () => 'none', (a) => `some(${a})` ) U.deepStrictEqual(pipe(_.some(1), f)(), 'some(1)') U.deepStrictEqual(pipe(_.none, f)(), 'none') }) it('matchE', () => { const f = _.matchE( () => I.of('none'), (a) => I.of(`some(${a})`) ) U.deepStrictEqual(pipe(_.some(1), f)(), 'some(1)') U.deepStrictEqual(pipe(_.none, f)(), 'none') }) it('fromEitherK', () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.fromEitherK(f) U.deepStrictEqual(g('')(), O.some('!')) U.deepStrictEqual(g('a')(), O.some('a!')) U.deepStrictEqual(g('aa')(), O.some('aa!')) U.deepStrictEqual(g('aaa')(), O.none) }) it('chainEitherK', () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.chainEitherK(f) U.deepStrictEqual(g(_.of(''))(), O.some('!')) U.deepStrictEqual(g(_.of('a'))(), O.some('a!')) U.deepStrictEqual(g(_.of('aa'))(), O.some('aa!')) U.deepStrictEqual(g(_.of('aaa'))(), O.none) }) it('tapEither', () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.tapEither(f) U.deepStrictEqual(g(_.of(''))(), O.some('')) U.deepStrictEqual(g(_.of('a'))(), O.some('a')) U.deepStrictEqual(g(_.of('aa'))(), O.some('aa')) U.deepStrictEqual(g(_.of('aaa'))(), O.none) }) it('chainFirstEitherK', () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.chainFirstEitherK(f) U.deepStrictEqual(g(_.of(''))(), O.some('')) U.deepStrictEqual(g(_.of('a'))(), O.some('a')) U.deepStrictEqual(g(_.of('aa'))(), O.some('aa')) U.deepStrictEqual(g(_.of('aaa'))(), O.none) }) it('tapIO', () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(pipe(_.of(1), _.tapIO(add))(), O.of(1)) U.deepStrictEqual(pipe(_.none, _.tapIO(add))(), O.none) U.deepStrictEqual(ref, [1]) }) it('as', () => { U.deepStrictEqual(pipe(_.some('a'), _.as('b'))(), O.some('b')) U.deepStrictEqual(_.as(_.of('a'), 'b')(), O.some('b')) U.deepStrictEqual(_.as(_.none, 'b')(), O.none) }) it('asUnit', () => { U.deepStrictEqual(pipe(_.some('a'), _.asUnit)(), O.some(undefined)) }) it('flatMapIO', () => { U.deepStrictEqual( pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(), O.of(2) ) }) it('flatMapOption', () => { const f = _.flatMapOption((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(f(_.some(1))(), O.some(1)) U.deepStrictEqual(f(_.some(-1))(), O.none) U.deepStrictEqual(f(_.none)(), O.none) }) it('flatMapNullable', () => { const f = _.flatMapNullable((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(f(_.of(1))(), O.some(1)) U.deepStrictEqual(f(_.of(0))(), O.none) U.deepStrictEqual(f(_.of(-1))(), O.none) }) it('flatMapEither', () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.flatMapEither(f) U.deepStrictEqual(g(_.of(''))(), O.some('!')) U.deepStrictEqual(g(_.of('a'))(), O.some('a!')) U.deepStrictEqual(g(_.of('aa'))(), O.some('aa!')) U.deepStrictEqual(g(_.of('aaa'))(), O.none) }) }) ================================================ FILE: test/IORef.ts ================================================ import { pipe } from '../src/function' import * as I from '../src/IO' import { IORef, newIORef } from '../src/IORef' import * as U from './util' describe('IORef', () => { it('read', () => { const ref = new IORef(1) U.deepStrictEqual(ref.read(), 1) }) it('write', () => { const ref = new IORef(1) U.deepStrictEqual( pipe( ref.write(2), I.chain(() => ref.read) )(), 2 ) }) it('modify', () => { const ref = new IORef(1) U.deepStrictEqual( pipe( ref.modify(U.double), I.chain(() => ref.read) )(), 2 ) }) it('newIORef', () => { U.deepStrictEqual( pipe( newIORef(1), I.chain((ref) => ref.read) )(), 1 ) }) it('pipe', () => { const ref = new IORef(1) pipe(2, ref.write)() U.deepStrictEqual(ref.read(), 2) pipe(() => 3, ref.modify)() U.deepStrictEqual(ref.read(), 3) }) }) ================================================ FILE: test/Identity.ts ================================================ import { left, right } from '../src/Either' import { identity, pipe } from '../src/function' import * as _ from '../src/Identity' import * as N from '../src/number' import * as O from '../src/Option' import * as S from '../src/string' import * as U from './util' describe('Identity', () => { describe('pipeables', () => { it('map', () => { U.deepStrictEqual(pipe(1, _.map(U.double)), 2) }) it('ap', () => { const fab = U.double U.deepStrictEqual(pipe(fab, _.ap(1)), 2) }) it('apFirst', () => { U.deepStrictEqual(pipe('a', _.apFirst('b')), 'a') }) it('apSecond', () => { U.deepStrictEqual(pipe('a', _.apSecond('b')), 'b') }) it('flatMap', () => { const f = (n: number) => n * 2 U.deepStrictEqual(pipe(1, _.flatMap(f)), 2) U.deepStrictEqual(_.flatMap(1, f), 2) }) it('chain', () => { const f = (n: number) => n * 2 U.deepStrictEqual(pipe(1, _.chain(f)), 2) }) it('tap', () => { const f = (n: number) => n * 2 U.deepStrictEqual(pipe(1, _.tap(f)), 1) }) it('chainFirst', () => { const f = (n: number) => n * 2 U.deepStrictEqual(pipe(1, _.chainFirst(f)), 1) }) it('reduce', () => { U.deepStrictEqual( pipe( 'b', _.reduce('a', (b, a) => b + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe('a', _.foldMap(S.Monoid)(identity)), 'a') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe('a', _.reduceRight('', f)), 'a') }) it('alt', () => { U.deepStrictEqual( pipe( 1, _.alt(() => 2) ), 1 ) }) it('extract', () => { U.deepStrictEqual(pipe(1, _.extract), 1) }) it('extend', () => { const f = (fa: _.Identity): number => fa.length U.deepStrictEqual(pipe('foo', _.extend(f)), 3) }) it('duplicate', () => { U.deepStrictEqual(pipe('a', _.duplicate), 'a') }) it('flatten', () => { U.deepStrictEqual(pipe('a', _.flatten), 'a') }) it('traverse', () => { const traverse = _.traverse(O.Applicative) U.deepStrictEqual(pipe(1, traverse(O.some)), O.some(1)) U.deepStrictEqual( pipe( 1, traverse(() => O.none) ), O.none ) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence(O.some('a')), O.some('a')) U.deepStrictEqual(sequence(O.none), O.none) }) }) it('getEq', () => { const S = _.getEq(N.Eq) U.deepStrictEqual(S.equals(1, 1), true) U.deepStrictEqual(S.equals(1, 2), false) U.deepStrictEqual(S.equals(2, 1), false) }) it('ChainRec', () => { const x = _.ChainRec.chainRec(0, (a) => (a < 10 ? left(a + 1) : right(a))) const expected = 10 U.deepStrictEqual(x, expected) }) it('getShow', () => { const Sh = _.getShow(S.Show) U.deepStrictEqual(Sh.show('a'), `"a"`) }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) ), { a: 1, b: 'b', c: [1, 'b'] } ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b'))), { a: 1, b: 'b' }) }) }) ================================================ FILE: test/Json.ts ================================================ import * as E from '../src/Either' import { pipe } from '../src/function' import * as _ from '../src/Json' import * as U from './util' describe('Json', () => { it('parse', () => { U.deepStrictEqual(pipe('{"a":1}', _.parse), E.right({ a: 1 })) U.deepStrictEqual( pipe('{"a":}', _.parse), E.left(new SyntaxError(`Unexpected token '}', "{"a":}" is not valid JSON`)) ) }) it('stringify', () => { U.deepStrictEqual(pipe({ a: 1 }, _.stringify), E.right('{"a":1}')) const circular: any = { ref: null } circular.ref = circular U.deepStrictEqual( pipe( circular, _.stringify, E.mapLeft((e) => (e as Error).message.includes('Converting circular structure to JSON')) ), E.left(true) ) type Person = { readonly name: string readonly age: number } const person: Person = { name: 'Giulio', age: 45 } U.deepStrictEqual(pipe(person, _.stringify), E.right('{"name":"Giulio","age":45}')) U.deepStrictEqual(_.stringify(undefined as any), E.left(new Error('Converting unsupported structure to JSON'))) }) }) ================================================ FILE: test/Magma.ts ================================================ import { increment, pipe } from '../src/function' import * as _ from '../src/Magma' import * as N from '../src/number' import * as U from './util' describe('Magma', () => { it('reverse', () => { const subAll = _.concatAll(_.reverse(N.MagmaSub))(0) U.deepStrictEqual(subAll([1, 2, 3]), 2) }) it('filterFirst', () => { const M = pipe( N.SemigroupSum, _.filterFirst((n) => n >= 0) ) // sum ignoring negative partials const sum = _.concatAll(M)(0) U.deepStrictEqual(sum([1, -2, 3]), 3) }) it('filterSecond', () => { const M = pipe( N.SemigroupSum, _.filterSecond((n) => n >= 0) ) // sum ignoring negative elements const sum = _.concatAll(M)(0) U.deepStrictEqual(sum([1, -2, 3]), 4) }) it('endo', () => { const M = pipe(N.SemigroupSum, _.endo(increment)) const sum = _.concatAll(M)(0) U.deepStrictEqual(sum([1, -2, 3]), 8) }) it('concatAll', () => { const subAll = _.concatAll(N.MagmaSub)(0) U.deepStrictEqual(subAll([1, 2, 3]), -6) }) }) ================================================ FILE: test/Map.ts ================================================ import * as assert from 'assert' import { Either, left, right } from '../src/Either' import { Eq, fromEquals } from '../src/Eq' import { identity, pipe } from '../src/function' import * as _ from '../src/Map' import * as N from '../src/number' import * as O from '../src/Option' import * as Ord from '../src/Ord' import * as RA from '../src/ReadonlyArray' import { Refinement } from '../src/Refinement' import * as Se from '../src/Semigroup' import { separated } from '../src/Separated' import { Show, struct } from '../src/Show' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' interface User { readonly id: string } const ordUser = pipe( S.Ord, Ord.contramap((u: User) => u.id) ) const eqUser: Eq = { equals: ordUser.equals } const p = ((n: number): boolean => n > 2) as Refinement interface Key { readonly id: number } interface Value { readonly value: number } const eqKey: Eq = fromEquals((x, y) => x.id % 3 === y.id % 3) const ordKey = Ord.fromCompare((x, y) => N.Ord.compare(x.id % 3, y.id % 3)) const eqValue: Eq = fromEquals((x, y) => x.value % 3 === y.value % 3) const semigroupValue = Se.struct({ value: N.SemigroupSum }) const key1 = { id: 1 } const value1 = { value: 1 } const repo = new Map([ [key1, value1], [{ id: 2 }, { value: 2 }] ]) describe('Map', () => { it('URI', () => { U.deepStrictEqual(_.URI, 'Map') }) it('size', () => { const emptyMap = new Map() const a1 = new Map([['a', 1]]) U.deepStrictEqual(_.size(emptyMap), 0) U.deepStrictEqual(_.size(a1), 1) U.deepStrictEqual(_.size(new Map()), 0) U.deepStrictEqual(_.size(new Map([['a', 1]])), 1) }) it('isEmpty', () => { const emptyMap = new Map() const a1 = new Map([['a', 1]]) U.deepStrictEqual(_.isEmpty(emptyMap), true) U.deepStrictEqual(_.isEmpty(a1), false) U.deepStrictEqual(_.isEmpty(new Map()), true) U.deepStrictEqual(_.isEmpty(new Map([['a', 1]])), false) }) it('member', () => { const x = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const memberS = _.member(eqUser) U.deepStrictEqual(memberS({ id: 'a' }, x), true) U.deepStrictEqual(memberS({ id: 'c' }, x), false) U.deepStrictEqual(memberS({ id: 'a' })(x), true) U.deepStrictEqual(memberS({ id: 'c' })(x), false) const member = _.member(eqKey) U.deepStrictEqual(member({ id: 1 }, repo), true) U.deepStrictEqual(member({ id: 2 }, repo), true) U.deepStrictEqual(member({ id: 4 }, repo), true) U.deepStrictEqual(member({ id: 3 }, repo), false) U.deepStrictEqual(member({ id: 1 })(repo), true) U.deepStrictEqual(member({ id: 2 })(repo), true) U.deepStrictEqual(member({ id: 4 })(repo), true) U.deepStrictEqual(member({ id: 3 })(repo), false) }) it('elem', () => { const x = new Map([ ['a', 1], ['b', 2] ]) const elemS = _.elem(N.Eq) U.deepStrictEqual(elemS(2, x), true) U.deepStrictEqual(elemS(3, x), false) U.deepStrictEqual(elemS(2)(x), true) U.deepStrictEqual(elemS(3)(x), false) const elem = _.elem(eqValue) U.deepStrictEqual(elem({ value: 1 })(repo), true) U.deepStrictEqual(elem({ value: 2 })(repo), true) U.deepStrictEqual(elem({ value: 4 })(repo), true) U.deepStrictEqual(elem({ value: 3 })(repo), false) U.deepStrictEqual(elem({ value: 1 })(repo), true) U.deepStrictEqual(elem({ value: 2 })(repo), true) U.deepStrictEqual(elem({ value: 4 })(repo), true) U.deepStrictEqual(elem({ value: 3 })(repo), false) }) it('keys', () => { const m = new Map([ [{ id: 'b' }, 2], [{ id: 'a' }, 1] ]) const ks = _.keys(ordUser)(m) U.deepStrictEqual(ks, Array.from(m.keys()).sort(ordUser.compare)) U.deepStrictEqual(ks, [{ id: 'a' }, { id: 'b' }]) U.deepStrictEqual( _.keys(S.Ord)( new Map([ ['a', 1], ['b', 2] ]) ), ['a', 'b'] ) U.deepStrictEqual( _.keys(S.Ord)( new Map([ ['b', 2], ['a', 1] ]) ), ['a', 'b'] ) }) it('values', () => { const m = new Map([ [2, { id: 'b' }], [1, { id: 'a' }] ]) const vals = _.values(ordUser)(m) U.deepStrictEqual(vals, Array.from(m.values()).sort(ordUser.compare)) U.deepStrictEqual(vals, [{ id: 'a' }, { id: 'b' }]) }) it('collect', () => { const m1 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const m2 = new Map([ [{ id: 'b' }, 2], [{ id: 'a' }, 1] ]) const collectO = _.collect(ordUser) const f = (_k: User, a: number): number => a + 1 U.deepStrictEqual(collectO(f)(m1), [2, 3]) U.deepStrictEqual(collectO(f)(m2), [2, 3]) const collect = _.collect(ordKey) const g = (k: Key, a: Value): readonly [number, number] => [k.id, a.value] U.deepStrictEqual( collect(g)( new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ), [ [1, 1], [2, 2] ] ) U.deepStrictEqual( collect(g)( new Map([ [{ id: 2 }, { value: 2 }], [{ id: 1 }, { value: 1 }] ]) ), [ [1, 1], [2, 2] ] ) U.deepStrictEqual( collect(g)( new Map([ [{ id: 4 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ), [ [4, 1], [2, 2] ] ) U.deepStrictEqual( collect(g)( new Map([ [{ id: 2 }, { value: 2 }], [{ id: 4 }, { value: 1 }] ]) ), [ [4, 1], [2, 2] ] ) }) it('toArray', () => { const m1 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const m2 = new Map([ [{ id: 'b' }, 2], [{ id: 'a' }, 1] ]) const toArrayO = _.toArray(ordUser) U.deepStrictEqual(toArrayO(m1), [ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) U.deepStrictEqual(toArrayO(m2), [ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const toArray = _.toArray(ordKey) U.deepStrictEqual( toArray( new Map([ [{ id: 1 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toArray( new Map([ [{ id: 2 }, 2], [{ id: 1 }, 1] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toArray( new Map([ [{ id: 4 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toArray( new Map([ [{ id: 2 }, 2], [{ id: 4 }, 1] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) }) it('toUnfoldable', () => { const a1 = new Map([[{ id: 'a' }, 1]]) const toUnfoldableO = _.toUnfoldable(ordUser, RA.Unfoldable) U.deepStrictEqual(toUnfoldableO(a1), [[{ id: 'a' }, 1]]) const toUnfoldable = _.toUnfoldable(ordKey, RA.Unfoldable) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 1 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 2 }, 2], [{ id: 1 }, 1] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 4 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 2 }, 2], [{ id: 4 }, 1] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) }) it('insertAt', () => { const emptyMap = new Map() const a1 = new Map([[{ id: 'a' }, 1]]) const a1b2 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const a2b2 = new Map([ [{ id: 'a' }, 2], [{ id: 'b' }, 2] ]) const a1b2c3 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2], [{ id: 'c' }, 3] ]) const insertS = _.insertAt(eqUser) U.deepStrictEqual(insertS({ id: 'a' }, 1)(emptyMap), a1) U.deepStrictEqual(insertS({ id: 'a' }, 1)(a1b2), a1b2) U.deepStrictEqual(insertS({ id: 'a' }, 2)(a1b2), a2b2) U.deepStrictEqual(insertS({ id: 'c' }, 3)(a1b2), a1b2c3) const insert = _.insertAt(eqKey) U.deepStrictEqual(insert({ id: 1 }, { value: 1 })(new Map()), new Map([[{ id: 1 }, { value: 1 }]])) const x = insert({ id: 1 }, value1)(repo) U.deepStrictEqual( x, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual(x.get(key1), value1) U.deepStrictEqual( insert({ id: 1 }, { value: 2 })(repo), new Map([ [{ id: 1 }, { value: 2 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual( insert({ id: 4 }, { value: 2 })(repo), new Map([ [{ id: 1 }, { value: 2 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual( insert({ id: 3 }, { value: 3 })(repo), new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }], [{ id: 3 }, { value: 3 }] ]) ) // should not modify the source U.deepStrictEqual( repo, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) }) it('deleteAt', () => { const a1b2 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const a1b2_ = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const b2 = new Map([[{ id: 'b' }, 2]]) const removeS = _.deleteAt(eqUser) U.deepStrictEqual(removeS({ id: 'a' })(a1b2), b2) U.deepStrictEqual(a1b2, a1b2_) U.deepStrictEqual(removeS({ id: 'c' })(a1b2), a1b2) const remove = _.deleteAt(eqKey) U.deepStrictEqual(remove({ id: 1 })(repo), new Map([[{ id: 2 }, { value: 2 }]])) U.deepStrictEqual(remove({ id: 4 })(repo), new Map([[{ id: 2 }, { value: 2 }]])) U.deepStrictEqual(remove({ id: 3 })(repo), repo) // should not modify the source U.deepStrictEqual( repo, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) }) it('pop', () => { const a1b2 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const b2 = new Map([[{ id: 'b' }, 2]]) const popS = _.pop(eqUser) U.deepStrictEqual(popS({ id: 'a' })(a1b2), O.some([1, b2])) U.deepStrictEqual(popS({ id: 'c' })(a1b2), O.none) const pop = _.pop(eqKey) U.deepStrictEqual(pop({ id: 1 })(repo), O.some([{ value: 1 }, new Map([[{ id: 2 }, { value: 2 }]])])) U.deepStrictEqual(pop({ id: 4 })(repo), O.some([{ value: 1 }, new Map([[{ id: 2 }, { value: 2 }]])])) U.deepStrictEqual(pop({ id: 3 })(repo), O.none) // should not modify the source U.deepStrictEqual( repo, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) }) it('lookupWithKey', () => { const x = new Map([[{ id: 'a' }, 1]]) const lookupWithKeyS = _.lookupWithKey(eqUser) U.deepStrictEqual(lookupWithKeyS({ id: 'a' }, x), O.some([{ id: 'a' }, 1])) U.deepStrictEqual(lookupWithKeyS({ id: 'b' }, x), O.none) U.deepStrictEqual(lookupWithKeyS({ id: 'a' })(x), O.some([{ id: 'a' }, 1])) U.deepStrictEqual(lookupWithKeyS({ id: 'b' })(x), O.none) const lookupWithKey = _.lookupWithKey(eqKey) assert.deepStrictEqual(lookupWithKey({ id: 1 }, repo), O.some([{ id: 1 }, { value: 1 }])) assert.deepStrictEqual(lookupWithKey({ id: 4 }, repo), O.some([{ id: 1 }, { value: 1 }])) U.deepStrictEqual(lookupWithKey({ id: 3 }, repo), O.none) assert.deepStrictEqual(lookupWithKey({ id: 1 })(repo), O.some([{ id: 1 }, { value: 1 }])) assert.deepStrictEqual(lookupWithKey({ id: 4 })(repo), O.some([{ id: 1 }, { value: 1 }])) U.deepStrictEqual(lookupWithKey({ id: 3 })(repo), O.none) }) it('lookup', () => { const x = new Map([[{ id: 'a' }, 1]]) const lookupS = _.lookup(eqUser) U.deepStrictEqual(lookupS({ id: 'a' }, x), O.some(1)) U.deepStrictEqual(lookupS({ id: 'b' }, x), O.none) U.deepStrictEqual(lookupS({ id: 'a' })(x), O.some(1)) U.deepStrictEqual(lookupS({ id: 'b' })(x), O.none) const lookup = _.lookup(eqKey) U.deepStrictEqual(lookup({ id: 1 }, repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 4 }, repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 3 }, repo), O.none) U.deepStrictEqual(lookup({ id: 1 })(repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 4 })(repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 3 })(repo), O.none) }) it('isSubmap', () => { const me = new Map([[{ id: 'a' }, 1]]) const that = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const isSubmapS = _.isSubmap(eqUser, N.Eq) U.deepStrictEqual(isSubmapS(me, that), true) U.deepStrictEqual(isSubmapS(that)(me), true) const isSubmap = _.isSubmap(eqKey, eqValue) U.deepStrictEqual(isSubmap(new Map([[{ id: 1 }, { value: 1 }]]), repo), true) U.deepStrictEqual(isSubmap(new Map([[{ id: 1 }, { value: 2 }]]), repo), false) U.deepStrictEqual(isSubmap(new Map([[{ id: 1 }, { value: 4 }]]), repo), true) U.deepStrictEqual(isSubmap(new Map([[{ id: 4 }, { value: 1 }]]), repo), true) U.deepStrictEqual(isSubmap(new Map([[{ id: 3 }, { value: 3 }]]), repo), false) U.deepStrictEqual(pipe(new Map([[{ id: 1 }, { value: 1 }]]), isSubmap(repo)), true) U.deepStrictEqual(pipe(new Map([[{ id: 1 }, { value: 2 }]]), isSubmap(repo)), false) U.deepStrictEqual(pipe(new Map([[{ id: 1 }, { value: 4 }]]), isSubmap(repo)), true) U.deepStrictEqual(pipe(new Map([[{ id: 4 }, { value: 1 }]]), isSubmap(repo)), true) U.deepStrictEqual(pipe(new Map([[{ id: 3 }, { value: 3 }]]), isSubmap(repo)), false) }) it('singleton', () => { U.deepStrictEqual(_.singleton('k1', 0), new Map([['k1', 0]])) }) it('getEq', () => { const a1 = new Map([[{ id: 'a' }, 1]]) const a1_ = new Map([[{ id: 'a' }, 1]]) const a2 = new Map([[{ id: 'a' }, 2]]) const b1 = new Map([[{ id: 'b' }, 1]]) const S = _.getEq(eqUser, N.Eq) U.deepStrictEqual(S.equals(a1, a1), true) U.deepStrictEqual(S.equals(a1, a1_), true) U.deepStrictEqual(S.equals(a1_, a1), true) U.deepStrictEqual(S.equals(a1, a2), false) U.deepStrictEqual(S.equals(a2, a1), false) U.deepStrictEqual(S.equals(a1, b1), false) U.deepStrictEqual(S.equals(b1, a1), false) const equals = _.getEq(eqKey, eqValue).equals U.deepStrictEqual(equals(repo, repo), true) U.deepStrictEqual( equals( new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]), repo ), true ) U.deepStrictEqual( equals( new Map([ [{ id: 1 }, { value: 2 }], [{ id: 2 }, { value: 2 }] ]), repo ), false ) U.deepStrictEqual( equals( new Map([ [{ id: 1 }, { value: 4 }], [{ id: 2 }, { value: 2 }] ]), repo ), true ) U.deepStrictEqual( equals( new Map([ [{ id: 4 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]), repo ), true ) U.deepStrictEqual( equals( new Map([ [{ id: 3 }, { value: 3 }], [{ id: 2 }, { value: 2 }] ]), repo ), false ) }) it('getMonoid', () => { const d1 = new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 3] ]) const d2 = new Map([ [{ id: 'k2' }, 2], [{ id: 'k3' }, 4] ]) const expected = new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 5], [{ id: 'k3' }, 4] ]) const M1 = _.getMonoid(eqUser, N.SemigroupSum) U.deepStrictEqual(M1.concat(d1, d2), expected) U.deepStrictEqual(M1.concat(d1, M1.empty), d1) U.deepStrictEqual(M1.concat(M1.empty, d2), d2) const M2 = _.getMonoid(eqKey, semigroupValue) U.deepStrictEqual( M2.concat(repo, new Map([[{ id: 3 }, { value: 3 }]])), new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }], [{ id: 3 }, { value: 3 }] ]) ) U.deepStrictEqual( M2.concat(repo, new Map([[{ id: 1 }, { value: 2 }]])), new Map([ [{ id: 1 }, { value: 3 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual( M2.concat(repo, new Map([[{ id: 4 }, { value: 2 }]])), new Map([ [{ id: 1 }, { value: 3 }], [{ id: 2 }, { value: 2 }] ]) ) }) describe('map_', () => { describe('functor', () => { it('map', () => { const d1 = new Map([ ['k1', 1], ['k2', 2] ]) const expected = new Map([ ['k1', 2], ['k2', 4] ]) U.deepStrictEqual(pipe(d1, _.map(U.double)), expected) }) }) describe('filterable', () => { it('compact', () => { const fooBar = new Map>([ ['foo', O.none], ['bar', O.some(123)] ]) const bar = new Map([['bar', 123]]) U.deepStrictEqual(_.compact(fooBar), bar) }) it('partitionMap', () => { const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const a0 = new Map([['a', 0]]) const b4 = new Map([['b', 4]]) const f = (n: number) => (p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(pipe(emptyMap, _.partitionMap(f)), separated(emptyMap, emptyMap)) U.deepStrictEqual(pipe(a1b3, _.partitionMap(f)), separated(a0, b4)) }) it('partition', () => { const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const a1 = new Map([['a', 1]]) const b3 = new Map([['b', 3]]) U.deepStrictEqual(pipe(emptyMap, _.partition(p)), separated(emptyMap, emptyMap)) U.deepStrictEqual(pipe(a1b3, _.partition(p)), separated(a1, b3)) }) it('separate', () => { const fooBar = new Map>([ ['foo', left(123)], ['bar', right(123)] ]) const foo = new Map([['foo', 123]]) const bar = new Map([['bar', 123]]) U.deepStrictEqual(_.separate(fooBar), separated(foo, bar)) }) it('filter', () => { const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const b3 = new Map([['b', 3]]) U.deepStrictEqual(pipe(a1b3, _.filter(p)), b3) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const y = new Map([ ['a', 1], ['b', 'foo'] ]) const a1 = new Map([['a', 1]]) const actual = pipe(y, _.filter(isNumber)) U.deepStrictEqual(actual, a1) }) it('filterMap', () => { const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const b4 = new Map([['b', 4]]) const f = (n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(pipe(emptyMap, _.filterMap(f)), emptyMap) U.deepStrictEqual(pipe(a1b3, _.filterMap(f)), b4) }) }) }) describe('getFoldable', () => { const F = _.getFoldable(ordUser) it('reduce', () => { const d1 = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) const reduceO = F.reduce U.deepStrictEqual( reduceO(d1, '', (b, a) => b + a), 'ab' ) const d2 = new Map([ [{ id: 'k2' }, 'b'], [{ id: 'k1' }, 'a'] ]) U.deepStrictEqual( reduceO(d2, '', (b, a) => b + a), 'ab' ) }) it('foldMap', () => { const foldMapOM = F.foldMap(S.Monoid) const m = new Map([ [{ id: 'a' }, 'a'], [{ id: 'a' }, 'b'] ]) U.deepStrictEqual(foldMapOM(m, identity), 'ab') }) it('reduceRight', () => { const reduceRightO = F.reduceRight const m = new Map([ [{ id: 'a' }, 'a'], [{ id: 'b' }, 'b'] ]) const init = '' const f = (a: string, acc: string) => acc + a U.deepStrictEqual(reduceRightO(m, init, f), 'ba') }) }) describe('getWitherable', () => { const W = _.getWitherable(ordUser) it('mapWithIndex', () => { const mapWithIndex = W.mapWithIndex const aa1 = new Map([[{ id: 'aa' }, 1]]) const aa3 = new Map([[{ id: 'aa' }, 3]]) U.deepStrictEqual( mapWithIndex(aa1, (k, a) => a + k.id.length), aa3 ) }) it('reduceWithIndex', () => { const d1 = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) const reduceWithIndexO = W.reduceWithIndex U.deepStrictEqual( reduceWithIndexO(d1, '', (k, b, a) => b + k.id + a), 'k1ak2b' ) const d2 = new Map([ [{ id: 'k2' }, 'b'], [{ id: 'k1' }, 'a'] ]) U.deepStrictEqual( reduceWithIndexO(d2, '', (k, b, a) => b + k.id + a), 'k1ak2b' ) }) it('foldMapWithIndex', () => { const foldMapWithIndexOM = W.foldMapWithIndex(S.Monoid) const m = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) U.deepStrictEqual( foldMapWithIndexOM(m, (k, a) => k.id + a), 'k1ak2b' ) }) it('reduceRightWithIndex', () => { const reduceRightWithIndexO = W.reduceRightWithIndex const m = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) U.deepStrictEqual( reduceRightWithIndexO(m, '', (k, a, b) => b + k.id + a), 'k2bk1a' ) }) it('traverse', () => { const traverse = W.traverse(O.Applicative) const x = new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 2] ]) U.deepStrictEqual( traverse(x, (n) => (n <= 2 ? O.some(n) : O.none)), O.some(x) ) U.deepStrictEqual( traverse(x, (n) => (n >= 2 ? O.some(n) : O.none)), O.none ) }) it('sequence', () => { const sequence = W.sequence(O.Applicative) U.deepStrictEqual( sequence( new Map([ [{ id: 'k1' }, O.some(1)], [{ id: 'k2' }, O.some(2)] ]) ), O.some( new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 2] ]) ) ) U.deepStrictEqual( sequence( new Map([ [{ id: 'k1' }, O.none], [{ id: 'k2' }, O.some(2)] ]) ), O.none ) }) it('traverseWithIndex', () => { const traverseWithIndex = W.traverseWithIndex(O.Applicative) U.deepStrictEqual( traverseWithIndex( new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 2] ]), (k, n): O.Option => (!ordUser.equals(k, { id: 'k1' }) ? O.some(n) : O.none) ), O.none ) U.deepStrictEqual( traverseWithIndex( new Map([ [{ id: 'k1' }, 2], [{ id: 'k2' }, 3] ]), (k, n): O.Option => (!ordUser.equals(k, { id: 'k3' }) ? O.some(n) : O.none) ), O.some( new Map([ [{ id: 'k1' }, 2], [{ id: 'k2' }, 3] ]) ) ) }) it('wither', async () => { const wither = W.wither(T.ApplicativePar) const f = (n: number) => T.of(p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(await wither(new Map(), f)(), new Map()) U.deepStrictEqual( await wither( new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 3] ]), f )(), new Map([[{ id: 'b' }, 4]]) ) }) it('wilt', async () => { const wilt = W.wilt(T.ApplicativePar) const f = (n: number) => T.of(p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(await wilt(new Map(), f)(), separated(new Map(), new Map())) U.deepStrictEqual( await wilt( new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 3] ]), f )(), separated(new Map([[{ id: 'a' }, 0]]), new Map([[{ id: 'b' }, 4]])) ) }) }) describe('getFilterableWithIndex', () => { it('partitionMapWithIndex', () => { const partitionMapWithIndex = _.getFilterableWithIndex().partitionMapWithIndex const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const a0 = new Map([['a', 0]]) const b4 = new Map([['b', 4]]) const f = (_: string, n: number) => (p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(partitionMapWithIndex(emptyMap, f), separated(emptyMap, emptyMap)) U.deepStrictEqual(partitionMapWithIndex(a1b3, f), separated(a0, b4)) }) it('partitionWithIndex', () => { const partitionWithIndex = _.getFilterableWithIndex().partitionWithIndex const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const a1 = new Map([['a', 1]]) const b3 = new Map([['b', 3]]) const f = (_: string, n: number) => p(n) U.deepStrictEqual(partitionWithIndex(emptyMap, f), separated(emptyMap, emptyMap)) U.deepStrictEqual(partitionWithIndex(a1b3, f), separated(a1, b3)) }) it('filterMapWithIndex', () => { const filterMapWithIndex = _.getFilterableWithIndex().filterMapWithIndex const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const b4 = new Map([['b', 4]]) const f = (_: string, n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(filterMapWithIndex(emptyMap, f), emptyMap) U.deepStrictEqual(filterMapWithIndex(a1b3, f), b4) }) it('filterWithIndex', () => { const filterWithIndex = _.getFilterableWithIndex().filterWithIndex const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const b3 = new Map([['b', 3]]) const f = (_: string, n: number) => p(n) U.deepStrictEqual(filterWithIndex(a1b3, f), b3) // refinements const filterWithIndexStr = _.getFilterableWithIndex().filterWithIndex const isNumber = (_: string, u: string | number): u is number => typeof u === 'number' const y = new Map([ ['a', 1], ['b', 'foo'] ]) const a1 = new Map([['a', 1]]) const actual = filterWithIndexStr(y, isNumber) U.deepStrictEqual(actual, a1) }) }) it('fromFoldable', () => { const a1 = new Map([[{ id: 'a' }, 1]]) const a2 = new Map([[{ id: 'a' }, 2]]) const fromFoldableS1 = _.fromFoldable(eqUser, Se.first(), RA.Foldable) U.deepStrictEqual(fromFoldableS1([[{ id: 'a' }, 1]]), a1) U.deepStrictEqual( fromFoldableS1([ [{ id: 'a' }, 1], [{ id: 'a' }, 2] ]), a1 ) const fromFoldableS2 = _.fromFoldable(eqUser, Se.last(), RA.Foldable) U.deepStrictEqual( fromFoldableS2([ [{ id: 'a' }, 1], [{ id: 'a' }, 2] ]), a2 ) }) it('getShow', () => { const showUser: Show = struct({ id: S.Show }) const Sh = _.getShow(showUser, S.Show) const m1 = new Map([]) U.deepStrictEqual(Sh.show(m1), `new Map([])`) const m2 = new Map([[{ id: 'a' }, 'b']]) U.deepStrictEqual(Sh.show(m2), `new Map([[{ id: "a" }, "b"]])`) const m3 = new Map([ [{ id: 'c' }, 'd'], [{ id: 'a' }, 'b'] ]) U.deepStrictEqual(Sh.show(m3), `new Map([[{ id: "a" }, "b"], [{ id: "c" }, "d"]])`) }) it('updateAt', () => { const m1 = new Map([]) U.deepStrictEqual(_.updateAt(eqUser)({ id: 'a' }, 'a')(m1), O.none) const m2 = new Map([[{ id: 'a' }, 'b']]) U.deepStrictEqual(_.updateAt(eqUser)({ id: 'a' }, 'a')(m2), O.some(new Map([[{ id: 'a' }, 'a']]))) }) it('modifyAt', () => { const m1 = new Map([]) U.deepStrictEqual(_.modifyAt(eqUser)({ id: 'a' }, (n: number) => n * 2)(m1), O.none) const m2 = new Map([[{ id: 'a' }, 1]]) U.deepStrictEqual( _.modifyAt(eqUser)({ id: 'a' }, (n: number) => n * 2)(m2), O.some(new Map([[{ id: 'a' }, 2]])) ) // should not return the same reference if nothing changed const input: Map = new Map([['a', 1]]) U.deepStrictEqual( pipe( input, _.modifyAt(S.Eq)('a', identity), O.map((out) => out === input) ), O.some(false) ) }) it('mapWithIndex', () => { const aa1 = new Map([[{ id: 'aa' }, 1]]) const aa3 = new Map([[{ id: 'aa' }, 3]]) U.deepStrictEqual( pipe( aa1, _.mapWithIndex((k, a) => a + k.id.length) ), aa3 ) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(eqUser, S.Semigroup) const x = new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1'], [{ id: 'c' }, 'c1'] ]) const y = new Map([ [{ id: 'b' }, 'b2'], [{ id: 'c' }, 'c2'], [{ id: 'd' }, 'd2'] ]) U.deepStrictEqual(M.concat(x, M.empty), x) U.deepStrictEqual(M.concat(M.empty, x), x) U.deepStrictEqual(M.concat(x, new Map()), x) U.deepStrictEqual(M.concat(new Map(), x), x) U.deepStrictEqual( M.concat(x, y), new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1b2'], [{ id: 'c' }, 'c1c2'], [{ id: 'd' }, 'd2'] ]) ) }) it('getIntersectionSemigroup', () => { const M = _.getIntersectionSemigroup(eqUser, S.Semigroup) const x = new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1'], [{ id: 'c' }, 'c1'] ]) const y = new Map([ [{ id: 'b' }, 'b2'], [{ id: 'c' }, 'c2'], [{ id: 'd' }, 'd2'] ]) U.deepStrictEqual(M.concat(x, new Map()), new Map()) U.deepStrictEqual(M.concat(new Map(), x), new Map()) U.deepStrictEqual( M.concat(x, y), new Map([ [{ id: 'b' }, 'b1b2'], [{ id: 'c' }, 'c1c2'] ]) ) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma(eqUser)() const x = new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1'], [{ id: 'c' }, 'c1'] ]) const y = new Map([ [{ id: 'b' }, 'b2'], [{ id: 'c' }, 'c2'], [{ id: 'd' }, 'd2'] ]) U.deepStrictEqual(M.concat(x, new Map()), x) U.deepStrictEqual(M.concat(new Map(), x), x) U.deepStrictEqual( M.concat(x, y), new Map([ [{ id: 'a' }, 'a1'], [{ id: 'd' }, 'd2'] ]) ) }) }) ================================================ FILE: test/Monoid.ts ================================================ import * as B from '../src/boolean' import { increment } from '../src/function' import * as _ from '../src/Monoid' import * as N from '../src/number' import * as S from '../src/string' import * as U from './util' describe('Monoid', () => { it('tuple', () => { const M1 = _.tuple(S.Monoid, N.MonoidSum) U.deepStrictEqual(M1.concat(['a', 1], ['b', 2]), ['ab', 3]) const M2 = _.tuple(S.Monoid, N.MonoidSum, B.MonoidAll) U.deepStrictEqual(M2.concat(['a', 1, true], ['b', 2, false]), ['ab', 3, false]) }) it('concatAll', () => { U.deepStrictEqual(_.concatAll(N.MonoidSum)([1, 2, 3]), 6) }) it('getEndomorphismMonoid', () => { const M = _.getEndomorphismMonoid() const f = M.concat(U.double, increment) U.deepStrictEqual(f(3), 8) }) it('min', () => { const M = _.min(N.Bounded) U.deepStrictEqual(_.concatAll(M)([]), +Infinity) U.deepStrictEqual(_.concatAll(M)([1]), 1) U.deepStrictEqual(_.concatAll(M)([1, -1]), -1) }) it('max', () => { const M = _.max(N.Bounded) U.deepStrictEqual(_.concatAll(M)([]), -Infinity) U.deepStrictEqual(_.concatAll(M)([1]), 1) U.deepStrictEqual(_.concatAll(M)([1, -1]), 1) }) it('reverse', () => { const M = _.reverse(S.Monoid) U.deepStrictEqual(M.concat('a', 'b'), 'ba') U.deepStrictEqual(M.concat('a', M.empty), 'a') U.deepStrictEqual(M.concat(M.empty, 'a'), 'a') }) it('struct', () => { // should ignore non own properties const monoids = Object.create({ a: 1 }) const s = _.struct(monoids) U.deepStrictEqual(s.empty, {}) }) }) ================================================ FILE: test/NonEmptyArray.ts ================================================ import * as assert from 'assert' import { Endomorphism } from '../src/Endomorphism' import { identity, pipe } from '../src/function' import * as _ from '../src/NonEmptyArray' import * as N from '../src/number' import * as O from '../src/Option' import * as S from '../src/string' import * as U from './util' describe('NonEmptyArray', () => { describe('pipeables', () => { it('traverse', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.traverse(O.Applicative)((n) => (n >= 0 ? O.some(n) : O.none)) ), O.some([1, 2, 3]) ) U.deepStrictEqual( pipe( [1, 2, 3], _.traverse(O.Applicative)((n) => (n >= 2 ? O.some(n) : O.none)) ), O.none ) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence([O.some(1), O.some(2), O.some(3)]), O.some([1, 2, 3])) U.deepStrictEqual(sequence([O.none, O.some(2), O.some(3)]), O.none) }) it('traverseWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length >= 1 ? O.some(s + i) : O.none)) ), O.some(['a0', 'bb1']) ) U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length > 1 ? O.some(s + i) : O.none)) ), O.none ) }) }) it('head', () => { U.deepStrictEqual(_.head([1, 2]), 1) }) it('tail', () => { U.deepStrictEqual(_.tail([1, 2]), [2]) }) it('map', () => { U.deepStrictEqual( pipe( [1, 2], _.map((n) => n * 2) ), [2, 4] ) }) it('mapWithIndex', () => { const add = (i: number, n: number) => n + i U.deepStrictEqual(pipe([1, 2], _.mapWithIndex(add)), [1, 3]) }) it('of', () => { U.deepStrictEqual(_.of(1), [1]) }) it('ap', () => { const fab: _.NonEmptyArray<(n: number) => number> = [U.double, U.double] U.deepStrictEqual(pipe(fab, _.ap([1, 2])), [2, 4, 2, 4]) }) it('flatMap', () => { const f = (a: number): _.NonEmptyArray => [a, 4] U.deepStrictEqual(pipe([1, 2], _.flatMap(f)), [1, 4, 2, 4]) U.deepStrictEqual(_.flatMap([1, 2], f), [1, 4, 2, 4]) }) it('chain', () => { const f = (a: number): _.NonEmptyArray => [a, 4] U.deepStrictEqual(pipe([1, 2], _.chain(f)), [1, 4, 2, 4]) }) it('extend', () => { const sum = _.concatAll(N.MonoidSum) U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(sum)), [10, 9, 7, 4]) }) it('extract', () => { U.deepStrictEqual(_.extract([1, 2, 3]), 1) }) it('min', () => { U.deepStrictEqual(_.min(N.Ord)([2, 1, 3]), 1) U.deepStrictEqual(_.min(N.Ord)([3]), 3) }) it('max', () => { U.deepStrictEqual(_.max(N.Ord)([1, 2, 3]), 3) U.deepStrictEqual(_.max(N.Ord)([1]), 1) }) it('reduce', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduce('', (b, a) => b + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe(['a', 'b', 'c'], _.foldMap(S.Monoid)(identity)), 'abc') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(['a', 'b', 'c'], _.reduceRight('', f)), 'cba') }) it('fromArray', () => { U.deepStrictEqual(_.fromArray([]), O.none) U.deepStrictEqual(_.fromArray([1]), O.some([1])) U.deepStrictEqual(_.fromArray([1, 2]), O.some([1, 2])) }) it('getSemigroup', () => { const S = _.getSemigroup() U.deepStrictEqual(S.concat([1], [2]), [1, 2]) U.deepStrictEqual(S.concat([1, 2], [3, 4]), [1, 2, 3, 4]) }) it('getEq', () => { const S = _.getEq(N.Eq) U.deepStrictEqual(S.equals([1], [1]), true) U.deepStrictEqual(S.equals([1], [1, 2]), false) }) it('group', () => { U.deepStrictEqual(_.group(N.Ord)([]), []) U.deepStrictEqual(_.group(N.Ord)([1, 2, 1, 1]), [[1], [2], [1, 1]]) U.deepStrictEqual(_.group(N.Ord)([1, 2, 1, 1, 3]), [[1], [2], [1, 1], [3]]) }) it('groupSort', () => { U.deepStrictEqual(_.groupSort(N.Ord)([]), []) U.deepStrictEqual(_.groupSort(N.Ord)([1, 2, 1, 1]), [[1, 1, 1], [2]]) }) it('last', () => { U.deepStrictEqual(_.last([1, 2, 3]), 3) U.deepStrictEqual(_.last([1]), 1) }) it('init', () => { U.deepStrictEqual(_.init([1, 2, 3]), [1, 2]) U.deepStrictEqual(_.init([1]), []) }) it('sort', () => { const sort = _.sort(N.Ord) U.deepStrictEqual(sort([3, 2, 1]), [1, 2, 3]) U.deepStrictEqual(sort([1]), [1]) }) it('prependAll', () => { U.deepStrictEqual(_.prependAll(0)([1, 2, 3]), [0, 1, 0, 2, 0, 3]) U.deepStrictEqual(_.prependAll(0)([1]), [0, 1]) U.deepStrictEqual(_.prependAll(0)([1, 2, 3, 4]), [0, 1, 0, 2, 0, 3, 0, 4]) }) it('intersperse', () => { U.deepStrictEqual(_.intersperse(0)([1, 2, 3]), [1, 0, 2, 0, 3]) U.deepStrictEqual(_.intersperse(0)([1]), [1]) U.deepStrictEqual(_.intersperse(0)([1, 2]), [1, 0, 2]) U.deepStrictEqual(_.intersperse(0)([1, 2, 3, 4]), [1, 0, 2, 0, 3, 0, 4]) }) it('intercalate', () => { U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a']), 'a') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', 'b', 'c']), 'a-b-c') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', '', 'c']), 'a--c') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', 'b']), 'a-b') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', 'b', 'c', 'd']), 'a-b-c-d') }) it('reverse', () => { U.deepStrictEqual(_.reverse([1, 2, 3]), [3, 2, 1]) }) it('groupBy', () => { U.deepStrictEqual(_.groupBy((_) => '')([]), {}) U.deepStrictEqual(_.groupBy(String)([1]), { '1': [1] }) U.deepStrictEqual(_.groupBy((s: string) => String(s.length))(['foo', 'bar', 'foobar']), { '3': ['foo', 'bar'], '6': ['foobar'] }) }) it('union', () => { const concat = _.getUnionSemigroup(N.Eq).concat U.deepStrictEqual(concat([1, 2], [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(concat([1, 2], [2, 3]), [1, 2, 3]) U.deepStrictEqual(concat([1, 2], [1, 2]), [1, 2]) }) it('insertAt', () => { const make = (x: number) => ({ x }) const a1 = make(1) const a2 = make(1) const a3 = make(2) const a4 = make(3) U.deepStrictEqual(pipe([], _.insertAt(1, 1)), O.none) U.deepStrictEqual(pipe([], _.insertAt(0, 1)), O.some([1])) U.deepStrictEqual(_.insertAt(0, a4)([a1, a2, a3]), O.some([a4, a1, a2, a3])) U.deepStrictEqual(_.insertAt(-1, a4)([a1, a2, a3]), O.none) U.deepStrictEqual(_.insertAt(3, a4)([a1, a2, a3]), O.some([a1, a2, a3, a4])) U.deepStrictEqual(_.insertAt(1, a4)([a1, a2, a3]), O.some([a1, a4, a2, a3])) U.deepStrictEqual(_.insertAt(4, a4)([a1, a2, a3]), O.none) }) it('updateAt', () => { const make2 = (x: number) => ({ x }) const a1 = make2(1) const a2 = make2(1) const a3 = make2(2) const a4 = make2(3) const arr: _.NonEmptyArray<{ readonly x: number }> = [a1, a2, a3] U.deepStrictEqual(_.updateAt(0, a4)(arr), O.some([a4, a2, a3])) U.deepStrictEqual(_.updateAt(-1, a4)(arr), O.none) U.deepStrictEqual(_.updateAt(3, a4)(arr), O.none) U.deepStrictEqual(_.updateAt(1, a4)(arr), O.some([a1, a4, a3])) // should return the same reference if nothing changed const r1 = _.updateAt(0, a1)(arr) if (O.isSome(r1)) { U.deepStrictEqual(r1.value, arr) } else { assert.fail('is not a Some') } const r2 = _.updateAt(2, a3)(arr) if (O.isSome(r2)) { U.deepStrictEqual(r2.value, arr) } else { assert.fail('is not a Some') } }) it('modifyAt', () => { U.deepStrictEqual(_.modifyAt(1, U.double)([1]), O.none) U.deepStrictEqual(_.modifyAt(1, U.double)([1, 2]), O.some([1, 4])) // should not return the same reference if nothing changed const input: _.NonEmptyArray = [1, 2, 3] U.deepStrictEqual( pipe( input, _.modifyAt(1, identity), O.map((out) => out === input) ), O.some(false) ) }) it('copy', () => { const nea1: _.NonEmptyArray = [1] const nea2 = _.copy(nea1) U.deepStrictEqual(nea2, nea1) U.deepStrictEqual(nea2 === nea1, false) }) it('filter', () => { const make = (x: number) => ({ x }) const a1 = make(1) const a2 = make(1) const a3 = make(2) const as: _.NonEmptyArray<{ readonly x: number }> = [a1, a2, a3] U.deepStrictEqual( pipe( as, _.filter(({ x }) => x !== 1) ), O.some([a3]) ) U.deepStrictEqual( pipe( as, _.filter(({ x }) => x !== 2) ), O.some([a1, a2]) ) U.deepStrictEqual( _.filter(({ x }) => { return !(x === 1 || x === 2) })([a1, a2, a3]), O.none ) U.deepStrictEqual( pipe( as, _.filter(({ x }) => x !== 10) ), O.some([a1, a2, a3]) ) // refinements const actual1 = _.filter(O.isSome)([O.some(3), O.some(2), O.some(1)]) U.deepStrictEqual(actual1, O.some([O.some(3), O.some(2), O.some(1)])) const actual2 = _.filter(O.isSome)([O.some(3), O.none, O.some(1)]) U.deepStrictEqual(actual2, O.some([O.some(3), O.some(1)])) }) it('filterWithIndex', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.filterWithIndex((i) => i % 2 === 0) ), O.some([1, 3]) ) U.deepStrictEqual(_.filterWithIndex((i, a: number) => i % 2 === 1 && a > 2)([1, 2, 3]), O.none) }) it('reduceWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceWithIndex('', (i, b, a) => b + i + a) ), '0a1b' ) }) it('foldMapWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.foldMapWithIndex(S.Monoid)((i, a) => i + a) ), '0a1b' ) }) it('reduceRightWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceRightWithIndex('', (i, a, b) => b + i + a) ), '1b0a' ) }) it('cons', () => { U.deepStrictEqual(_.cons(1, [2, 3, 4]), [1, 2, 3, 4]) }) it('snoc', () => { U.deepStrictEqual(_.snoc([1, 2, 3], 4), [1, 2, 3, 4]) }) it('unprepend', () => { U.deepStrictEqual(_.unprepend([0]), [0, []]) U.deepStrictEqual(_.unprepend([1, 2, 3, 4]), [1, [2, 3, 4]]) }) it('unappend', () => { U.deepStrictEqual(_.unappend([0]), [[], 0]) U.deepStrictEqual(_.unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) }) it('getShow', () => { const Sh = _.getShow(S.Show) U.deepStrictEqual(Sh.show(['a']), `["a"]`) U.deepStrictEqual(Sh.show(['a', 'b', 'c']), `["a", "b", "c"]`) }) it('alt', () => { U.deepStrictEqual( pipe( ['a'], _.alt(() => ['b']) ), ['a', 'b'] ) }) it('foldMap', () => { const f = _.foldMap(N.SemigroupSum)((s: string) => s.length) U.deepStrictEqual(f(['a']), 1) U.deepStrictEqual(f(['a', 'bb']), 3) }) it('foldMapWithIndex', () => { const f = _.foldMapWithIndex(N.SemigroupSum)((i: number, s: string) => s.length + i) U.deepStrictEqual(f(['a']), 1) U.deepStrictEqual(f(['a', 'bb']), 4) }) it('concatAll', () => { const f = _.concatAll(S.Semigroup) U.deepStrictEqual(f(['a']), 'a') U.deepStrictEqual(f(['a', 'bb']), 'abb') }) it('zipWith', () => { U.deepStrictEqual( _.zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3'] ) }) it('zip', () => { const x: _.NonEmptyArray = [1, 2, 3] U.deepStrictEqual(_.zip(x, ['a', 'b', 'c', 'd']), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) U.deepStrictEqual(pipe(x, _.zip(['a', 'b', 'c', 'd'])), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) }) it('unzip', () => { U.deepStrictEqual( _.unzip([ [1, 'a'], [2, 'b'], [3, 'c'] ]), [ [1, 2, 3], ['a', 'b', 'c'] ] ) }) it('splitAt', () => { const assertSplitAt = ( input: _.NonEmptyArray, index: number, expectedInit: ReadonlyArray, expectedRest: ReadonlyArray ) => { const [init, rest] = _.splitAt(index)(input) U.deepStrictEqual(init, expectedInit) U.deepStrictEqual(rest, expectedRest) } const two: _.NonEmptyArray = [1, 2] U.deepStrictEqual(_.splitAt(1)(two), [[1], [2]]) assertSplitAt(two, 2, two, []) const singleton: _.NonEmptyArray = [1] assertSplitAt(singleton, 1, singleton, []) // out of bounds assertSplitAt(singleton, 0, singleton, []) assertSplitAt(singleton, 2, singleton, []) U.deepStrictEqual(_.splitAt(0)(two), [[1], [2]]) assertSplitAt(two, 3, two, []) }) it('chunksOf', () => { U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5, 6]), [ [1, 2], [3, 4], [5, 6] ]) U.deepStrictEqual(_.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]]) // out of bounds U.deepStrictEqual(_.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) const assertSingleChunk = (input: _.NonEmptyArray, n: number) => { const chunks = _.chunksOf(n)(input) U.deepStrictEqual(chunks.length, 1) U.deepStrictEqual(_.head(chunks), input) } // n = length assertSingleChunk([1, 2], 2) // n out of bounds assertSingleChunk([1, 2], 3) }) it('matchLeft', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.matchLeft((head, tail) => [head, tail]) ), [1, [2, 3]] ) }) it('matchRight', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.matchRight((init, last) => [init, last]) ), [[1, 2], 3] ) }) it('modifyHead', () => { const f: Endomorphism = (s) => s + '!' U.deepStrictEqual(pipe(['a'], _.modifyHead(f)), ['a!']) U.deepStrictEqual(pipe(['a', 'b'], _.modifyHead(f)), ['a!', 'b']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.modifyHead(f)), ['a!', 'b', 'c']) }) it('modifyLast', () => { const f: Endomorphism = (s) => s + '!' U.deepStrictEqual(pipe(['a'], _.modifyLast(f)), ['a!']) U.deepStrictEqual(pipe(['a', 'b'], _.modifyLast(f)), ['a', 'b!']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.modifyLast(f)), ['a', 'b', 'c!']) }) it('replicate', () => { const f = _.replicate('a') U.deepStrictEqual(pipe(0, f), ['a']) U.deepStrictEqual(pipe(1, f), ['a']) U.deepStrictEqual(pipe(2, f), ['a', 'a']) }) it('updateHead', () => { U.deepStrictEqual(pipe(['a'], _.updateHead('d')), ['d']) U.deepStrictEqual(pipe(['a', 'b'], _.updateHead('d')), ['d', 'b']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.updateHead('d')), ['d', 'b', 'c']) }) it('updateLast', () => { U.deepStrictEqual(pipe(['a'], _.updateLast('d')), ['d']) U.deepStrictEqual(pipe(['a', 'b'], _.updateLast('d')), ['a', 'd']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.updateLast('d')), ['a', 'b', 'd']) }) it('concatW', () => { U.deepStrictEqual(pipe(['a'], _.concatW(['b'])), ['a', 'b']) }) it('concat', () => { U.deepStrictEqual(pipe(['a'], _.concat(['b'])), ['a', 'b']) U.deepStrictEqual(pipe([], _.concat(['b'])), ['b']) U.deepStrictEqual(pipe(['a'], _.concat([])), ['a']) U.deepStrictEqual(_.concat(['a'], ['b']), ['a', 'b']) U.deepStrictEqual(_.concat(['a'], []), ['a']) U.deepStrictEqual(_.concat([], ['b']), ['b']) }) }) ================================================ FILE: test/Option.ts ================================================ import * as E from '../src/Either' import { identity, pipe } from '../src/function' import * as N from '../src/number' import * as _ from '../src/Option' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { separated } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' const p = (n: number): boolean => n > 2 describe('Option', () => { describe('pipeables', () => { it('map', () => { U.deepStrictEqual(pipe(_.some(2), _.map(U.double)), _.some(4)) U.deepStrictEqual(pipe(_.none, _.map(U.double)), _.none) }) it('flap', () => { U.deepStrictEqual(pipe(_.some(U.double), _.flap(2)), _.some(4)) U.deepStrictEqual(pipe(_.none, _.flap(2)), _.none) }) it('ap', () => { U.deepStrictEqual(pipe(_.some(U.double), _.ap(_.some(2))), _.some(4)) U.deepStrictEqual(pipe(_.some(U.double), _.ap(_.none)), _.none) U.deepStrictEqual(pipe(_.none, _.ap(_.some(2))), _.none) U.deepStrictEqual(pipe(_.none, _.ap(_.none)), _.none) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.some('a'), _.apFirst(_.some('b'))), _.some('a')) }) it('apSecond', () => { U.deepStrictEqual(pipe(_.some('a'), _.apSecond(_.some('b'))), _.some('b')) }) it('flatMap', () => { const f = (n: number) => _.some(n * 2) const g = () => _.none U.deepStrictEqual(pipe(_.some(1), _.flatMap(f)), _.some(2)) U.deepStrictEqual(pipe(_.none, _.flatMap(f)), _.none) U.deepStrictEqual(pipe(_.some(1), _.flatMap(g)), _.none) U.deepStrictEqual(pipe(_.none, _.flatMap(g)), _.none) U.deepStrictEqual(_.flatMap(_.some(1), f), _.some(2)) U.deepStrictEqual(_.flatMap(_.none, f), _.none) U.deepStrictEqual(_.flatMap(_.some(1), g), _.none) U.deepStrictEqual(_.flatMap(_.none, g), _.none) }) it('chain', () => { const f = (n: number) => _.some(n * 2) const g = () => _.none U.deepStrictEqual(pipe(_.some(1), _.chain(f)), _.some(2)) U.deepStrictEqual(pipe(_.none, _.chain(f)), _.none) U.deepStrictEqual(pipe(_.some(1), _.chain(g)), _.none) U.deepStrictEqual(pipe(_.none, _.chain(g)), _.none) }) it('tap', () => { const f = (n: number) => _.some(n * 2) U.deepStrictEqual(pipe(_.some(1), _.tap(f)), _.some(1)) U.deepStrictEqual(_.tap(_.some(1), f), _.some(1)) }) it('chainFirst', () => { const f = (n: number) => _.some(n * 2) U.deepStrictEqual(pipe(_.some(1), _.chainFirst(f)), _.some(1)) }) it('duplicate', () => { U.deepStrictEqual(pipe(_.some(1), _.duplicate), _.some(_.some(1))) }) it('flatten', () => { U.deepStrictEqual(pipe(_.some(_.some(1)), _.flatten), _.some(1)) }) it('alt', () => { U.deepStrictEqual( pipe( _.some(1), _.alt(() => _.some(2)) ), _.some(1) ) U.deepStrictEqual( pipe( _.some(2), _.alt(() => _.none as _.Option) ), _.some(2) ) U.deepStrictEqual( pipe( _.none, _.alt(() => _.some(1)) ), _.some(1) ) U.deepStrictEqual( pipe( _.none, _.alt(() => _.none) ), _.none ) }) it('extend', () => { const f = _.getOrElse(() => 0) U.deepStrictEqual(pipe(_.some(2), _.extend(f)), _.some(2)) U.deepStrictEqual(pipe(_.none, _.extend(f)), _.none) }) it('reduce', () => { U.deepStrictEqual( pipe( _.none, _.reduce(2, (b, a) => b + a) ), 2 ) U.deepStrictEqual( pipe( _.some(3), _.reduce(2, (b, a) => b + a) ), 5 ) }) it('foldMap', () => { U.deepStrictEqual(pipe(_.some('a'), _.foldMap(S.Monoid)(identity)), 'a') U.deepStrictEqual(pipe(_.none, _.foldMap(S.Monoid)(identity)), '') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(_.some('a'), _.reduceRight('', f)), 'a') U.deepStrictEqual(pipe(_.none, _.reduceRight('', f)), '') }) it('compact', () => { U.deepStrictEqual(_.compact(_.none), _.none) U.deepStrictEqual(_.compact(_.some(_.none)), _.none) U.deepStrictEqual(_.compact(_.some(_.some('123'))), _.some('123')) }) it('separate', () => { U.deepStrictEqual(_.separate(_.none), separated(_.none, _.none)) U.deepStrictEqual(_.separate(_.some(E.left('123'))), separated(_.some('123'), _.none)) U.deepStrictEqual(_.separate(_.some(E.right('123'))), separated(_.none, _.some('123'))) }) it('filter', () => { const predicate = (a: number) => a === 2 U.deepStrictEqual(pipe(_.none, _.filter(predicate)), _.none) U.deepStrictEqual(pipe(_.some(1), _.filter(predicate)), _.none) U.deepStrictEqual(pipe(_.some(2), _.filter(predicate)), _.some(2)) }) it('filterMap', () => { const f = (n: number) => (p(n) ? _.some(n + 1) : _.none) U.deepStrictEqual(pipe(_.none, _.filterMap(f)), _.none) U.deepStrictEqual(pipe(_.some(1), _.filterMap(f)), _.none) U.deepStrictEqual(pipe(_.some(3), _.filterMap(f)), _.some(4)) }) it('partition', () => { U.deepStrictEqual(pipe(_.none, _.partition(p)), separated(_.none, _.none)) U.deepStrictEqual(pipe(_.some(1), _.partition(p)), separated(_.some(1), _.none)) U.deepStrictEqual(pipe(_.some(3), _.partition(p)), separated(_.none, _.some(3))) }) it('partitionMap', () => { const f = (n: number) => (p(n) ? E.right(n + 1) : E.left(n - 1)) U.deepStrictEqual(pipe(_.none, _.partitionMap(f)), separated(_.none, _.none)) U.deepStrictEqual(pipe(_.some(1), _.partitionMap(f)), separated(_.some(0), _.none)) U.deepStrictEqual(pipe(_.some(3), _.partitionMap(f)), separated(_.none, _.some(4))) }) it('traverse', () => { U.deepStrictEqual( pipe( _.some('hello'), _.traverse(RA.Applicative)(() => []) ), [] ) U.deepStrictEqual( pipe( _.some('hello'), _.traverse(RA.Applicative)((s) => [s.length]) ), [_.some(5)] ) U.deepStrictEqual( pipe( _.none, _.traverse(RA.Applicative)((s) => [s]) ), [_.none] ) }) it('sequence', () => { const sequence = _.sequence(RA.Applicative) U.deepStrictEqual(sequence(_.some([1, 2])), [_.some(1), _.some(2)]) U.deepStrictEqual(sequence(_.none), [_.none]) }) it('wither', async () => { const wither = _.wither(T.ApplicativePar)((n: number) => T.of(p(n) ? _.some(n + 1) : _.none)) U.deepStrictEqual(await pipe(_.none, wither)(), _.none) U.deepStrictEqual(await pipe(_.some(1), wither)(), _.none) U.deepStrictEqual(await pipe(_.some(3), wither)(), _.some(4)) }) it('wilt', async () => { const wilt = _.wilt(T.ApplicativePar)((n: number) => T.of(p(n) ? E.right(n + 1) : E.left(n - 1))) U.deepStrictEqual(await pipe(_.none, wilt)(), separated(_.none, _.none)) U.deepStrictEqual(await pipe(_.some(1), wilt)(), separated(_.some(0), _.none)) U.deepStrictEqual(await pipe(_.some(3), wilt)(), separated(_.none, _.some(4))) }) }) describe('constructors', () => { it('fromEither', () => { U.deepStrictEqual(_.fromEither(E.left('a')), _.none) U.deepStrictEqual(_.fromEither(E.right(1)), _.some(1)) }) }) it('zero', () => { U.deepStrictEqual(_.zero(), _.none) }) it('fold', () => { const f = () => 'none' const g = (s: string) => `some${s.length}` const fold = _.fold(f, g) U.deepStrictEqual(fold(_.none), 'none') U.deepStrictEqual(fold(_.some('abc')), 'some3') }) it('toNullable', () => { U.deepStrictEqual(_.toNullable(_.none), null) U.deepStrictEqual(_.toNullable(_.some(1)), 1) }) it('toUndefined', () => { U.deepStrictEqual(_.toUndefined(_.none), undefined) U.deepStrictEqual(_.toUndefined(_.some(1)), 1) }) it('getOrElse', () => { U.deepStrictEqual( pipe( _.some(1), _.getOrElse(() => 0) ), 1 ) U.deepStrictEqual( pipe( _.none, _.getOrElse(() => 0) ), 0 ) }) it('equals', () => { const { equals } = _.getEq(N.Eq) U.deepStrictEqual(equals(_.none, _.none), true) U.deepStrictEqual(equals(_.none, _.some(1)), false) U.deepStrictEqual(equals(_.some(1), _.none), false) U.deepStrictEqual(equals(_.some(2), _.some(1)), false) U.deepStrictEqual(equals(_.some(1), _.some(2)), false) U.deepStrictEqual(equals(_.some(2), _.some(2)), true) }) it('getEq', () => { const E = _.getEq(S.Ord) U.deepStrictEqual(E.equals(_.none, _.none), true) U.deepStrictEqual(E.equals(_.some('a'), _.none), false) U.deepStrictEqual(E.equals(_.none, _.some('a')), false) U.deepStrictEqual(E.equals(_.some('a'), _.some('a')), true) U.deepStrictEqual(E.equals(_.some('a'), _.some('b')), false) }) it('getOrd', () => { const OS = _.getOrd(S.Ord) U.deepStrictEqual(OS.compare(_.none, _.none), 0) U.deepStrictEqual(OS.compare(_.none, { _tag: 'None' }), 0) U.deepStrictEqual(OS.compare(_.some('a'), _.none), 1) U.deepStrictEqual(OS.compare(_.none, _.some('a')), -1) U.deepStrictEqual(OS.compare(_.some('a'), _.some('a')), 0) U.deepStrictEqual(OS.compare(_.some('a'), _.some('b')), -1) U.deepStrictEqual(OS.compare(_.some('b'), _.some('a')), 1) }) it('chainNullableK', () => { interface X { readonly a?: { readonly b?: { readonly c?: { readonly d: number } } } } const x1: X = { a: {} } const x2: X = { a: { b: {} } } const x3: X = { a: { b: { c: { d: 1 } } } } U.deepStrictEqual( pipe( _.fromNullable(x1.a), _.chainNullableK((x) => x.b), _.chainNullableK((x) => x.c), _.chainNullableK((x) => x.d) ), _.none ) U.deepStrictEqual( pipe( _.fromNullable(x2.a), _.chainNullableK((x) => x.b), _.chainNullableK((x) => x.c), _.chainNullableK((x) => x.d) ), _.none ) U.deepStrictEqual( pipe( _.fromNullable(x3.a), _.chainNullableK((x) => x.b), _.chainNullableK((x) => x.c), _.chainNullableK((x) => x.d) ), _.some(1) ) }) it('getMonoid', () => { const { concat } = _.getMonoid(S.Semigroup) U.deepStrictEqual(concat(_.none, _.none), _.none) U.deepStrictEqual(concat(_.none, _.some('a')), _.some('a')) U.deepStrictEqual(concat(_.some('a'), _.none), _.some('a')) U.deepStrictEqual(concat(_.some('b'), _.some('a')), _.some('ba')) U.deepStrictEqual(concat(_.some('a'), _.some('b')), _.some('ab')) }) it('fromNullable', () => { U.deepStrictEqual(_.fromNullable(2), _.some(2)) U.deepStrictEqual(_.fromNullable(null), _.none) U.deepStrictEqual(_.fromNullable(undefined), _.none) }) it('fromPredicate', () => { const f = _.fromPredicate(p) U.deepStrictEqual(f(1), _.none) U.deepStrictEqual(f(3), _.some(3)) type Direction = 'asc' | 'desc' const parseDirection = _.fromPredicate((s: string): s is Direction => s === 'asc' || s === 'desc') U.deepStrictEqual(parseDirection('asc'), _.some('asc')) U.deepStrictEqual(parseDirection('foo'), _.none) }) it('getApplySemigroup', () => { const S = _.getApplySemigroup(N.SemigroupSum) U.deepStrictEqual(S.concat(_.none, _.none), _.none) U.deepStrictEqual(S.concat(_.some(1), _.none), _.none) U.deepStrictEqual(S.concat(_.none, _.some(1)), _.none) U.deepStrictEqual(S.concat(_.some(1), _.some(2)), _.some(3)) }) it('getApplyMonoid', () => { const M = _.getApplyMonoid(N.MonoidSum) U.deepStrictEqual(M.concat(M.empty, _.none), _.none) U.deepStrictEqual(M.concat(_.none, M.empty), _.none) U.deepStrictEqual(M.concat(M.empty, _.some(1)), _.some(1)) U.deepStrictEqual(M.concat(_.some(1), M.empty), _.some(1)) }) it('getFirstMonoid', () => { const M = _.getFirstMonoid() U.deepStrictEqual(M.concat(_.none, _.none), _.none) U.deepStrictEqual(M.concat(_.some(1), _.none), _.some(1)) U.deepStrictEqual(M.concat(_.none, _.some(2)), _.some(2)) U.deepStrictEqual(M.concat(_.some(1), _.some(2)), _.some(1)) }) it('getLastMonoid', () => { const M = _.getLastMonoid() U.deepStrictEqual(M.concat(_.none, _.none), _.none) U.deepStrictEqual(M.concat(_.some(1), _.none), _.some(1)) U.deepStrictEqual(M.concat(_.none, _.some(2)), _.some(2)) U.deepStrictEqual(M.concat(_.some(1), _.some(2)), _.some(2)) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(2, _.none), false) U.deepStrictEqual(_.elem(N.Eq)(2, _.some(2)), true) U.deepStrictEqual(_.elem(N.Eq)(1, _.some(2)), false) U.deepStrictEqual(pipe(_.none, _.elem(N.Eq)(2)), false) U.deepStrictEqual(pipe(_.some(2), _.elem(N.Eq)(2)), true) U.deepStrictEqual(pipe(_.some(2), _.elem(N.Eq)(1)), false) }) it('isNone', () => { U.deepStrictEqual(_.isNone(_.none), true) U.deepStrictEqual(_.isNone(_.some(1)), false) }) it('isSome', () => { U.deepStrictEqual(_.isSome(_.none), false) U.deepStrictEqual(_.isSome(_.some(1)), true) }) it('exists', () => { const predicate = (a: number) => a === 2 U.deepStrictEqual(pipe(_.none, _.exists(predicate)), false) U.deepStrictEqual(pipe(_.some(1), _.exists(predicate)), false) U.deepStrictEqual(pipe(_.some(2), _.exists(predicate)), true) }) it('tryCatch', () => { U.deepStrictEqual( _.tryCatch(() => JSON.parse('2')), _.some(2) ) U.deepStrictEqual( _.tryCatch(() => JSON.parse('(')), _.none ) }) it('getRefinement', () => { const f = (s: string | number): _.Option => (typeof s === 'string' ? _.some(s) : _.none) const isString = _.getRefinement(f) U.deepStrictEqual(isString('s'), true) U.deepStrictEqual(isString(1), false) type A = { readonly type: 'A' } type B = { readonly type: 'B' } type C = A | B const isA = _.getRefinement((c) => (c.type === 'A' ? _.some(c) : _.none)) U.deepStrictEqual(isA({ type: 'A' }), true) U.deepStrictEqual(isA({ type: 'B' }), false) }) it('getShow', () => { const Sh = _.getShow(S.Show) U.deepStrictEqual(Sh.show(_.some('a')), `some("a")`) U.deepStrictEqual(Sh.show(_.none), `none`) }) it('getLeft', () => { U.deepStrictEqual(_.getLeft(E.right(1)), _.none) U.deepStrictEqual(_.getLeft(E.left('err')), _.some('err')) }) it('getRight', () => { U.deepStrictEqual(_.getRight(E.right(1)), _.some(1)) U.deepStrictEqual(_.getRight(E.left('err')), _.none) }) it('throwError', () => { U.deepStrictEqual(_.throwError(undefined), _.none) }) it('do notation', () => { U.deepStrictEqual( pipe( _.some(1), _.bindTo('a'), _.bind('b', () => _.some('b')), _.let('c', ({ a, b }) => [a, b]) ), _.some({ a: 1, b: 'b', c: [1, 'b'] }) ) }) it('apS', () => { U.deepStrictEqual(pipe(_.some(1), _.bindTo('a'), _.apS('b', _.some('b'))), _.some({ a: 1, b: 'b' })) }) it('fromNullableK', () => { const f = _.fromNullableK((n: number) => (n > 0 ? n : null)) U.deepStrictEqual(f(1), _.some(1)) U.deepStrictEqual(f(-1), _.none) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none)) U.deepStrictEqual(pipe(RA.empty, f), _.some(RA.empty)) U.deepStrictEqual(pipe(input, f), _.some(['a0', 'b1'])) U.deepStrictEqual(pipe(['a', ''], f), _.none) }) it('sequenceArray', () => { U.deepStrictEqual(pipe([_.of(1), _.of(2)], _.sequenceArray), _.some([1, 2])) U.deepStrictEqual(pipe([_.of(1), _.none], _.sequenceArray), _.none) }) }) it('tryCatchK', () => { const f = _.tryCatchK((s: string) => { const len = s.length if (len > 0) { return len } throw new Error('empty string') }) U.deepStrictEqual(f('a'), _.some(1)) U.deepStrictEqual(f(''), _.none) }) it('guard', () => { U.deepStrictEqual( pipe( _.Do, _.bind('x', () => _.some('a')), _.bind('y', () => _.some('a')), _.chainFirst(({ x, y }) => _.guard(x === y)) ), _.some({ x: 'a', y: 'a' }) ) U.deepStrictEqual( pipe( _.Do, _.bind('x', () => _.some('a')), _.bind('y', () => _.some('b')), _.chainFirst(({ x, y }) => _.guard(x === y)) ), _.none ) }) it('tapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(pipe(_.some('a'), _.tapEither(f)), _.some('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(pipe(_.some('a'), _.tapEither(g)), _.none) }) it('chainFirstEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(pipe(_.some('a'), _.chainFirstEitherK(f)), _.some('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(pipe(_.some('a'), _.chainFirstEitherK(g)), _.none) }) it('as', () => { U.deepStrictEqual(pipe(_.some('a'), _.as('b')), _.some('b')) U.deepStrictEqual(_.as(_.of('a'), 'b'), _.some('b')) U.deepStrictEqual(_.as(_.none, 'b'), _.none) }) it('asUnit', () => { U.deepStrictEqual(pipe(_.some('a'), _.asUnit), _.some(undefined)) }) }) ================================================ FILE: test/OptionT.ts ================================================ import * as O from '../src/Option' import { getOptionM } from '../src/OptionT' import * as T from '../src/Task' import * as U from './util' const MT = getOptionM(T.Monad) describe('OptionT', () => { it('map', async () => { const greetingT = MT.of('welcome') const excitedGreetingT = MT.map(greetingT, (s) => s + '!') U.deepStrictEqual(await excitedGreetingT(), O.some('welcome!')) }) it('ap', async () => { const a = MT.of('a') const b = MT.of('b') U.deepStrictEqual( await MT.ap( MT.map(a, (a) => (b) => [a, b]), b )(), O.some(['a', 'b']) ) }) it('chain', async () => { const to1 = MT.chain(MT.of('foo'), (a) => MT.of(a.length)) const to2 = MT.chain(T.of(O.none), (a: string) => MT.of(a.length)) const [o1, o2] = await Promise.all([to1(), to2()]) U.deepStrictEqual(o1, O.some(3)) U.deepStrictEqual(o2, O.none) }) it('fold', async () => { const f = () => T.of('none') const g = (s: string) => T.of(`some${s.length}`) const s1 = await MT.fold(T.of(O.none), f, g)() U.deepStrictEqual(s1, 'none') const s2 = await MT.fold(MT.of('s'), f, g)() U.deepStrictEqual(s2, 'some1') }) it('alt', async () => { const o1 = await MT.alt(T.of(O.some(1)), () => T.of(O.some(2)))() U.deepStrictEqual(o1, O.some(1)) const o2 = await MT.alt(T.of(O.none), () => T.of(O.some(2)))() U.deepStrictEqual(o2, O.some(2)) }) it('getOrElse', async () => { const n1 = await MT.getOrElse(T.of(O.some(1)), () => T.of(2))() U.deepStrictEqual(n1, 1) const n2 = await MT.getOrElse(T.of(O.none), () => T.of(2))() U.deepStrictEqual(n2, 2) }) it('fromM', async () => { U.deepStrictEqual(await MT.fromM(T.of(1))(), O.some(1)) }) it('none', async () => { U.deepStrictEqual(await MT.none()(), O.none) }) }) ================================================ FILE: test/Ord.ts ================================================ import * as B from '../src/boolean' import { pipe } from '../src/function' import { concatAll } from '../src/Monoid' import * as N from '../src/number' import * as _ from '../src/Ord' import { sort } from '../src/ReadonlyArray' import * as RR from '../src/ReadonlyRecord' import * as S from '../src/string' import * as U from './util' describe('Ord', () => { it('tuple', () => { const O = _.tuple(S.Ord, N.Ord, B.Ord) U.deepStrictEqual(O.compare(['a', 1, true], ['b', 2, true]), -1) U.deepStrictEqual(O.compare(['a', 1, true], ['a', 2, true]), -1) U.deepStrictEqual(O.compare(['a', 1, true], ['a', 1, false]), 1) }) it('getMonoid', () => { type T = readonly [number, string] const tuples: ReadonlyArray = [ [2, 'c'], [1, 'b'], [2, 'a'], [1, 'c'] ] const M = _.getMonoid() const sortByFst = pipe( N.Ord, _.contramap((x: T) => x[0]) ) const sortBySnd = pipe( S.Ord, _.contramap((x: T) => x[1]) ) // v-- left unit const O1 = concatAll(M)([M.empty, sortByFst, sortBySnd]) U.deepStrictEqual(sort(O1)(tuples), [ [1, 'b'], [1, 'c'], [2, 'a'], [2, 'c'] ]) // right unit --v const O2 = concatAll(M)([sortBySnd, sortByFst, M.empty]) U.deepStrictEqual(sort(O2)(tuples), [ [2, 'a'], [1, 'b'], [1, 'c'], [2, 'c'] ]) }) it('clamp', () => { const clampNumber = _.clamp(N.Ord) U.deepStrictEqual(clampNumber(1, 10)(2), 2) U.deepStrictEqual(clampNumber(1, 10)(10), 10) U.deepStrictEqual(clampNumber(1, 10)(20), 10) U.deepStrictEqual(clampNumber(1, 10)(1), 1) U.deepStrictEqual(clampNumber(1, 10)(-10), 1) }) it('between', () => { const betweenNumber = _.between(N.Ord) U.deepStrictEqual(betweenNumber(1, 10)(2), true) U.deepStrictEqual(betweenNumber(1, 10)(10), true) U.deepStrictEqual(betweenNumber(1, 10)(20), false) U.deepStrictEqual(betweenNumber(1, 10)(1), true) U.deepStrictEqual(betweenNumber(1, 10)(-10), false) }) it('reverse', () => { const O = _.reverse(N.Ord) U.deepStrictEqual(O.compare(1, 2), 1) U.deepStrictEqual(O.compare(2, 1), -1) U.deepStrictEqual(O.compare(2, 2), 0) }) it('leq', () => { U.deepStrictEqual(_.leq(N.Ord)(0, 1), true) U.deepStrictEqual(_.leq(N.Ord)(1, 1), true) U.deepStrictEqual(_.leq(N.Ord)(2, 1), false) }) it('geq', () => { U.deepStrictEqual(_.geq(N.Ord)(0, 1), false) U.deepStrictEqual(_.geq(N.Ord)(1, 1), true) U.deepStrictEqual(_.geq(N.Ord)(2, 1), true) }) it('fromCompare', () => { const O1 = _.fromCompare(N.Ord.compare) U.deepStrictEqual(O1.equals(0, 1), false) U.deepStrictEqual(O1.equals(1, 1), true) interface A { readonly x: number } let nbCall = 0 const O2 = _.fromCompare((a, b) => { nbCall += 1 return N.Ord.compare(a.x, b.x) }) const a1 = { x: 1 } const a2 = { x: 1 } U.deepStrictEqual(O2.equals(a1, a1), true) U.deepStrictEqual(nbCall, 0) U.deepStrictEqual(O2.equals(a1, a2), true) U.deepStrictEqual(nbCall, 1) U.deepStrictEqual(O2.compare(a1, a1), 0) U.deepStrictEqual(nbCall, 1) U.deepStrictEqual(O2.compare(a1, a2), 0) U.deepStrictEqual(nbCall, 2) }) it('min', () => { type A = { readonly a: number } const min = _.min( pipe( N.Ord, _.contramap((a: A) => a.a) ) ) U.deepStrictEqual(min({ a: 1 }, { a: 2 }), { a: 1 }) U.deepStrictEqual(min({ a: 2 }, { a: 1 }), { a: 1 }) const first = { a: 1 } const second = { a: 1 } U.strictEqual(min(first, second), first) }) it('max', () => { type A = { readonly a: number } const max = _.max( pipe( N.Ord, _.contramap((a: A) => a.a) ) ) U.deepStrictEqual(max({ a: 1 }, { a: 2 }), { a: 2 }) U.deepStrictEqual(max({ a: 2 }, { a: 1 }), { a: 2 }) const first = { a: 1 } const second = { a: 1 } U.strictEqual(max(first, second), first) }) it('equals', () => { const equals = _.equals(N.Ord) U.deepStrictEqual(equals(1)(1), true) U.deepStrictEqual(equals(1)(2), false) }) it('trivial', () => { const toReadonlyArray = RR.collect(_.trivial)((k, a) => [k, a]) U.deepStrictEqual(toReadonlyArray({ a: 1, b: 2 }), [ ['a', 1], ['b', 2] ]) U.deepStrictEqual(toReadonlyArray({ b: 2, a: 1 }), [ ['b', 2], ['a', 1] ]) }) it('ordDate', () => { const O = _.ordDate U.deepStrictEqual(O.compare(new Date(0), new Date(0)), 0) U.deepStrictEqual(O.compare(new Date(0), new Date(1)), -1) U.deepStrictEqual(O.compare(new Date(1), new Date(0)), 1) }) }) ================================================ FILE: test/Ordering.ts ================================================ import * as _ from '../src/Ordering' import * as U from './util' describe('Ordering', () => { // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('Eq', () => { U.deepStrictEqual(_.Eq.equals(-1, -1), true) U.deepStrictEqual(_.Eq.equals(-1, 0), false) U.deepStrictEqual(_.Eq.equals(-1, 1), false) U.deepStrictEqual(_.Eq.equals(0, -1), false) U.deepStrictEqual(_.Eq.equals(0, 0), true) U.deepStrictEqual(_.Eq.equals(0, 1), false) U.deepStrictEqual(_.Eq.equals(1, -1), false) U.deepStrictEqual(_.Eq.equals(1, 0), false) U.deepStrictEqual(_.Eq.equals(1, 1), true) }) it('Monoid', () => { // concat U.deepStrictEqual(_.Monoid.concat(-1, -1), -1) U.deepStrictEqual(_.Monoid.concat(-1, 0), -1) U.deepStrictEqual(_.Monoid.concat(-1, 1), -1) U.deepStrictEqual(_.Monoid.concat(0, -1), -1) U.deepStrictEqual(_.Monoid.concat(0, 0), 0) U.deepStrictEqual(_.Monoid.concat(0, 1), 1) U.deepStrictEqual(_.Monoid.concat(1, -1), 1) U.deepStrictEqual(_.Monoid.concat(1, 0), 1) U.deepStrictEqual(_.Monoid.concat(1, 1), 1) // empty U.deepStrictEqual(_.Monoid.concat(1, _.Monoid.empty), 1) U.deepStrictEqual(_.Monoid.concat(_.Monoid.empty, 1), 1) U.deepStrictEqual(_.Monoid.concat(-1, _.Monoid.empty), -1) U.deepStrictEqual(_.Monoid.concat(_.Monoid.empty, -1), -1) U.deepStrictEqual(_.Monoid.concat(0, _.Monoid.empty), 0) U.deepStrictEqual(_.Monoid.concat(_.Monoid.empty, 0), 0) }) // ------------------------------------------------------------------------------------- // destructors // ------------------------------------------------------------------------------------- it('sign', () => { const f = _.match( () => 'lt', () => 'eq', () => 'gt' ) U.deepStrictEqual(f(-1), 'lt') U.deepStrictEqual(f(0), 'eq') U.deepStrictEqual(f(1), 'gt') }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('sign', () => { U.deepStrictEqual(_.sign(10), 1) U.deepStrictEqual(_.sign(0), 0) U.deepStrictEqual(_.sign(-10), -1) }) it('reverse', () => { U.deepStrictEqual(_.reverse(-1), 1) U.deepStrictEqual(_.reverse(0), 0) U.deepStrictEqual(_.reverse(1), -1) }) }) ================================================ FILE: test/Predicate.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/Predicate' import * as U from './util' const isPositive: _.Predicate = (n) => n > 0 const isNegative: _.Predicate = (n) => n < 0 const lt2: _.Predicate = (n) => n < 2 describe('Predicate', () => { it('contramap', () => { type A = { readonly a: number } const predicate = pipe( isPositive, _.contramap((a: A) => a.a) ) U.deepStrictEqual(predicate({ a: -1 }), false) U.deepStrictEqual(predicate({ a: 0 }), false) U.deepStrictEqual(predicate({ a: 1 }), true) }) it('Contravariant.contramap', () => { type A = { readonly a: number } const predicate = _.Contravariant.contramap(isPositive, (a: A) => a.a) U.deepStrictEqual(predicate({ a: -1 }), false) U.deepStrictEqual(predicate({ a: 0 }), false) U.deepStrictEqual(predicate({ a: 1 }), true) }) it('not', () => { const predicate = _.not(isPositive) U.deepStrictEqual(predicate(1), false) U.deepStrictEqual(predicate(0), true) U.deepStrictEqual(predicate(-1), true) }) it('getMonoidAny', () => { const M = _.getMonoidAny() const predicate = M.concat(isPositive, isNegative) U.deepStrictEqual(predicate(0), false) U.deepStrictEqual(predicate(-1), true) U.deepStrictEqual(predicate(1), true) }) it('getMonoidAll', () => { const M = _.getMonoidAll() const predicate = M.concat(isPositive, lt2) U.deepStrictEqual(predicate(0), false) U.deepStrictEqual(predicate(-2), false) U.deepStrictEqual(predicate(1), true) }) }) ================================================ FILE: test/Random.ts ================================================ import * as _ from '../src/Random' import * as U from './util' describe('Random', () => { it('random', () => { const n = _.random() U.deepStrictEqual(typeof n, 'number') }) it('randomInt', () => { const n = _.randomInt(0, 10)() U.deepStrictEqual(typeof n, 'number') U.deepStrictEqual(n % 1 === 0, true) U.deepStrictEqual(n >= 0, true) U.deepStrictEqual(n <= 10, true) }) it('randomRange', () => { for (let i = 0; i < 10; i++) { const n = _.randomRange(0, 10)() U.deepStrictEqual(typeof n, 'number') U.deepStrictEqual(n >= 0, true) U.deepStrictEqual(n < 10, true) } }) it('randomBool', () => { const b = _.randomBool() U.deepStrictEqual(typeof b, 'boolean') }) it('randomElem', () => { const e = _.randomElem([1, 2, 3])() U.deepStrictEqual(e >= 1 && e <= 3, true) }) }) ================================================ FILE: test/Reader.ts ================================================ import { pipe } from '../src/function' import * as N from '../src/number' import * as _ from '../src/Reader' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import * as S from '../src/string' import * as U from './util' interface Env { readonly count: number } describe('Reader', () => { describe('pipeables', () => { it('map', () => { U.deepStrictEqual(pipe(_.of(1), _.map(U.double))({}), 2) }) it('ap', () => { U.deepStrictEqual(pipe(_.of(U.double), _.ap(_.of(1)))({}), 2) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.of('a'), _.apFirst(_.of('b')))({}), 'a') }) it('apFirstW', () => { const fb = _.of<{ readonly k: string }, boolean>(true) U.deepStrictEqual(pipe(_.of<{ readonly x: number }, string>('foo'), _.apFirstW(fb))({ x: 1, k: 'v' }), 'foo') }) it('apSecond', () => { U.deepStrictEqual(pipe(_.of('a'), _.apSecond(_.of('b')))({}), 'b') }) it('apSecondW', () => { const fb = _.of<{ readonly k: string }, boolean>(true) U.deepStrictEqual(pipe(_.of<{ readonly x: number }, string>('foo'), _.apSecondW(fb))({ x: 1, k: 'v' }), true) }) it('flatMap', () => { const f = (s: string): _.Reader => _.of(s.length) U.deepStrictEqual(pipe(_.of('foo'), _.chain(f))({}), 3) }) it('chain', () => { const f = (s: string): _.Reader => _.of(s.length) U.deepStrictEqual(pipe(_.of('foo'), _.flatMap(f))({}), 3) U.deepStrictEqual(_.flatMap(_.of('foo'), f)({}), 3) }) it('tap', () => { const f = (s: string): _.Reader => _.of(s.length) U.deepStrictEqual(pipe(_.of('foo'), _.tap(f))({}), 'foo') U.deepStrictEqual(_.tap(_.of('foo'), f)({}), 'foo') }) it('chainFirst', () => { const f = (s: string): _.Reader => _.of(s.length) U.deepStrictEqual(pipe(_.of('foo'), _.chainFirst(f))({}), 'foo') }) it('chainFirstW', () => { const f = (s: string) => _.of(s.length) U.deepStrictEqual(pipe(_.of('foo'), _.chainFirstW(f))({}), 'foo') }) it('flatten', () => { U.deepStrictEqual(pipe(_.of(_.of('a')), _.flatten)({}), 'a') }) type R1 = { readonly env1: unknown } type R2 = { readonly env2: unknown } it('flattenW', () => { U.deepStrictEqual(pipe(_.of>(_.of('a')), _.flattenW)({ env1: '', env2: '' }), 'a') }) it('compose', () => { U.deepStrictEqual(pipe(U.double, _.compose(S.size))('aaa'), 6) }) it('promap', () => { const x = (s: string) => s.length const reader = pipe( x, _.promap( (a: { readonly name: string }) => a.name, (n) => n >= 2 ) ) U.deepStrictEqual(reader({ name: 'foo' }), true) U.deepStrictEqual(reader({ name: 'a' }), false) }) }) it('of', () => { U.deepStrictEqual(_.of(1)({}), 1) }) it('local', () => { interface E { readonly name: string } const x = pipe( (s: string) => s.length, _.local((e: E) => e.name) ) U.deepStrictEqual(x({ name: 'foo' }), 3) }) it('id', () => { const x = _.id() U.deepStrictEqual(x(1), 1) }) it('compose', () => { const x = (s: string) => s.length const y = (n: number) => n >= 2 const z = pipe(y, _.compose(x)) U.deepStrictEqual(z('foo'), true) U.deepStrictEqual(z('a'), false) }) it('getSemigroup', () => { const S = _.getSemigroup(N.SemigroupSum) U.deepStrictEqual(S.concat(_.of(1), _.of(2))({}), 3) }) it('getMonoid', () => { const M = _.getMonoid(N.MonoidSum) U.deepStrictEqual(M.concat(_.of(1), M.empty)({}), 1) U.deepStrictEqual(M.concat(M.empty, _.of(1))({}), 1) }) it('ask', () => { const e: Env = { count: 0 } U.deepStrictEqual(_.ask()(e), e) }) it('asks', () => { const e: Env = { count: 0 } const f = (e: Env) => e.count + 1 U.deepStrictEqual(_.asks(f)(e), 1) }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) )(undefined), { a: 1, b: 'b', c: [1, 'b'] } ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b')))(undefined), { a: 1, b: 'b' }) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => _.of(a + i)) U.strictEqual(pipe(RA.empty, f)({}), RA.empty) U.deepStrictEqual(pipe(input, f)({}), ['a0', 'b1']) }) it('sequenceArray', () => { U.deepStrictEqual(pipe([_.of(1), _.of(2)], _.sequenceArray)(undefined), [1, 2]) }) }) it('asksReader', () => { const e: Env = { count: 0 } const f = (e: Env) => _.of(e.count + 1) U.deepStrictEqual(_.asksReader(f)(e), 1) }) }) ================================================ FILE: test/ReaderEither.ts ================================================ import * as Apply from '../src/Apply' import * as E from '../src/Either' import { pipe } from '../src/function' import * as N from '../src/number' import * as O from '../src/Option' import * as R from '../src/Reader' import * as _ from '../src/ReaderEither' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { left, right } from '../src/Separated' import * as S from '../src/string' import * as U from './util' describe('ReaderEither', () => { describe('pipeables', () => { it('map', () => { U.deepStrictEqual(pipe(_.right(1), _.map(U.double))({}), E.right(2)) }) it('alt', () => { U.deepStrictEqual( pipe( _.right('a'), _.alt(() => _.right('b')) )({}), E.right('a') ) U.deepStrictEqual( pipe( _.left(1), _.alt(() => _.right('b')) )({}), E.right('b') ) }) it('ap', () => { U.deepStrictEqual(pipe(_.right(U.double), _.ap(_.right(1)))({}), E.right(2)) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.right('a'), _.apFirst(_.right('b')))({}), E.right('a')) }) it('apFirstW', () => { const fa = _.right<{ readonly k: string }, 'Foo', string>('a') const fb = _.right<{ readonly x: number }, 'Bar', number>(4) U.deepStrictEqual(pipe(fa, _.apFirstW(fb))({ k: 'v', x: 1 }), E.right('a')) }) it('apSecond', () => { U.deepStrictEqual(pipe(_.right('a'), _.apSecond(_.right('b')))({}), E.right('b')) }) it('apSecondW', () => { const fa = _.right<{ readonly k: string }, 'Foo', string>('a') const fb = _.right<{ readonly x: number }, 'Bar', number>(4) U.deepStrictEqual(pipe(fa, _.apSecondW(fb))({ k: 'v', x: 1 }), E.right(4)) }) it('tap', () => { const f = (n: number) => _.right(n * 2) U.deepStrictEqual(pipe(_.right(1), _.tap(f))({}), E.right(1)) U.deepStrictEqual(_.tap(_.right(1), f)({}), E.right(1)) }) it('chainFirst', () => { const f = (n: number) => _.right(n * 2) U.deepStrictEqual(pipe(_.right(1), _.chainFirst(f))({}), E.right(1)) }) it('chainFirstW', () => { const f = (n: number) => _.right(n * 2) U.deepStrictEqual(pipe(_.right(1), _.chainFirstW(f))({}), E.right(1)) }) it('flatten', () => { U.deepStrictEqual(pipe(_.right(_.right('a')), _.flatten)({}), E.right('a')) }) type R1 = { readonly env1: unknown } type R2 = { readonly env2: unknown } type E1 = { readonly left1: unknown } type E2 = { readonly left2: unknown } it('flattenW', () => { U.deepStrictEqual( pipe(_.right>(_.right('a')), _.flattenW)({ env1: '', env2: '' }), E.right('a') ) }) it('mapLeft', () => { U.deepStrictEqual(pipe(_.right(1), _.mapLeft(S.size))({}), E.right(1)) U.deepStrictEqual(pipe(_.left('aa'), _.mapLeft(S.size))({}), E.left(2)) }) it('bimap', () => { U.deepStrictEqual(pipe(_.right(1), _.bimap(S.size, U.double))({}), E.right(2)) U.deepStrictEqual(pipe(_.left('aaa'), _.bimap(S.size, U.double))({}), E.left(3)) }) it('fromOption', () => { U.deepStrictEqual( pipe( O.none, _.fromOption(() => 'none') )({}), E.left('none') ) U.deepStrictEqual( pipe( O.some(1), _.fromOption(() => 'none') )({}), E.right(1) ) }) it('fromPredicate', () => { const gt2 = _.fromPredicate( (n: number) => n >= 2, (n) => `Invalid number ${n}` ) U.deepStrictEqual(gt2(3)({}), E.right(3)) U.deepStrictEqual(gt2(1)({}), E.left('Invalid number 1')) }) it('filterOrElse', () => { const e1 = pipe( _.right(12), _.filterOrElse( (n) => n > 10, () => 'a' ) )({}) U.deepStrictEqual(e1, E.right(12)) const e2 = pipe( _.right(7), _.filterOrElse( (n) => n > 10, () => 'a' ) )({}) U.deepStrictEqual(e2, E.left('a')) }) }) it('fold', () => { const fold = _.fold( (s: string) => R.of(s.length), (n: number) => R.of(n * 2) ) U.deepStrictEqual(fold(_.right(1))({}), 2) U.deepStrictEqual(fold(_.left('aaa'))({}), 3) }) it('getOrElse', () => { const getOrElse = _.getOrElse((s: string) => R.of(s.length)) U.deepStrictEqual(getOrElse(_.right(1))({}), 1) U.deepStrictEqual(getOrElse(_.left('aaa'))({}), 3) }) it('orElse', () => { const orElse = _.orElse((s: string) => (s.length > 2 ? _.right(1) : _.left(2))) U.deepStrictEqual(orElse(_.right(1))({}), E.right(1)) }) it('orElseW', () => { const orElse = _.orElseW((s: string) => (s.length > 2 ? _.right(1) : _.left(2))) U.deepStrictEqual(orElse(_.right(1))({}), E.right(1)) }) it('flatMapOption', () => { const f = _.flatMapOption( (n: number) => (n > 0 ? O.some(n) : O.none), () => 'a' ) U.deepStrictEqual(f(_.right(1))(undefined), E.right(1)) U.deepStrictEqual(f(_.right(-1))(undefined), E.left('a')) U.deepStrictEqual(f(_.left('b'))(undefined), E.left('b')) }) it('tapError', () => { const f = (s: string) => (s.length <= 1 ? _.right(true) : _.left(s + '!')) U.deepStrictEqual(pipe(_.right(1), _.tapError(f))({}), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), _.tapError(f))({}), E.left('a')) U.deepStrictEqual(pipe(_.left('aa'), _.tapError(f))({}), E.left('aa!')) U.deepStrictEqual(_.tapError(_.right(1), f)({}), E.right(1)) U.deepStrictEqual(_.tapError(_.left('a'), f)({}), E.left('a')) U.deepStrictEqual(_.tapError(_.left('aa'), f)({}), E.left('aa!')) }) it('orElseFirst', () => { const f = _.orElseFirst((s: string) => (s.length <= 1 ? _.right(true) : _.left(s + '!'))) U.deepStrictEqual(pipe(_.right(1), f)({}), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)({}), E.left('a')) U.deepStrictEqual(pipe(_.left('aa'), f)({}), E.left('aa!')) }) it('orElseFirstW', () => { const f = _.orElseFirstW((s: string) => (s.length <= 1 ? _.right(true) : _.left(s + '!'))) U.deepStrictEqual(pipe(_.right(1), f)({}), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)({}), E.left('a')) U.deepStrictEqual(pipe(_.left('aa'), f)({}), E.left('aa!')) }) it('orLeft', () => { const f = _.orLeft((s: string) => R.of(s + '!')) U.deepStrictEqual(pipe(_.right(1), f)({}), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)({}), E.left('a!')) }) it('orLeftW', () => { const f = _.orLeftW((s: string) => R.of(s + '!')) U.deepStrictEqual(pipe(_.right(1), f)({}), E.right(1)) U.deepStrictEqual(pipe(_.left('a'), f)({}), E.left('a!')) }) describe('getSemigroup', () => { it('concat', () => { const S = _.getSemigroup(N.SemigroupSum) const e1 = S.concat(_.left('a'), _.left('b'))({}) U.deepStrictEqual(e1, E.left('a')) const e2 = S.concat(_.left('a'), _.right(2))({}) U.deepStrictEqual(e2, E.right(2)) const e3 = S.concat(_.right(1), _.left('b'))({}) U.deepStrictEqual(e3, E.right(1)) const e4 = S.concat(_.right(1), _.right(2))({}) U.deepStrictEqual(e4, E.right(3)) }) }) describe('getApplyMonoid', () => { const M = _.getApplyMonoid(S.Monoid) it('concat (right)', () => { const x = M.concat(_.right('a'), _.right('b'))({}) return U.deepStrictEqual(x, E.right('ab')) }) it('concat (left)', () => { const x = M.concat(_.right('a'), _.left('b'))({}) return U.deepStrictEqual(x, E.left('b')) }) it('empty (right)', () => { const x = M.concat(_.right('a'), M.empty)({}) return U.deepStrictEqual(x, E.right('a')) }) it('empty (left)', () => { const x = M.concat(M.empty, _.right('a'))({}) return U.deepStrictEqual(x, E.right('a')) }) }) it('ask', () => { U.deepStrictEqual(_.ask()({}), E.right({})) }) it('asks', () => { U.deepStrictEqual(_.asks((r: { readonly a: number }) => r.a)({ a: 1 }), E.right(1)) }) it('local', () => { U.deepStrictEqual(_.local((n: number) => ({ a: n }))((r: { readonly a: number }) => E.right(r.a))(1), E.right(1)) }) it('getApplicativeReaderValidation', () => { const A = _.getApplicativeReaderValidation(S.Monoid) U.deepStrictEqual(Apply.sequenceT(A)(_.left('a'), _.left('b'))(null), E.left('ab')) const AV = _.getReaderValidation(S.Monoid) U.deepStrictEqual(Apply.sequenceT(AV)(_.left('a'), _.left('b'))(null), E.left('ab')) }) it('getAltReaderValidation', () => { const A = _.getAltReaderValidation(S.Monoid) U.deepStrictEqual(A.alt(_.left('a'), () => _.left('b'))(null), E.left('ab')) const AV = _.getReaderValidation(S.Monoid) U.deepStrictEqual(AV.alt(_.left('a'), () => _.left('b'))(null), E.left('ab')) }) it('flatMapEither', () => { const f = (s: string) => (s.length === 1 ? E.right(s.length) : E.left('b')) U.deepStrictEqual(pipe(_.right('a'), _.flatMapEither(f))({}), E.right(1)) U.deepStrictEqual(pipe(_.right('aa'), _.flatMapEither(f))({}), E.left('b')) }) it('chainEitherK', () => { const f = (s: string) => (s.length === 1 ? E.right(s.length) : E.left('b')) U.deepStrictEqual(pipe(_.right('a'), _.chainEitherK(f))({}), E.right(1)) U.deepStrictEqual(pipe(_.right('aa'), _.chainEitherK(f))({}), E.left('b')) }) it('do notation', () => { U.deepStrictEqual( pipe( _.right(1), _.bindTo('a'), _.bind('b', () => _.right('b')), _.let('c', ({ a, b }) => [a, b]) )(undefined), E.right({ a: 1, b: 'b', c: [1, 'b'] }) ) }) it('apS', () => { U.deepStrictEqual( pipe(_.right(1), _.bindTo('a'), _.apS('b', _.right('b')))(undefined), E.right({ a: 1, b: 'b' }) ) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(pipe(RA.empty, f)({}), E.right(RA.empty)) U.deepStrictEqual(pipe(input, f)({}), E.right(['a0', 'b1'])) U.deepStrictEqual(pipe(['a', ''], f)({}), E.left('e')) }) // old it('sequenceArray', () => { U.deepStrictEqual(pipe([_.right(1), _.right(2)], _.sequenceArray)(undefined), E.right([1, 2])) U.deepStrictEqual(pipe([_.right(1), _.left('a')], _.sequenceArray)(undefined), E.left('a')) }) }) it('getCompactable', () => { const C = _.getCompactable(S.Monoid) U.deepStrictEqual(C.compact(_.of(O.some('a')))({}), E.right('a')) }) it('getFilterable', () => { const F = _.getFilterable(S.Monoid) U.deepStrictEqual(F.filter(_.of('a'), (s) => s.length > 0)({}), E.right('a')) U.deepStrictEqual(F.filterMap(_.of('a'), (s) => (s.length > 0 ? O.some(s.length) : O.none))({}), E.right(1)) const s1 = F.partition(_.of('a'), (s) => s.length > 0) U.deepStrictEqual(left(s1)({}), E.left('')) U.deepStrictEqual(right(s1)({}), E.right('a')) const s2 = F.partitionMap(_.of('a'), (s) => (s.length > 0 ? E.right(s.length) : E.left(s))) U.deepStrictEqual(left(s2)({}), E.left('')) U.deepStrictEqual(right(s2)({}), E.right(1)) }) it('match', () => { const f = _.match( () => 'left', () => 'right' ) U.deepStrictEqual(f(_.right(1))({}), 'right') U.deepStrictEqual(f(_.left('a'))({}), 'left') }) it('matchE', () => { const f = _.matchE( () => R.of('left'), () => R.of('right') ) U.deepStrictEqual(f(_.right(1))({}), 'right') U.deepStrictEqual(f(_.left('a'))({}), 'left') }) it('fromReaderK', () => { const ma = _.fromReaderK( (n: number): R.Reader => (c) => n * c ) U.deepStrictEqual(ma(3)(2), E.right(6)) }) it('chainReaderK', () => { const f = _.chainReaderK( (n: number): R.Reader => (c) => n * c ) U.deepStrictEqual(pipe(_.right(3), f)(2), E.right(6)) U.deepStrictEqual(pipe(_.left('a'), f)(2), E.left('a')) }) it('chainReaderKW', () => { const f = _.chainReaderKW((): R.Reader => () => 2) U.deepStrictEqual(pipe(_.right<{}, never, number>(3), f)({}), E.right(2)) }) it('chainFirstReaderK', () => { const f = _.chainFirstReaderK( (n: number): R.Reader => (c) => n * c ) U.deepStrictEqual(pipe(_.right(3), f)(2), E.right(3)) U.deepStrictEqual(pipe(_.left('a'), f)(2), E.left('a')) }) it('chainFirstReaderKW', () => { const f = _.chainFirstReaderKW((): R.Reader => () => 2) U.deepStrictEqual(pipe(_.right<{}, never, number>(3), f)({}), E.right(3)) }) it('tapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(pipe(_.right('a'), _.tapEither(f))({}), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(pipe(_.right('a'), _.tapEither(g))({}), E.left(1)) }) it('chainFirstEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(pipe(_.right('a'), _.chainFirstEitherK(f))({}), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(pipe(_.right('a'), _.chainFirstEitherK(g))({}), E.left(1)) }) it('as', () => { U.deepStrictEqual(pipe(_.right('a'), _.as('b'))(undefined), E.right('b')) U.deepStrictEqual(_.as(_.of('a'), 'b')(undefined), E.right('b')) U.deepStrictEqual(_.as(_.left('error'), 'b')(undefined), E.left('error')) }) it('asUnit', () => { U.deepStrictEqual(pipe(_.of('a'), _.asUnit)(undefined), E.of(undefined)) }) it('tapReader', () => { U.deepStrictEqual(_.tapReader(_.of(1), () => R.of(2))({}), E.of(1)) }) it('flatMapReader', () => { U.deepStrictEqual(_.flatMapReader(_.of(1), () => R.of(2))({}), E.of(2)) }) }) ================================================ FILE: test/ReaderIO.ts ================================================ import { pipe } from '../src/function' import * as I from '../src/IO' import * as R from '../src/Reader' import * as _ from '../src/ReaderIO' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import * as S from '../src/string' import * as U from './util' describe('ReaderIO', () => { // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- it('map', () => { U.deepStrictEqual(pipe(_.of(1), _.map(U.double))({})(), 2) }) it('ap', () => { U.deepStrictEqual(pipe(_.of(U.double), _.ap(_.of(1)))({})(), 2) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.of('a'), _.apFirst(_.of('b')))({})(), 'a') }) it('apSecond', () => { U.deepStrictEqual(pipe(_.of('a'), _.apSecond(_.of('b')))({})(), 'b') }) it('flatMap', () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(pipe(_.of('foo'), _.flatMap(f))({})(), 3) U.deepStrictEqual(_.flatMap(_.of('foo'), f)({})(), 3) }) it('chain', () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(pipe(_.of('foo'), _.chain(f))({})(), 3) U.deepStrictEqual(_.Monad.chain(_.of('foo'), f)({})(), 3) }) it('tap', () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(pipe(_.of('foo'), _.tap(f))({})(), 'foo') U.deepStrictEqual(_.tap(_.of('foo'), f)({})(), 'foo') }) it('chainFirst', () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(pipe(_.of('foo'), _.chainFirst(f))({})(), 'foo') }) it('chainFirstW', () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(pipe(_.of('foo'), _.chainFirstW(f))({})(), 'foo') }) it('flatten', () => { U.deepStrictEqual(pipe(_.of(_.of('a')), _.flatten)({})(), 'a') }) type R1 = { readonly env1: unknown } type R2 = { readonly env2: unknown } it('flattenW', () => { U.deepStrictEqual(pipe(_.of>(_.of('a')), _.flattenW)({ env1: '', env2: '' })(), 'a') }) it('of', () => { U.deepStrictEqual(_.fromReader(R.of(1))({})(), 1) }) it('fromIO', async () => { U.deepStrictEqual(_.fromIO(() => 1)({})(), 1) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('ask', () => { return U.deepStrictEqual(_.ask()(1)(), 1) }) it('asks', () => { return U.deepStrictEqual(_.asks((s: string) => s.length)('foo')(), 3) }) it('fromReader', () => { U.deepStrictEqual(_.fromReader(R.of(1))({})(), 1) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('local', () => { U.deepStrictEqual( pipe( _.asks((n: number) => n + 1), _.local(S.size) )('aaa')(), 4 ) }) it('chainIOK', () => { const f = (s: string) => I.of(s.length) U.deepStrictEqual(pipe(_.of('a'), _.chainIOK(f))(undefined)(), 1) }) it('fromIOK', () => { const f = _.fromIOK((s: string) => I.of(s.length)) U.deepStrictEqual(pipe(_.of('a'), _.chain(f))({})(), 1) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')) )(undefined)(), { a: 1, b: 'b' } ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b')))(undefined)(), { a: 1, b: 'b' }) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => _.of(a + i)) U.deepStrictEqual(pipe(RA.empty, f)(undefined)(), RA.empty) U.deepStrictEqual(pipe(input, f)(undefined)(), ['a0', 'b1']) }) // old it('sequenceArray', () => { // tslint:disable-next-line: readonly-array const log: Array = [] const append = (n: number): _.ReaderIO => () => () => { log.push(n) return n } // tslint:disable-next-line: deprecation U.deepStrictEqual(pipe([append(1), append(2)], _.sequenceArray)(undefined)(), [1, 2]) U.deepStrictEqual(log, [1, 2]) }) }) it('tapIO', () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(pipe(_.ask(), _.tapIO(add))(1)(), 1) U.deepStrictEqual(ref, [1]) }) it('as', () => { U.deepStrictEqual(pipe(_.of('a'), _.as('b'))('c')(), 'b') }) it('asUnit', () => { U.deepStrictEqual(pipe(_.of('a'), _.asUnit)('b')(), undefined) }) it('tapReader', () => { U.deepStrictEqual(_.tapReader(_.of(1), () => R.of(2))({})(), 1) }) it('flatMapIO', () => { U.deepStrictEqual( pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(undefined)(), 2 ) }) it('flatMapReader', () => { U.deepStrictEqual(_.flatMapReader(_.of(1), () => R.of(2))(undefined)(), 2) }) }) ================================================ FILE: test/ReaderT.ts ================================================ import * as E from '../src/Either' import * as IO from '../src/IO' import * as _ from '../src/ReaderT' import * as TE from '../src/TaskEither' import * as U from './util' describe('ReaderT', () => { it('fromNaturalTransformation', async () => { const fromReaderIO = _.fromNaturalTransformation<'IO', 'TaskEither'>(TE.fromIO) const f = (s: string): IO.IO => IO.of(s.length) const fa = fromReaderIO(f) U.deepStrictEqual(await fa('a')(), E.right(1)) }) }) ================================================ FILE: test/ReaderTask.ts ================================================ import { pipe, SK } from '../src/function' import * as I from '../src/IO' import { monoidString } from '../src/Monoid' import * as R from '../src/Reader' import * as RIO from '../src/ReaderIO' import * as _ from '../src/ReaderTask' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { semigroupString } from '../src/Semigroup' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' describe('ReaderTask', () => { // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- it('map', async () => { U.deepStrictEqual(await pipe(_.of(1), _.map(U.double))({})(), 2) }) it('ap', async () => { U.deepStrictEqual(await pipe(_.of(U.double), _.ap(_.of(1)))({})(), 2) }) it('apFirst', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.apFirst(_.of('b')))({})(), 'a') }) it('apFirstW', async () => { const fa = _.of<{ readonly k: string }, string>('a') const fb = _.of<{ readonly x: number }, boolean>(true) U.deepStrictEqual(await pipe(fa, _.apFirstW(fb))({ k: 'v', x: 42 })(), 'a') }) it('apSecond', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.apSecond(_.of('b')))({})(), 'b') }) it('apSecondW', async () => { const fa = _.of<{ readonly k: string }, string>('a') const fb = _.of<{ readonly x: number }, boolean>(true) U.deepStrictEqual(await pipe(fa, _.apSecondW(fb))({ k: 'v', x: 42 })(), true) }) it('flatMap', async () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(await pipe(_.of('foo'), _.flatMap(f))({})(), 3) U.deepStrictEqual(await _.flatMap(_.of('foo'), f)({})(), 3) }) it('chain', async () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(await pipe(_.of('foo'), _.chain(f))({})(), 3) U.deepStrictEqual(await _.Monad.chain(_.of('foo'), f)({})(), 3) }) it('tap', async () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(await pipe(_.of('foo'), _.tap(f))({})(), 'foo') U.deepStrictEqual(await _.tap(_.of('foo'), f)({})(), 'foo') }) it('chainFirst', async () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(await pipe(_.of('foo'), _.chainFirst(f))({})(), 'foo') }) it('chainFirstW', async () => { const f = (a: string) => _.of(a.length) U.deepStrictEqual(await pipe(_.of('foo'), _.chainFirstW(f))({})(), 'foo') }) it('flatten', async () => { U.deepStrictEqual(await pipe(_.of(_.of('a')), _.flatten)({})(), 'a') }) type R1 = { readonly env1: unknown } type R2 = { readonly env2: unknown } it('flattenW', async () => { U.deepStrictEqual(await pipe(_.of>(_.of('a')), _.flattenW)({ env1: '', env2: '' })(), 'a') }) it('of', async () => { U.deepStrictEqual(await _.fromReader(R.of(1))({})(), 1) }) it('fromIO', async () => { U.deepStrictEqual(await _.fromIO(() => 1)({})(), 1) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('ask', async () => { return U.deepStrictEqual(await _.ask()(1)(), 1) }) it('asks', async () => { return U.deepStrictEqual(await _.asks((s: string) => s.length)('foo')(), 3) }) it('fromTask', async () => { U.deepStrictEqual(await _.fromTask(T.of(1))({})(), 1) }) it('fromReader', async () => { U.deepStrictEqual(await _.fromReader(R.of(1))({})(), 1) }) it('fromReaderIO', async () => { U.deepStrictEqual(await _.fromReaderIO(RIO.of(1))({})(), 1) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('local', async () => { U.deepStrictEqual( await pipe( _.asks((n: number) => n + 1), _.local(S.size) )('aaa')(), 4 ) }) it('chainIOK', async () => { const f = (s: string) => I.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainIOK(f))(undefined)(), 1) }) it('chainTaskK', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainTaskK(f))(undefined)(), 1) }) it('flatMapTask', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.flatMapTask(f))(undefined)(), 1) }) it('chainFirstTaskK', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainFirstTaskK(f))(undefined)(), 'a') }) it('fromIOK', async () => { const f = _.fromIOK((s: string) => I.of(s.length)) U.deepStrictEqual(await pipe(_.of('a'), _.chain(f))({})(), 1) }) it('fromTaskK', async () => { const f = _.fromTaskK((s: string) => T.of(s.length)) U.deepStrictEqual(await pipe(_.of('a'), _.chain(f))({})(), 1) }) it('fromReaderIOK', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await _.fromReaderIOK(f)('a')(undefined)(), 1) }) it('chainReaderIOKW', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainReaderIOKW(f))({})(), 1) }) it('chainReaderIOK', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainReaderIOK(f))(undefined)(), 1) }) it('chainFirstReaderIOKW', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainFirstReaderIOKW(f))({})(), 'a') }) it('chainFirstReaderIOK', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainFirstReaderIOK(f))({})(), 'a') }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('getSemigroup', async () => { const M = _.getSemigroup(semigroupString) U.deepStrictEqual(await M.concat(_.of('a'), _.of('b'))({})(), 'ab') }) it('getMonoid', async () => { const M = _.getMonoid(monoidString) U.deepStrictEqual(await M.concat(_.of('a'), M.empty)({})(), 'a') U.deepStrictEqual(await M.concat(M.empty, _.of('b'))({})(), 'b') U.deepStrictEqual(await M.concat(_.of('a'), _.of('b'))({})(), 'ab') }) it('applicativeTaskEitherSeq', async () => { await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa(null)()) }) it('applicativeTaskEitherPar', async () => { await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa(null)()) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('do notation', async () => { U.deepStrictEqual( await pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) )(undefined)(), { a: 1, b: 'b', c: [1, 'b'] } ) }) it('apS', async () => { U.deepStrictEqual(await pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b')))(undefined)(), { a: 1, b: 'b' }) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => _.of(a + i)) U.deepStrictEqual(await pipe(RA.empty, f)(undefined)(), RA.empty) U.deepStrictEqual(await pipe(input, f)(undefined)(), ['a0', 'b1']) }) it('sequenceReadonlyArray', async () => { U.deepStrictEqual(await pipe(RA.empty, _.traverseReadonlyArrayWithIndex(SK))(undefined)(), RA.empty) const log: Array = [] const append = (n: number): _.ReaderTask => _.fromTask( T.delay(n % 2 === 0 ? 50 : 100)( T.fromIO(() => { log.push(n) return n }) ) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.traverseReadonlyArrayWithIndex(SK))(undefined)(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 2, 1, 3]) }) it('sequenceReadonlyArraySeq', async () => { U.deepStrictEqual(await pipe(RA.empty, _.traverseReadonlyArrayWithIndexSeq(SK))(undefined)(), RA.empty) const log: Array = [] const append = (n: number): _.ReaderTask => _.fromTask( T.delay(n % 2 === 0 ? 50 : 100)( T.fromIO(() => { log.push(n) return n }) ) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.traverseReadonlyArrayWithIndexSeq(SK))(undefined)(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 1, 2, 3]) }) // old it('sequenceArray', async () => { const log: Array = [] const append = (n: number): _.ReaderTask => _.fromTask( T.delay(n % 2 === 0 ? 50 : 100)( T.fromIO(() => { log.push(n) return n }) ) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.sequenceArray)(undefined)(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 2, 1, 3]) }) it('sequenceSeqArray', async () => { const log: Array = [] const append = (n: number): _.ReaderTask => _.fromTask( T.delay(n % 2 === 0 ? 50 : 100)( T.fromIO(() => { log.push(n) return n }) ) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.sequenceSeqArray)(undefined)(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 1, 2, 3]) }) }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(await pipe(_.ask(), _.tapIO(add))(1)(), 1) U.deepStrictEqual(ref, [1]) }) it('tapTask', async () => { const ref: Array = [] const add = (value: number) => T.fromIO(() => ref.push(value)) U.deepStrictEqual(await pipe(_.ask(), _.tapTask(add))(1)(), 1) U.deepStrictEqual(ref, [1]) }) it('as', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.as('b'))('c')(), 'b') }) it('asUnit', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.asUnit)('b')(), undefined) }) it('tapReader', async () => { U.deepStrictEqual(await _.tapReader(_.of(1), () => R.of(2))({})(), 1) }) it('tapReaderIO', async () => { U.deepStrictEqual(await _.tapReaderIO(_.of(1), () => RIO.of(2))({})(), 1) }) it('flatMapIO', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(undefined)(), 2 ) }) it('flatMapReader', async () => { U.deepStrictEqual(await _.flatMapReader(_.of(1), () => R.of(2))(undefined)(), 2) }) it('flatMapReaderIO', async () => { U.deepStrictEqual(await _.flatMapReaderIO(_.of(1), () => RIO.of(2))(undefined)(), 2) }) }) ================================================ FILE: test/ReaderTaskEither.ts ================================================ import { sequenceT } from '../src/Apply' import * as E from '../src/Either' import { constVoid, flow, pipe, SK } from '../src/function' import * as I from '../src/IO' import * as IE from '../src/IOEither' import * as N from '../src/number' import * as O from '../src/Option' import * as R from '../src/Reader' import * as RE from '../src/ReaderEither' import * as RIO from '../src/ReaderIO' import * as RT from '../src/ReaderTask' import * as _ from '../src/ReaderTaskEither' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { left, right } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as TE from '../src/TaskEither' import * as U from './util' describe('ReaderTaskEither', () => { describe('pipeables', () => { it('map', async () => { U.deepStrictEqual(await pipe(_.right(1), _.map(U.double))({})(), E.right(2)) }) it('ap', async () => { U.deepStrictEqual(await pipe(_.right(U.double), _.ap(_.right(1)))({})(), E.right(2)) }) it('apFirst', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.apFirst(_.right('b')))({})(), E.right('a')) }) it('apFirstW', async () => { const fa = _.right<{ readonly k: string }, 'Foo', string>('a') const fb = _.right<{ readonly x: number }, 'Bar', boolean>(true) U.deepStrictEqual(await pipe(fa, _.apFirstW(fb))({ k: 'v', x: 42 })(), E.right('a')) }) it('apSecond', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.apSecond(_.right('b')))({})(), E.right('b')) }) it('apSecondW', async () => { const fa = _.right<{ readonly k: string }, 'Foo', string>('a') const fb = _.right<{ readonly x: number }, 'Bar', boolean>(true) U.deepStrictEqual(await pipe(fa, _.apSecondW(fb))({ k: 'v', x: 42 })(), E.right(true)) }) it('flatMap', async () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('b')) U.deepStrictEqual(await pipe(_.right('aaa'), _.flatMap(f))({})(), E.right(3)) U.deepStrictEqual(await _.flatMap(_.right('a'), f)({})(), E.left('b')) }) it('chain', async () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('b')) U.deepStrictEqual(await pipe(_.right('aaa'), _.chain(f))({})(), E.right(3)) U.deepStrictEqual(await pipe(_.right('a'), _.chain(f))({})(), E.left('b')) }) it('tap', async () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('b')) U.deepStrictEqual(await pipe(_.right('aaa'), _.tap(f))({})(), E.right('aaa')) U.deepStrictEqual(await _.tap(_.right('aaa'), f)({})(), E.right('aaa')) }) it('chainFirst', async () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('b')) U.deepStrictEqual(await pipe(_.right('aaa'), _.chainFirst(f))({})(), E.right('aaa')) }) it('chainFirstW', async () => { const f = (a: string) => (a.length > 2 ? _.right(a.length) : _.left('b')) U.deepStrictEqual(await pipe(_.right('aaa'), _.chainFirstW(f))({})(), E.right('aaa')) }) it('flatten', async () => { U.deepStrictEqual(await pipe(_.right(_.right('a')), _.flatten)({})(), E.right('a')) }) type R1 = { readonly env1: unknown } type R2 = { readonly env2: unknown } type E1 = { readonly left1: unknown } type E2 = { readonly left2: unknown } it('flattenW', async () => { U.deepStrictEqual( await pipe( _.right>(_.right('a')), _.flattenW )({ env1: '', env2: '' })(), E.right('a') ) }) it('bimap', async () => { const f = (s: string): number => s.length const g = (n: number): boolean => n > 2 U.deepStrictEqual(await pipe(_.right(1), _.bimap(f, g))({})(), E.right(false)) U.deepStrictEqual(await pipe(_.left('error'), _.bimap(f, g))({})(), E.left(5)) }) it('mapLeft', async () => { U.deepStrictEqual(await pipe(_.right(1), _.mapLeft(S.size))({})(), E.right(1)) U.deepStrictEqual(await pipe(_.left('err'), _.mapLeft(S.size))({})(), E.left(3)) }) it('alt', async () => { U.deepStrictEqual( await pipe( _.right(1), _.alt(() => _.right(2)) )({})(), E.right(1) ) U.deepStrictEqual( await pipe( _.left('a'), _.alt(() => _.right(2)) )({})(), E.right(2) ) U.deepStrictEqual( await pipe( _.left('a'), _.alt(() => _.left('b')) )({})(), E.left('b') ) }) it('fromPredicate', async () => { const predicate = (n: number) => n >= 2 const gt2 = _.fromPredicate(predicate, (n) => `Invalid number ${n}`) const refinement = (u: string | number): u is number => typeof u === 'number' const isNumber = _.fromPredicate(refinement, (u) => `Invalid number ${String(u)}`) U.deepStrictEqual(await gt2(3)({})(), E.right(3)) U.deepStrictEqual(await gt2(1)({})(), E.left('Invalid number 1')) U.deepStrictEqual(await isNumber(4)({})(), E.right(4)) }) it('fromEither', async () => { U.deepStrictEqual(await _.fromEither(E.right(1))({})(), E.right(1)) U.deepStrictEqual(await _.fromEither(E.left('a'))({})(), E.left('a')) }) it('fromOption', async () => { U.deepStrictEqual(await _.fromOption(() => 'none')(O.none)({})(), E.left('none')) U.deepStrictEqual(await _.fromOption(() => 'none')(O.some(1))({})(), E.right(1)) }) it('filterOrElse', async () => { U.deepStrictEqual( await pipe( _.right(12), _.filterOrElse( (n) => n > 10, () => 'a' ) )({})(), E.right(12) ) U.deepStrictEqual( await pipe( _.right(8), _.filterOrElse( (n) => n > 10, () => 'a' ) )({})(), E.left('a') ) }) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('applicativeReaderTaskEitherSeq', async () => { await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa(null)()) }) it('applicativeReaderTaskEitherPar', async () => { await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa(null)()) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('ask', async () => { return U.deepStrictEqual(await _.ask()(1)(), E.right(1)) }) it('asks', async () => { return U.deepStrictEqual(await _.asks((s: string) => s.length)('foo')(), E.right(3)) }) it('local', async () => { U.deepStrictEqual( await pipe( _.asks((n: number) => n + 1), _.local(S.size) )('aaa')(), E.right(4) ) }) it('leftTask', async () => { U.deepStrictEqual(await _.leftTask(T.of(1))({})(), E.left(1)) }) it('rightTask', async () => { U.deepStrictEqual(await _.rightTask(T.of(1))({})(), E.right(1)) }) it('leftReaderTask', async () => { U.deepStrictEqual(await _.leftReaderTask(RT.of(1))({})(), E.left(1)) }) it('rightReaderTask', async () => { U.deepStrictEqual(await _.rightReaderTask(RT.of(1))({})(), E.right(1)) }) it('rightReader', async () => { U.deepStrictEqual(await _.rightReader(R.of(1))({})(), E.right(1)) }) it('leftReader', async () => { U.deepStrictEqual(await _.leftReader(R.of(1))({})(), E.left(1)) }) it('fromTaskEither', async () => { U.deepStrictEqual(await _.fromTaskEither(TE.of(1))({})(), E.right(1)) }) it('leftIO', async () => { U.deepStrictEqual(await _.leftIO(I.of(1))({})(), E.left(1)) }) it('rightReaderIO', async () => { U.deepStrictEqual(await _.rightReaderIO(RIO.of(1))({})(), E.right(1)) }) it('leftReaderIO', async () => { U.deepStrictEqual(await _.leftReaderIO(RIO.of(1))({})(), E.left(1)) }) it('fromIOEither', async () => { U.deepStrictEqual(await _.fromIOEither(() => E.right(1))({})(), E.right(1)) U.deepStrictEqual(await _.fromIOEither(() => E.left('error'))({})(), E.left('error')) }) it('fold', async () => { const fold = _.fold( (l: string) => R.of(T.of(l.length)), (a: number) => R.of(T.of(a * 2)) ) U.deepStrictEqual(await fold(_.right(1))({})(), 2) U.deepStrictEqual(await fold(_.left('err'))({})(), 3) }) it('getOrElse', async () => { U.deepStrictEqual( await pipe( _.right(1), _.getOrElse((l: string) => R.of(T.of(l.length))) )({})(), 1 ) U.deepStrictEqual( await pipe( _.left('err'), _.getOrElse((l: string) => R.of(T.of(l.length))) )({})(), 3 ) }) it('orElse', async () => { U.deepStrictEqual( await pipe( _.right(1), _.orElse((s: string) => _.right(s.length)) )({})(), E.right(1) ) U.deepStrictEqual( await pipe( _.left('error'), _.orElse((s) => _.right(s.length)) )({})(), E.right(5) ) }) it('orElseW', async () => { U.deepStrictEqual( await pipe( _.right(1), _.orElseW((s: string) => _.right(s.length)) )({})(), E.right(1) ) U.deepStrictEqual( await pipe( _.left('error'), _.orElseW((s) => _.right(s.length)) )({})(), E.right(5) ) }) it('tapError', async () => { const f = (s: string) => (s.length <= 1 ? _.right(true) : _.left(s + '!')) U.deepStrictEqual(await pipe(_.right(1), _.tapError(f))({})(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), _.tapError(f))({})(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), _.tapError(f))({})(), E.left('aa!')) U.deepStrictEqual(await pipe(_.tapError(_.right(1), f))({})(), E.right(1)) U.deepStrictEqual(await pipe(_.tapError(_.left('a'), f))({})(), E.left('a')) U.deepStrictEqual(await pipe(_.tapError(_.left('aa'), f))({})(), E.left('aa!')) }) it('orElseFirst', async () => { const f = _.orElseFirst((s: string) => (s.length <= 1 ? _.right(true) : _.left(s + '!'))) U.deepStrictEqual(await pipe(_.right(1), f)({})(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)({})(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), f)({})(), E.left('aa!')) }) it('orElseFirstW', async () => { const f = _.orElseFirstW((s: string) => (s.length <= 1 ? _.right(true) : _.left(s + '!'))) U.deepStrictEqual(await pipe(_.right(1), f)({})(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)({})(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), f)({})(), E.left('aa!')) }) it('orLeft', async () => { const f = _.orLeft((s: string) => RT.of(s + '!')) U.deepStrictEqual(await pipe(_.right(1), f)({})(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)({})(), E.left('a!')) }) it('orLeftW', async () => { const f = _.orLeftW((s: string) => RT.of(s + '!')) U.deepStrictEqual(await pipe(_.right(1), f)({})(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)({})(), E.left('a!')) }) describe('MonadIO', () => { it('fromIO', async () => { U.deepStrictEqual(await _.fromIO(() => 1)({})(), E.right(1)) }) }) it('swap', async () => { U.deepStrictEqual(await _.swap(_.right(1))({})(), E.left(1)) U.deepStrictEqual(await _.swap(_.left('a'))({})(), E.right('a')) }) describe('getSemigroup', () => { it('concat', async () => { const S = _.getSemigroup(N.SemigroupSum) U.deepStrictEqual(await S.concat(_.left('a'), _.left('b'))({})(), E.left('a')) U.deepStrictEqual(await S.concat(_.left('a'), _.right(2))({})(), E.right(2)) U.deepStrictEqual(await S.concat(_.right(1), _.left('b'))({})(), E.right(1)) U.deepStrictEqual(await S.concat(_.right(1), _.right(2))({})(), E.right(3)) }) }) it('getApplyMonoid', async () => { const M = _.getApplyMonoid(N.MonoidSum) U.deepStrictEqual(await M.concat(_.right(1), _.right(2))({})(), E.right(3)) U.deepStrictEqual(await M.concat(_.right(1), _.left('b'))({})(), E.left('b')) U.deepStrictEqual(await M.concat(_.right(1), M.empty)({})(), E.right(1)) U.deepStrictEqual(await M.concat(M.empty, _.right(1))({})(), E.right(1)) }) it('fromReaderEither', async () => { U.deepStrictEqual(await _.fromReaderEither(RE.left('a'))({})(), E.left('a')) U.deepStrictEqual(await _.fromReaderEither(RE.right(1))({})(), E.right(1)) }) it('getApplicativeReaderTaskValidation', async () => { const A = _.getApplicativeReaderTaskValidation(T.ApplicativePar, S.Semigroup) U.deepStrictEqual(await sequenceT(A)(_.left('a'), _.left('b'))(null)(), E.left('ab')) const AV = _.getReaderTaskValidation(S.Semigroup) U.deepStrictEqual(await sequenceT(AV)(_.left('a'), _.left('b'))(null)(), E.left('ab')) }) it('getAltReaderTaskValidation', async () => { const A = _.getAltReaderTaskValidation(S.Semigroup) U.deepStrictEqual(await A.alt(_.left('a'), () => _.left('b'))(null)(), E.left('ab')) const AV = _.getReaderTaskValidation(S.Semigroup) U.deepStrictEqual(await AV.alt(_.left('a'), () => _.left('b'))(null)(), E.left('ab')) }) describe('bracket', () => { let log: Array = [] const acquireFailure = _.left('acquire failure') const acquireSuccess = _.right({ res: 'acquire success' }) const useSuccess = () => _.right('use success') const useFailure = () => _.left('use failure') const releaseSuccess = () => _.fromIO(() => { log.push('release success') }) const releaseFailure = () => _.left('release failure') beforeEach(() => { log = [] }) it('should return the acquire error if acquire fails', async () => { U.deepStrictEqual( await _.bracket(acquireFailure, useSuccess, releaseSuccess)(undefined)(), E.left('acquire failure') ) }) it('body and release must not be called if acquire fails', async () => { await _.bracket(acquireFailure, useSuccess, releaseSuccess)(undefined)() U.deepStrictEqual(log, []) }) it('should return the use error if use fails and release does not', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useFailure, releaseSuccess)(undefined)(), E.left('use failure')) }) it('should return the release error if both use and release fail', async () => { U.deepStrictEqual( await _.bracket(acquireSuccess, useFailure, releaseFailure)(undefined)(), E.left('release failure') ) }) it('release must be called if the body returns', async () => { await _.bracket(acquireSuccess, useSuccess, releaseSuccess)(undefined)() U.deepStrictEqual(log, ['release success']) }) it('release must be called if the body throws', async () => { await _.bracket(acquireSuccess, useFailure, releaseSuccess)(undefined)() U.deepStrictEqual(log, ['release success']) }) it('should return the release error if release fails', async () => { U.deepStrictEqual( await _.bracket(acquireSuccess, useSuccess, releaseFailure)(undefined)(), E.left('release failure') ) }) }) it('bracketW', async () => { const acquire = _.right<{ readonly a: string }, string, string>('string') const use = (_a: string) => _.right<{ readonly b: number }, number, string>('test') const release = (_a: string, _e: E.Either) => _.right<{ readonly c: boolean }, Error, void>(constVoid()) const res = await _.bracketW( acquire, use, release )({ a: 'string', b: 5, c: true })() U.deepStrictEqual(res, E.right('test')) }) it('flatMapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.flatMapEither(f))(undefined)(), E.right(1)) }) it('chainEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainEitherK(f))(undefined)(), E.right(1)) }) it('tapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right<{}, number, string>('a'), _.tapEither(f))({})(), E.right('a')) }) it('chainFirstEitherKW', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right<{}, number, string>('a'), _.chainFirstEitherKW(f))({})(), E.right('a')) }) it('chainIOEitherK', async () => { const f = (s: string) => IE.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainIOEitherK(f))(undefined)(), E.right(1)) }) it('chainTaskEitherK', async () => { const f = (s: string) => TE.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainTaskEitherK(f))(undefined)(), E.right(1)) }) it('flatMapTaskEither', async () => { const f = (s: string) => TE.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.flatMapTaskEither(f))(undefined)(), E.right(1)) }) it('chainFirstTaskEitherKW', async () => { const f = (s: string) => TE.right(s.length) U.deepStrictEqual(await pipe(_.right<{}, number, string>('a'), _.chainFirstTaskEitherKW(f))({})(), E.right('a')) }) it('chainReaderTaskK', async () => { const f = flow(S.size, RT.of) U.deepStrictEqual(await pipe(_.right('a'), _.chainReaderTaskK(f))(undefined)(), E.right(1)) }) it('flatMapReaderTask', async () => { const f = flow(S.size, RT.of) U.deepStrictEqual(await pipe(_.right('a'), _.flatMapReaderTask(f))(undefined)(), E.right(1)) }) it('chainReaderTaskKW', async () => { const f = flow(S.size, RT.of) U.deepStrictEqual(await pipe(_.right<{}, never, string>('a'), _.chainReaderTaskKW(f))({})(), E.right(1)) }) it('chainFirstReaderTaskKW', async () => { const f = flow(S.size, RT.of) U.deepStrictEqual(await pipe(_.right<{}, never, string>('a'), _.chainFirstReaderTaskKW(f))({})(), E.right('a')) }) it('chainReaderEitherKW', async () => { const f = (s: string) => RE.right(s.length) U.deepStrictEqual(await pipe(_.right<{}, never, string>('a'), _.chainReaderEitherKW(f))({})(), E.right(1)) }) it('chainFirstReaderEitherKW', async () => { const f = (s: string) => RE.right(s.length) U.deepStrictEqual(await pipe(_.right<{}, never, string>('a'), _.chainFirstReaderEitherKW(f))({})(), E.right('a')) }) it('fromReaderIOK', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await _.fromReaderIOK(f)('a')(undefined)(), E.right(1)) }) it('chainReaderIOKW', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainReaderIOKW(f))({})(), E.right(1)) }) it('chainReaderIOK', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainReaderIOK(f))(undefined)(), E.right(1)) }) it('chainFirstReaderIOKW', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainFirstReaderIOKW(f))({})(), E.right('a')) }) it('chainFirstReaderIOK', async () => { const f = (s: string) => RIO.of(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainFirstReaderIOK(f))({})(), E.right('a')) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('do notation', async () => { U.deepStrictEqual( await pipe( _.right(1), _.bindTo('a'), _.bind('b', () => _.right('b')), _.let('c', ({ a, b }) => [a, b]) )(undefined)(), E.right({ a: 1, b: 'b', c: [1, 'b'] }) ) }) it('apS', async () => { U.deepStrictEqual( await pipe(_.right(1), _.bindTo('a'), _.apS('b', _.right('b')))(undefined)(), E.right({ a: 1, b: 'b' }) ) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(undefined)(), E.right(RA.empty)) U.deepStrictEqual(await pipe(input, f)(undefined)(), E.right(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(undefined)(), E.left('e')) }) it('traverseReadonlyArrayWithIndexSeq', async () => { const f = _.traverseReadonlyArrayWithIndexSeq((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(undefined)(), E.right(RA.empty)) U.deepStrictEqual(await pipe(input, f)(undefined)(), E.right(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(undefined)(), E.left('e')) }) it('sequenceReadonlyArray', async () => { const log: Array = [] const right = (n: number): _.ReaderTaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.ReaderTaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual( await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndex(SK))(undefined)(), E.right([1, 2]) ) U.deepStrictEqual( await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndex(SK))(undefined)(), E.left('a') ) U.deepStrictEqual( await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndex(SK))(undefined)(), E.left('b') ) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceReadonlyArraySeq', async () => { const log: Array = [] const right = (n: number): _.ReaderTaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.ReaderTaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual( await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndexSeq(SK))(undefined)(), E.right([1, 2]) ) U.deepStrictEqual( await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndexSeq(SK))(undefined)(), E.left('a') ) U.deepStrictEqual( await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndexSeq(SK))(undefined)(), E.left('b') ) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) // old it('sequenceArray', async () => { const log: Array = [] const right = (n: number): _.ReaderTaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.ReaderTaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.sequenceArray)(undefined)(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceArray)(undefined)(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceArray)(undefined)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceSeqArray', async () => { const log: Array = [] const right = (n: number): _.ReaderTaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.ReaderTaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.sequenceSeqArray)(undefined)(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceSeqArray)(undefined)(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceSeqArray)(undefined)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) }) it('getCompactable', async () => { const C = _.getCompactable(S.Monoid) U.deepStrictEqual(await C.compact(_.of(O.some('a')))({})(), E.right('a')) }) it('getFilterable', async () => { const F = _.getFilterable(S.Monoid) U.deepStrictEqual(await F.filter(_.of('a'), (s) => s.length > 0)({})(), E.right('a')) U.deepStrictEqual(await F.filterMap(_.of('a'), (s) => (s.length > 0 ? O.some(s.length) : O.none))({})(), E.right(1)) const s1 = F.partition(_.of('a'), (s) => s.length > 0) U.deepStrictEqual(await left(s1)({})(), E.left('')) U.deepStrictEqual(await right(s1)({})(), E.right('a')) const s2 = F.partitionMap(_.of('a'), (s) => (s.length > 0 ? E.right(s.length) : E.left(s))) U.deepStrictEqual(await left(s2)({})(), E.left('')) U.deepStrictEqual(await right(s2)({})(), E.right(1)) }) it('match', async () => { const f = _.match( () => 'left', () => 'right' ) U.deepStrictEqual(await f(_.right(1))({})(), 'right') U.deepStrictEqual(await f(_.left(''))({})(), 'left') }) it('matchE', async () => { const f = _.matchE( () => RT.of('left'), () => RT.of('right') ) U.deepStrictEqual(await f(_.right(1))({})(), 'right') U.deepStrictEqual(await f(_.left(''))({})(), 'left') }) it('fromNullable', async () => { const testNullable = _.fromNullable('foo') U.deepStrictEqual(await testNullable(1)(undefined)(), E.right(1)) U.deepStrictEqual(await testNullable(null)(undefined)(), E.left('foo')) U.deepStrictEqual(await testNullable(undefined)(undefined)(), E.left('foo')) }) it('fromNullableK', async () => { const f = _.fromNullableK('foo')((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(await f(1)(undefined)(), E.right(1)) U.deepStrictEqual(await f(0)(undefined)(), E.left('foo')) U.deepStrictEqual(await f(-1)(undefined)(), E.left('foo')) }) it('chainNullableK', async () => { const f = _.chainNullableK('foo')((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(await f(_.of(1))(undefined)(), E.right(1)) U.deepStrictEqual(await f(_.of(0))(undefined)(), E.left('foo')) U.deepStrictEqual(await f(_.of(-1))(undefined)(), E.left('foo')) }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(await pipe(_.ask(), _.tapIO(add))(1)(), E.of(1)) U.deepStrictEqual(await pipe(_.left('error'), _.tapIO(add))(undefined)(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('as', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.as('b'))(undefined)(), E.right('b')) U.deepStrictEqual(await _.as(_.of('a'), 'b')(undefined)(), E.right('b')) U.deepStrictEqual(await _.as(_.left('error'), 'b')(undefined)(), E.left('error')) }) it('asUnit', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.asUnit)(undefined)(), E.of(undefined)) }) it('tapTask', async () => { const ref: Array = [] const add = (value: number) => T.fromIO(() => ref.push(value)) U.deepStrictEqual(await pipe(_.ask(), _.tapTask(add))(1)(), E.of(1)) U.deepStrictEqual(await pipe(_.left('error'), _.tapTask(add))(undefined)(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('tapReader', async () => { U.deepStrictEqual(await _.tapReader(_.of(1), () => R.of(2))({})(), E.of(1)) }) it('tapReaderEither', async () => { U.deepStrictEqual(await _.tapReaderEither(_.of(1), () => RE.of(2))({})(), E.of(1)) }) it('tapTaskEither', async () => { U.deepStrictEqual(await _.tapTaskEither(_.of(1), () => TE.of(2))({})(), E.of(1)) }) it('tapReaderTask', async () => { U.deepStrictEqual(await _.tapReaderTask(_.of(1), () => RT.of(2))({})(), E.of(1)) }) it('tapReaderIO', async () => { U.deepStrictEqual(await _.tapReaderIO(_.of(1), () => RIO.of(2))({})(), E.of(1)) }) it('flatMapIO', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(undefined)(), E.of(2) ) }) it('flatMapTask', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.flatMapTask(f))(undefined)(), E.of(1)) }) it('flatMapReader', async () => { U.deepStrictEqual(await _.flatMapReader(_.of(1), () => R.of(2))(undefined)(), E.of(2)) }) it('flatMapReaderIO', async () => { U.deepStrictEqual(await _.flatMapReaderIO(_.of(1), () => RIO.of(2))(undefined)(), E.of(2)) }) it('flatMapIOEither', async () => { U.deepStrictEqual(await _.flatMapIOEither(_.of(1), () => IE.of(2))(undefined)(), E.of(2)) }) it('flatMapReaderEither', async () => { U.deepStrictEqual(await _.flatMapReaderEither(_.of(1), () => RE.of(2))(undefined)(), E.of(2)) }) }) ================================================ FILE: test/ReadonlyArray.ts ================================================ import * as assert from 'assert' import * as fc from 'fast-check' import { isDeepStrictEqual } from 'util' import * as B from '../src/boolean' import * as E from '../src/Either' import * as Eq from '../src/Eq' import { identity, pipe, tuple } from '../src/function' import * as M from '../src/Monoid' import * as N from '../src/number' import * as O from '../src/Option' import * as Ord from '../src/Ord' import { Predicate } from '../src/Predicate' import * as _ from '../src/ReadonlyArray' import { Refinement } from '../src/Refinement' import { separated } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' describe('ReadonlyArray', () => { describe('pipeables', () => { it('traverse', () => { const traverse = _.traverse(O.Applicative)((n: number): O.Option => (n % 2 === 0 ? O.none : O.some(n))) U.deepStrictEqual(traverse([1, 2]), O.none) U.deepStrictEqual(traverse([1, 3]), O.some([1, 3])) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence([O.some(1), O.some(3)]), O.some([1, 3])) U.deepStrictEqual(sequence([O.some(1), O.none]), O.none) }) it('traverseWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length >= 1 ? O.some(s + i) : O.none)) ), O.some(['a0', 'bb1']) ) U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length > 1 ? O.some(s + i) : O.none)) ), O.none ) }) it('lookup', () => { U.deepStrictEqual(_.lookup(0, [1, 2, 3]), O.some(1)) U.deepStrictEqual(_.lookup(3, [1, 2, 3]), O.none) U.deepStrictEqual(pipe([1, 2, 3], _.lookup(0)), O.some(1)) U.deepStrictEqual(pipe([1, 2, 3], _.lookup(3)), O.none) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(2, [1, 2, 3]), true) U.deepStrictEqual(_.elem(N.Eq)(0, [1, 2, 3]), false) U.deepStrictEqual(pipe([1, 2, 3], _.elem(N.Eq)(2)), true) U.deepStrictEqual(pipe([1, 2, 3], _.elem(N.Eq)(0)), false) }) it('unfold', () => { const as = _.unfold(5, (n) => (n > 0 ? O.some([n, n - 1]) : O.none)) U.deepStrictEqual(as, [5, 4, 3, 2, 1]) }) it('wither', async () => { const wither = _.wither(T.ApplicativePar)((n: number) => T.of(n > 2 ? O.some(n + 1) : O.none)) U.deepStrictEqual(await pipe([], wither)(), []) U.deepStrictEqual(await pipe([1, 3], wither)(), [4]) }) it('wilt', async () => { const wilt = _.wilt(T.ApplicativePar)((n: number) => T.of(n > 2 ? E.right(n + 1) : E.left(n - 1))) U.deepStrictEqual(await pipe([], wilt)(), separated([], [])) U.deepStrictEqual(await pipe([1, 3], wilt)(), separated([0], [4])) }) it('map', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.map((n) => n * 2) ), [2, 4, 6] ) }) it('mapWithIndex', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.mapWithIndex((i, n) => n + i) ), [1, 3, 5] ) }) it('alt', () => { U.deepStrictEqual( pipe( [1, 2], _.alt(() => [3, 4]) ), [1, 2, 3, 4] ) }) it('ap', () => { U.deepStrictEqual(pipe([(x: number) => x * 2, (x: number) => x * 3], _.ap([1, 2, 3])), [2, 4, 6, 3, 6, 9]) }) it('apFirst', () => { U.deepStrictEqual(pipe([1, 2], _.apFirst(['a', 'b', 'c'])), [1, 1, 1, 2, 2, 2]) }) it('apSecond', () => { U.deepStrictEqual(pipe([1, 2], _.apSecond(['a', 'b', 'c'])), ['a', 'b', 'c', 'a', 'b', 'c']) }) it('flatMap', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.flatMap((n) => [n, n + 1]) ), [1, 2, 2, 3, 3, 4] ) U.deepStrictEqual( _.flatMap([1, 2, 3], (n) => [n, n + 1]), [1, 2, 2, 3, 3, 4] ) }) it('chain', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.chain((n) => [n, n + 1]) ), [1, 2, 2, 3, 3, 4] ) }) it('chainWithIndex', () => { const f = _.chainWithIndex((i, n: number) => [n + i]) U.deepStrictEqual(pipe([1, 2, 3], f), [1, 3, 5]) U.strictEqual(pipe(_.empty, f), _.empty) const empty: ReadonlyArray = [] U.strictEqual(pipe(empty, f), _.empty) }) it('chainFirst', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.chainFirst((n) => [n, n + 1]) ), [1, 1, 2, 2, 3, 3] ) }) it('extend', () => { const sum = (as: ReadonlyArray) => M.concatAll(N.MonoidSum)(as) U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(sum)), [10, 9, 7, 4]) U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(identity)), [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]) }) it('foldMap', () => { U.deepStrictEqual(pipe(['a', 'b', 'c'], _.foldMap(S.Monoid)(identity)), 'abc') U.deepStrictEqual(pipe([], _.foldMap(S.Monoid)(identity)), '') }) it('compact', () => { U.deepStrictEqual(_.compact([]), []) U.deepStrictEqual(_.compact([O.some(1), O.some(2), O.some(3)]), [1, 2, 3]) U.deepStrictEqual(_.compact([O.some(1), O.none, O.some(3)]), [1, 3]) }) it('separate', () => { U.deepStrictEqual(_.separate([]), separated([], [])) U.deepStrictEqual(_.separate([E.left(123), E.right('123')]), separated([123], ['123'])) }) it('filter', () => { const g = (n: number) => n % 2 === 1 U.deepStrictEqual(pipe([1, 2, 3], _.filter(g)), [1, 3]) const x = pipe([O.some(3), O.some(2), O.some(1)], _.filter(O.isSome)) assert.deepStrictEqual(x, [O.some(3), O.some(2), O.some(1)]) const y = pipe([O.some(3), O.none, O.some(1)], _.filter(O.isSome)) assert.deepStrictEqual(y, [O.some(3), O.some(1)]) }) it('filterWithIndex', () => { const f = (n: number) => n % 2 === 0 U.deepStrictEqual(pipe(['a', 'b', 'c'], _.filterWithIndex(f)), ['a', 'c']) }) it('filterMap', () => { const f = (n: number) => (n % 2 === 0 ? O.none : O.some(n)) U.deepStrictEqual(pipe([1, 2, 3], _.filterMap(f)), [1, 3]) U.deepStrictEqual(pipe([], _.filterMap(f)), []) }) it('foldMapWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.foldMapWithIndex(S.Monoid)((i, a) => i + a) ), '0a1b' ) }) it('filterMapWithIndex', () => { const f = (i: number, n: number) => ((i + n) % 2 === 0 ? O.none : O.some(n)) U.deepStrictEqual(pipe([1, 2, 4], _.filterMapWithIndex(f)), [1, 2]) U.deepStrictEqual(pipe([], _.filterMapWithIndex(f)), []) }) it('partitionMap', () => { U.deepStrictEqual(pipe([], _.partitionMap(identity)), separated([], [])) U.deepStrictEqual( pipe([E.right(1), E.left('foo'), E.right(2)], _.partitionMap(identity)), separated(['foo'], [1, 2]) ) }) it('partition', () => { U.deepStrictEqual( pipe( [], _.partition((n) => n > 2) ), separated([], []) ) U.deepStrictEqual( pipe( [1, 3], _.partition((n) => n > 2) ), separated([1], [3]) ) }) it('partitionMapWithIndex', () => { U.deepStrictEqual( pipe( [], _.partitionMapWithIndex((_, a) => a) ), separated([], []) ) U.deepStrictEqual( pipe( [E.right(1), E.left('foo'), E.right(2)], _.partitionMapWithIndex((i, a) => pipe( a, E.filterOrElse( (n) => n > i, () => 'err' ) ) ) ), separated(['foo', 'err'], [1]) ) }) it('partitionWithIndex', () => { U.deepStrictEqual( pipe( [], _.partitionWithIndex((i, n) => i + n > 2) ), separated([], []) ) U.deepStrictEqual( pipe( [1, 2], _.partitionWithIndex((i, n) => i + n > 2) ), separated([1], [2]) ) }) it('reduce', () => { U.deepStrictEqual( pipe( ['a', 'b', 'c'], _.reduce('', (acc, a) => acc + a) ), 'abc' ) }) it('reduceWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceWithIndex('', (i, b, a) => b + i + a) ), '0a1b' ) }) it('reduceRight', () => { const as: ReadonlyArray = ['a', 'b', 'c'] const b = '' const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(as, _.reduceRight(b, f)), 'cba') const x2: ReadonlyArray = [] U.deepStrictEqual(pipe(x2, _.reduceRight(b, f)), '') }) it('reduceRightWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceRightWithIndex('', (i, a, b) => b + i + a) ), '1b0a' ) }) it('duplicate', () => { U.deepStrictEqual(pipe(['a', 'b'], _.duplicate), [['a', 'b'], ['b']]) }) }) it('getMonoid', () => { const M = _.getMonoid() U.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4]) const x = [1, 2] U.strictEqual(M.concat(x, M.empty), x) U.strictEqual(M.concat(M.empty, x), x) }) it('getEq', () => { const O = _.getEq(S.Ord) U.deepStrictEqual(O.equals([], []), true) U.deepStrictEqual(O.equals(['a'], ['a']), true) U.deepStrictEqual(O.equals(['a', 'b'], ['a', 'b']), true) U.deepStrictEqual(O.equals(['a'], []), false) U.deepStrictEqual(O.equals([], ['a']), false) U.deepStrictEqual(O.equals(['a'], ['b']), false) U.deepStrictEqual(O.equals(['a', 'b'], ['b', 'a']), false) U.deepStrictEqual(O.equals(['a', 'a'], ['a']), false) }) it('getOrd', () => { const O = _.getOrd(S.Ord) U.deepStrictEqual(O.compare([], []), 0) U.deepStrictEqual(O.compare(['a'], ['a']), 0) U.deepStrictEqual(O.compare(['b'], ['a']), 1) U.deepStrictEqual(O.compare(['a'], ['b']), -1) U.deepStrictEqual(O.compare(['a'], []), 1) U.deepStrictEqual(O.compare([], ['a']), -1) U.deepStrictEqual(O.compare(['a', 'a'], ['a']), 1) U.deepStrictEqual(O.compare(['a', 'a'], ['b']), -1) U.deepStrictEqual(O.compare(['a', 'a'], ['a', 'a']), 0) U.deepStrictEqual(O.compare(['a', 'b'], ['a', 'b']), 0) U.deepStrictEqual(O.compare(['a', 'a'], ['a', 'b']), -1) U.deepStrictEqual(O.compare(['a', 'b'], ['a', 'a']), 1) U.deepStrictEqual(O.compare(['a', 'b'], ['b', 'a']), -1) U.deepStrictEqual(O.compare(['b', 'a'], ['a', 'a']), 1) U.deepStrictEqual(O.compare(['b', 'a'], ['a', 'b']), 1) U.deepStrictEqual(O.compare(['b', 'b'], ['b', 'a']), 1) U.deepStrictEqual(O.compare(['b', 'a'], ['b', 'b']), -1) }) it('isEmpty', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.isEmpty(as), false) U.deepStrictEqual(_.isEmpty([]), true) }) it('isNotEmpty', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.isNonEmpty(as), true) U.deepStrictEqual(_.isNonEmpty([]), false) }) it('cons', () => { U.deepStrictEqual(_.cons(0, [1, 2, 3]), [0, 1, 2, 3]) U.deepStrictEqual(_.cons([1], [[2]]), [[1], [2]]) U.deepStrictEqual(pipe([1, 2, 3], _.cons(0)), [0, 1, 2, 3]) U.deepStrictEqual(pipe([[2]], _.cons([1])), [[1], [2]]) }) it('snoc', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.snoc(as, 4), [1, 2, 3, 4]) U.deepStrictEqual(_.snoc([[1]], [2]), [[1], [2]]) }) it('head', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.head(as), O.some(1)) U.deepStrictEqual(_.head([]), O.none) }) it('last', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.last(as), O.some(3)) U.deepStrictEqual(_.last([]), O.none) }) it('tail', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.tail(as), O.some([2, 3])) U.deepStrictEqual(_.tail([]), O.none) }) it('takeLeft', () => { // _.empty U.strictEqual(_.takeLeft(0)(_.empty), _.empty) // empty const empty: ReadonlyArray = [] U.strictEqual(_.takeLeft(0)(empty), empty) const full: ReadonlyArray = [1, 2] // non empty U.strictEqual(_.takeLeft(0)(full), _.empty) U.deepStrictEqual(_.takeLeft(1)(full), [1]) // full U.strictEqual(_.takeLeft(2)(full), full) // out of bound U.strictEqual(_.takeLeft(1)(_.empty), _.empty) U.strictEqual(_.takeLeft(1)(empty), empty) U.strictEqual(_.takeLeft(3)(full), full) U.strictEqual(_.takeLeft(-1)(_.empty), _.empty) U.strictEqual(_.takeLeft(-1)(empty), empty) U.strictEqual(_.takeLeft(-1)(full), full) }) it('takeRight', () => { // _.empty U.strictEqual(_.takeRight(0)(_.empty), _.empty) // empty const empty: ReadonlyArray = [] U.strictEqual(_.takeRight(0)(empty), empty) const full: ReadonlyArray = [1, 2] // non empty U.strictEqual(_.takeRight(0)(full), _.empty) U.deepStrictEqual(_.takeRight(1)(full), [2]) // full U.strictEqual(_.takeRight(2)(full), full) // out of bound U.strictEqual(_.takeRight(1)(_.empty), _.empty) U.strictEqual(_.takeRight(1)(empty), empty) U.strictEqual(_.takeRight(3)(full), full) U.strictEqual(_.takeRight(-1)(_.empty), _.empty) U.strictEqual(_.takeRight(-1)(empty), empty) U.strictEqual(_.takeRight(-1)(full), full) }) it('spanLeft', () => { const f = _.spanLeft((n: number) => n % 2 === 1) const assertSpanLeft = ( input: ReadonlyArray, expectedInit: ReadonlyArray, expectedRest: ReadonlyArray ) => { const { init, rest } = f(input) U.strictEqual(init, expectedInit) U.strictEqual(rest, expectedRest) } U.deepStrictEqual(f([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] }) const empty: ReadonlyArray = [] assertSpanLeft(empty, empty, _.empty) assertSpanLeft(_.empty, _.empty, _.empty) const inputAll: ReadonlyArray = [1, 3] assertSpanLeft(inputAll, inputAll, _.empty) const inputNone: ReadonlyArray = [2, 4] assertSpanLeft(inputNone, _.empty, inputNone) }) it('takeLeftWhile', () => { const f = (n: number) => n % 2 === 0 U.deepStrictEqual(_.takeLeftWhile(f)([2, 4, 3, 6]), [2, 4]) const empty: ReadonlyArray = [] U.strictEqual(_.takeLeftWhile(f)(empty), empty) U.strictEqual(_.takeLeftWhile(f)(_.empty), _.empty) U.strictEqual(_.takeLeftWhile(f)([1, 2, 4]), _.empty) const input: ReadonlyArray = [2, 4] U.strictEqual(_.takeLeftWhile(f)(input), input) }) it('dropLeft', () => { // _.empty U.strictEqual(_.dropLeft(0)(_.empty), _.empty) // empty const empty: ReadonlyArray = [] U.strictEqual(_.dropLeft(0)(empty), empty) const full: ReadonlyArray = [1, 2] // non empty U.strictEqual(_.dropLeft(0)(full), full) U.deepStrictEqual(_.dropLeft(1)(full), [2]) // full U.strictEqual(_.dropLeft(2)(full), _.empty) // out of bound U.strictEqual(_.dropLeft(1)(_.empty), _.empty) U.strictEqual(_.dropLeft(1)(empty), empty) U.strictEqual(_.dropLeft(3)(full), _.empty) U.strictEqual(_.dropLeft(-1)(_.empty), _.empty) U.strictEqual(_.dropLeft(-1)(empty), empty) U.strictEqual(_.dropLeft(-1)(full), full) }) it('dropRight', () => { // _.empty U.strictEqual(_.dropRight(0)(_.empty), _.empty) // empty const empty: ReadonlyArray = [] U.strictEqual(_.dropRight(0)(empty), empty) const full: ReadonlyArray = [1, 2] // non empty U.strictEqual(_.dropRight(0)(full), full) U.deepStrictEqual(_.dropRight(1)(full), [1]) // full U.strictEqual(_.dropRight(2)(full), _.empty) // out of bound U.strictEqual(_.dropRight(1)(_.empty), _.empty) U.strictEqual(_.dropRight(1)(empty), empty) U.strictEqual(_.dropRight(3)(full), _.empty) U.strictEqual(_.dropRight(-1)(_.empty), _.empty) U.strictEqual(_.dropRight(-1)(empty), empty) U.strictEqual(_.dropRight(-1)(full), full) }) it('dropLeftWhile', () => { const f = _.dropLeftWhile((n: number) => n > 0) U.strictEqual(f(_.empty), _.empty) const empty: ReadonlyArray = [] U.strictEqual(f(empty), empty) U.strictEqual(f([1, 2]), _.empty) const x1: ReadonlyArray = [-1, -2] U.strictEqual(f(x1), x1) const x2: ReadonlyArray = [-1, 2] U.strictEqual(f(x2), x2) U.deepStrictEqual(f([1, -2, 3]), [-2, 3]) }) it('init', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.init(as), O.some([1, 2])) U.deepStrictEqual(_.init([]), O.none) }) it('findIndex', () => { U.deepStrictEqual(_.findIndex((x) => x === 2)([1, 2, 3]), O.some(1)) U.deepStrictEqual(_.findIndex((x) => x === 2)([]), O.none) }) it('findFirst', () => { U.deepStrictEqual( pipe( [], _.findFirst((x: { readonly a: number }) => x.a > 1) ), O.none ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findFirst((x) => x.a > 1) ), O.some({ a: 2 }) ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findFirst((x) => x.a > 3) ), O.none ) }) it('findFirstMap', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.findFirstMap((n) => (n > 1 ? O.some(n * 2) : O.none)) ), O.some(4) ) U.deepStrictEqual( pipe( [1], _.findFirstMap((n) => (n < 1 ? O.some(n * 2) : O.none)) ), O.none ) }) it('findLast', () => { U.deepStrictEqual( pipe( [], _.findLast((x: { readonly a: number }) => x.a > 1) ), O.none ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findLast((x) => x.a > 1) ), O.some({ a: 3 }) ) U.deepStrictEqual( pipe( [{ a: 1 }, { a: 2 }, { a: 3 }], _.findLast((x) => x.a > 3) ), O.none ) }) it('findLastMap', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.findLastMap((n) => (n > 1 ? O.some(n * 2) : O.none)) ), O.some(6) ) U.deepStrictEqual( pipe( [1], _.findLastMap((n) => (n > 1 ? O.some(n * 2) : O.none)) ), O.none ) }) it('findLastIndex', () => { interface X { readonly a: number readonly b: number } const xs: ReadonlyArray = [ { a: 1, b: 0 }, { a: 1, b: 1 } ] U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 1)(xs), O.some(1)) U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 4)(xs), O.none) U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 1)([]), O.none) }) it('insertAt', () => { U.deepStrictEqual(_.insertAt(1, 1)([]), O.none) U.deepStrictEqual(_.insertAt(0, 1)([]), O.some([1] as const)) U.deepStrictEqual(_.insertAt(2, 5)([1, 2, 3, 4]), O.some([1, 2, 5, 3, 4] as const)) }) it('unsafeUpdateAt', () => { const empty: ReadonlyArray = [] U.strictEqual(_.unsafeUpdateAt(1, 2, empty), empty) U.strictEqual(_.unsafeUpdateAt(1, 2, _.empty), _.empty) // should return the same reference if nothing changed const input: ReadonlyArray = [1, 2, 3] U.deepStrictEqual( pipe(_.unsafeUpdateAt(1, 2, input), (out) => out === input), true ) }) it('updateAt', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.updateAt(1, 1)(as), O.some([1, 1, 3])) U.deepStrictEqual(_.updateAt(1, 1)([]), O.none) }) it('deleteAt', () => { const as: ReadonlyArray = [1, 2, 3] U.deepStrictEqual(_.deleteAt(0)(as), O.some([2, 3])) U.deepStrictEqual(_.deleteAt(1)([]), O.none) }) it('modifyAt', () => { U.deepStrictEqual(_.modifyAt(1, U.double)([1, 2, 3]), O.some([1, 4, 3])) U.deepStrictEqual(_.modifyAt(1, U.double)([]), O.none) // should return the same reference if nothing changed const input: ReadonlyArray = [1, 2, 3] U.deepStrictEqual( pipe( input, _.modifyAt(1, identity), O.map((out) => out === input) ), O.some(true) ) }) it('sort', () => { const O = pipe( N.Ord, Ord.contramap((x: { readonly a: number }) => x.a) ) U.deepStrictEqual( pipe( [ { a: 3, b: 'b1' }, { a: 2, b: 'b2' }, { a: 1, b: 'b3' } ], _.sort(O) ), [ { a: 1, b: 'b3' }, { a: 2, b: 'b2' }, { a: 3, b: 'b1' } ] ) U.strictEqual(_.sort(N.Ord)(_.empty), _.empty) const as: ReadonlyArray = [1] U.strictEqual(_.sort(N.Ord)(as), as) }) it('zipWith', () => { U.deepStrictEqual( _.zipWith([1, 2, 3], [], (n, s) => s + n), [] ) U.deepStrictEqual( _.zipWith([], ['a', 'b', 'c', 'd'], (n, s) => s + n), [] ) U.deepStrictEqual( _.zipWith([], [], (n, s) => s + n), [] ) U.deepStrictEqual( _.zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3'] ) }) it('zip', () => { U.deepStrictEqual(_.zip([], ['a', 'b', 'c', 'd']), []) U.deepStrictEqual(_.zip([1, 2, 3], []), []) U.deepStrictEqual(_.zip([1, 2, 3], ['a', 'b', 'c', 'd']), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) U.deepStrictEqual(pipe([1, 2, 3], _.zip(['a', 'b', 'c', 'd'])), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) }) it('unzip', () => { U.deepStrictEqual(_.unzip([]), [[], []]) U.deepStrictEqual( _.unzip([ [1, 'a'], [2, 'b'], [3, 'c'] ]), [ [1, 2, 3], ['a', 'b', 'c'] ] ) }) it('rights', () => { U.deepStrictEqual(_.rights([E.right(1), E.left('foo'), E.right(2)]), [1, 2]) U.deepStrictEqual(_.rights([]), []) }) it('lefts', () => { U.deepStrictEqual(_.lefts([E.right(1), E.left('foo'), E.right(2)]), ['foo']) U.deepStrictEqual(_.lefts([]), []) }) it('flatten', () => { U.deepStrictEqual(_.flatten([[1], [2], [3]]), [1, 2, 3]) }) it('prependAll', () => { const empty: ReadonlyArray = [] U.strictEqual(_.prependAll(0)(empty), empty) U.strictEqual(_.prependAll(0)(_.empty), _.empty) U.deepStrictEqual(_.prependAll(0)([1, 2, 3]), [0, 1, 0, 2, 0, 3]) U.deepStrictEqual(_.prependAll(0)([1]), [0, 1]) U.deepStrictEqual(_.prependAll(0)([1, 2, 3, 4]), [0, 1, 0, 2, 0, 3, 0, 4]) }) it('intersperse', () => { const empty: ReadonlyArray = [] U.strictEqual(_.intersperse(0)(empty), empty) U.strictEqual(_.intersperse(0)(_.empty), _.empty) const singleton = [1] U.strictEqual(_.intersperse(0)(singleton), singleton) U.deepStrictEqual(_.intersperse(0)([1, 2, 3]), [1, 0, 2, 0, 3]) U.deepStrictEqual(_.intersperse(0)([1, 2]), [1, 0, 2]) U.deepStrictEqual(_.intersperse(0)([1, 2, 3, 4]), [1, 0, 2, 0, 3, 0, 4]) }) it('intercalate', () => { U.deepStrictEqual(_.intercalate(S.Monoid)('-')([]), '') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a']), 'a') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', '', 'c']), 'a--c') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', 'b']), 'a-b') U.deepStrictEqual(_.intercalate(S.Monoid)('-')(['a', 'b', 'c', 'd']), 'a-b-c-d') }) it('rotate', () => { U.strictEqual(_.rotate(0)(_.empty), _.empty) U.strictEqual(_.rotate(1)(_.empty), _.empty) const singleton: ReadonlyArray = [1] U.strictEqual(_.rotate(1)(singleton), singleton) U.strictEqual(_.rotate(2)(singleton), singleton) U.strictEqual(_.rotate(-1)(singleton), singleton) U.strictEqual(_.rotate(-2)(singleton), singleton) const two: ReadonlyArray = [1, 2] U.strictEqual(_.rotate(2)(two), two) U.strictEqual(_.rotate(0)(two), two) U.strictEqual(_.rotate(-2)(two), two) U.deepStrictEqual(_.rotate(1)([1, 2]), [2, 1]) U.deepStrictEqual(_.rotate(1)([1, 2, 3, 4, 5]), [5, 1, 2, 3, 4]) U.deepStrictEqual(_.rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-1)([1, 2, 3, 4, 5]), [2, 3, 4, 5, 1]) U.deepStrictEqual(_.rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) U.deepStrictEqual(_.rotate(7)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-7)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) U.deepStrictEqual(_.rotate(2.2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-2.2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) }) it('reverse', () => { const empty: ReadonlyArray = [] U.strictEqual(_.reverse(empty), empty) U.strictEqual(_.reverse(_.empty), _.empty) const singleton: ReadonlyArray = [1] U.strictEqual(_.reverse(singleton), singleton) U.deepStrictEqual(_.reverse([1, 2, 3]), [3, 2, 1]) }) it('foldLeft', () => { const len: (as: ReadonlyArray) => number = _.foldLeft( () => 0, (_, tail) => 1 + len(tail) ) U.deepStrictEqual(len([1, 2, 3]), 3) }) it('foldRight', () => { const len: (as: ReadonlyArray) => number = _.foldRight( () => 0, (init, _) => 1 + len(init) ) U.deepStrictEqual(len([1, 2, 3]), 3) }) it('scanLeft', () => { const f = (b: number, a: number) => b - a U.deepStrictEqual(_.scanLeft(10, f)([1, 2, 3]), [10, 9, 7, 4]) U.deepStrictEqual(_.scanLeft(10, f)([0]), [10, 10]) U.deepStrictEqual(_.scanLeft(10, f)([]), [10]) }) it('scanRight', () => { const f = (b: number, a: number) => b - a U.deepStrictEqual(_.scanRight(10, f)([1, 2, 3]), [-8, 9, -7, 10]) U.deepStrictEqual(_.scanRight(10, f)([0]), [-10, 10]) U.deepStrictEqual(_.scanRight(10, f)([]), [10]) }) it('uniq', () => { interface A { readonly a: string readonly b: number } const eqA = pipe( N.Eq, Eq.contramap((f: A) => f.b) ) const arrA: A = { a: 'a', b: 1 } const arrB: A = { a: 'b', b: 1 } const arrC: A = { a: 'c', b: 2 } const arrD: A = { a: 'd', b: 2 } const arrUniq: ReadonlyArray = [arrA, arrC] U.deepStrictEqual(_.uniq(eqA)(arrUniq), arrUniq) U.deepStrictEqual(_.uniq(eqA)([arrA, arrB, arrC, arrD]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrB, arrA, arrC, arrD]), [arrB, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrA, arrA, arrC, arrD, arrA]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrA, arrC]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrC, arrA]), [arrC, arrA]) U.deepStrictEqual(_.uniq(B.Eq)([true, false, true, false]), [true, false]) U.deepStrictEqual(_.uniq(N.Eq)([-0, -0]), [-0]) U.deepStrictEqual(_.uniq(N.Eq)([0, -0]), [0]) U.deepStrictEqual(_.uniq(N.Eq)([1]), [1]) U.deepStrictEqual(_.uniq(N.Eq)([2, 1, 2]), [2, 1]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 1]), [1, 2]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(N.Eq)([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'a']), ['a', 'b']) U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'A']), ['a', 'b', 'A']) U.strictEqual(_.uniq(N.Eq)(_.empty), _.empty) const as: ReadonlyArray = [1] U.strictEqual(_.uniq(N.Eq)(as), as) }) it('sortBy', () => { interface X { readonly a: string readonly b: number readonly c: boolean } const byName = pipe( S.Ord, Ord.contramap((p: { readonly a: string; readonly b: number }) => p.a) ) const byAge = pipe( N.Ord, Ord.contramap((p: { readonly a: string; readonly b: number }) => p.b) ) const f = _.sortBy([byName, byAge]) const xs: ReadonlyArray = [ { a: 'a', b: 1, c: true }, { a: 'b', b: 3, c: true }, { a: 'c', b: 2, c: true }, { a: 'b', b: 2, c: true } ] U.deepStrictEqual(f(xs), [ { a: 'a', b: 1, c: true }, { a: 'b', b: 2, c: true }, { a: 'b', b: 3, c: true }, { a: 'c', b: 2, c: true } ]) const sortByAgeByName = _.sortBy([byAge, byName]) U.deepStrictEqual(sortByAgeByName(xs), [ { a: 'a', b: 1, c: true }, { a: 'b', b: 2, c: true }, { a: 'c', b: 2, c: true }, { a: 'b', b: 3, c: true } ]) U.strictEqual(f(_.empty), _.empty) U.strictEqual(_.sortBy([])(xs), xs) }) it('chop', () => { const f = _.chop((as) => [as[0] * 2, as.slice(1)]) const empty: ReadonlyArray = [] U.strictEqual(f(empty), _.empty) U.strictEqual(f(_.empty), _.empty) U.deepStrictEqual(f([1, 2, 3]), [2, 4, 6]) }) it('splitAt', () => { const assertSplitAt = ( input: ReadonlyArray, index: number, expectedInit: ReadonlyArray, expectedRest: ReadonlyArray ) => { const [init, rest] = _.splitAt(index)(input) U.strictEqual(init, expectedInit) U.strictEqual(rest, expectedRest) } U.deepStrictEqual(_.splitAt(1)([1, 2]), [[1], [2]]) const two: ReadonlyArray = [1, 2] assertSplitAt(two, 2, two, _.empty) U.deepStrictEqual(_.splitAt(2)([1, 2, 3, 4, 5]), [ [1, 2], [3, 4, 5] ]) // zero const empty: ReadonlyArray = [] assertSplitAt(_.empty, 0, _.empty, _.empty) assertSplitAt(empty, 0, empty, _.empty) assertSplitAt(two, 0, _.empty, two) // out of bounds assertSplitAt(_.empty, -1, _.empty, _.empty) assertSplitAt(empty, -1, empty, _.empty) assertSplitAt(two, -1, _.empty, two) assertSplitAt(two, 3, two, _.empty) assertSplitAt(_.empty, 3, _.empty, _.empty) assertSplitAt(empty, 3, empty, _.empty) }) describe('chunksOf', () => { it('should split a `ReadonlyArray` into length-n pieces', () => { U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5, 6]), [ [1, 2], [3, 4], [5, 6] ]) U.deepStrictEqual(_.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]]) // out of bounds U.deepStrictEqual(_.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) const assertSingleChunk = (input: ReadonlyArray, n: number) => { const chunks = _.chunksOf(n)(input) U.strictEqual(chunks.length, 1) U.strictEqual(chunks[0], input) } // n = length assertSingleChunk([1, 2], 2) // n out of bounds assertSingleChunk([1, 2], 3) }) // #897 it('returns an empty array if provided an empty array', () => { const empty: ReadonlyArray = [] U.strictEqual(_.chunksOf(0)(empty), _.empty) U.strictEqual(_.chunksOf(0)(_.empty), _.empty) U.strictEqual(_.chunksOf(1)(empty), _.empty) U.strictEqual(_.chunksOf(1)(_.empty), _.empty) U.strictEqual(_.chunksOf(2)(empty), _.empty) U.strictEqual(_.chunksOf(2)(_.empty), _.empty) }) // #897 it('should respect the law: chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys)))', () => { const xs: ReadonlyArray = [] const ys: ReadonlyArray = [1, 2] U.deepStrictEqual(_.chunksOf(2)(xs).concat(_.chunksOf(2)(ys)), _.chunksOf(2)(xs.concat(ys))) fc.assert( fc.property( fc.array(fc.integer()).filter((xs) => xs.length % 2 === 0), // Ensures `xs.length` is even fc.array(fc.integer()), fc.integer({ min: 1, max: 1 }).map((x) => x * 2), // Generates `n` to be even so that it evenly divides `xs` (xs, ys, n) => { const as = _.chunksOf(n)(xs).concat(_.chunksOf(n)(ys)) const bs = _.chunksOf(n)(xs.concat(ys)) isDeepStrictEqual(as, bs) } ) ) }) }) it('prepend', () => { U.deepStrictEqual(pipe(['a', 'b'], _.prepend('c')), ['c', 'a', 'b']) U.deepStrictEqual(pipe(['a', 'b'], _.prependW(3)), [3, 'a', 'b']) }) it('append', () => { U.deepStrictEqual(pipe(['a', 'b'], _.append('c')), ['a', 'b', 'c']) U.deepStrictEqual(pipe(['a', 'b'], _.appendW(3)), ['a', 'b', 3]) }) it('makeBy', () => { U.deepStrictEqual(_.makeBy(5, U.double), [0, 2, 4, 6, 8]) U.strictEqual(_.makeBy(0, U.double), _.empty) U.strictEqual(_.makeBy(-1, U.double), _.empty) U.deepStrictEqual(_.makeBy(2.2, U.double), [0, 2]) }) it('replicate', () => { U.strictEqual(_.replicate(0, 'a'), _.empty) U.strictEqual(_.replicate(-1, 'a'), _.empty) U.deepStrictEqual(_.replicate(3, 'a'), ['a', 'a', 'a']) U.deepStrictEqual(_.replicate(2.2, 'a'), ['a', 'a']) }) it('range', () => { U.deepStrictEqual(_.range(0, 0), [0]) U.deepStrictEqual(_.range(0, 1), [0, 1]) U.deepStrictEqual(_.range(1, 5), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.range(10, 15), [10, 11, 12, 13, 14, 15]) U.deepStrictEqual(_.range(-1, 0), [-1, 0]) U.deepStrictEqual(_.range(-5, -1), [-5, -4, -3, -2, -1]) // out of bound U.deepStrictEqual(_.range(2, 1), [2]) U.deepStrictEqual(_.range(-1, -2), [-1]) }) it('comprehension', () => { U.deepStrictEqual( _.comprehension([[1, 2, 3]], (a) => a * 2), [2, 4, 6] ) U.deepStrictEqual( _.comprehension( [ [1, 2, 3], ['a', 'b'] ], tuple ), [ [1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'], [3, 'a'], [3, 'b'] ] ) U.deepStrictEqual( _.comprehension( [ [1, 2, 3], ['a', 'b'] ], tuple, (a, b) => (a + b.length) % 2 === 0 ), [ [1, 'a'], [1, 'b'], [3, 'a'], [3, 'b'] ] ) }) it('union', () => { const concat = _.union(N.Eq) const two: ReadonlyArray = [1, 2] U.deepStrictEqual(concat(two, [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(concat(two, [2, 3]), [1, 2, 3]) U.deepStrictEqual(concat(two, [1, 2]), [1, 2]) U.deepStrictEqual(pipe(two, concat([3, 4])), [1, 2, 3, 4]) U.deepStrictEqual(pipe(two, concat([2, 3])), [1, 2, 3]) U.deepStrictEqual(pipe(two, concat([1, 2])), [1, 2]) U.strictEqual(pipe(two, concat(_.empty)), two) U.strictEqual(pipe(_.empty, concat(two)), two) U.strictEqual(pipe(_.empty, concat(_.empty)), _.empty) }) it('intersection', () => { U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [3, 4]), []) U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [2, 3]), [2]) U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [1, 2]), [1, 2]) U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([3, 4])), []) U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([2, 3])), [2]) U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([1, 2])), [1, 2]) }) it('difference', () => { U.deepStrictEqual(_.difference(N.Eq)([1, 2], [3, 4]), [1, 2]) U.deepStrictEqual(_.difference(N.Eq)([1, 2], [2, 3]), [1]) U.deepStrictEqual(_.difference(N.Eq)([1, 2], [1, 2]), []) U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([3, 4])), [1, 2]) U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([2, 3])), [1]) U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([1, 2])), []) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(N.Eq) const two: ReadonlyArray = [1, 2] U.deepStrictEqual(M.concat(two, [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(M.concat(two, [2, 3]), [1, 2, 3]) U.deepStrictEqual(M.concat(two, [1, 2]), [1, 2]) U.strictEqual(M.concat(two, M.empty), two) U.strictEqual(M.concat(M.empty, two), two) U.strictEqual(M.concat(M.empty, M.empty), M.empty) }) it('getIntersectionSemigroup', () => { const concat = _.getIntersectionSemigroup(N.Eq).concat U.deepStrictEqual(concat([1, 2], [3, 4]), []) U.deepStrictEqual(concat([1, 2], [2, 3]), [2]) U.deepStrictEqual(concat([1, 2], [1, 2]), [1, 2]) }) it('getDifferenceMagma', () => { const concat = _.getDifferenceMagma(N.Eq).concat U.deepStrictEqual(concat([1, 2], [3, 4]), [1, 2]) U.deepStrictEqual(concat([1, 2], [2, 3]), [1]) U.deepStrictEqual(concat([1, 2], [1, 2]), []) }) it('should be safe when calling map with a binary function', () => { interface Foo { readonly bar: () => number } const f = (a: number, x?: Foo) => (x !== undefined ? `${a}${x.bar()}` : `${a}`) U.deepStrictEqual(_.Functor.map([1, 2], f), ['1', '2']) U.deepStrictEqual(pipe([1, 2], _.map(f)), ['1', '2']) }) it('getShow', () => { const Sh = _.getShow(S.Show) U.deepStrictEqual(Sh.show([]), `[]`) U.deepStrictEqual(Sh.show(['a']), `["a"]`) U.deepStrictEqual(Sh.show(['a', 'b']), `["a", "b"]`) }) it('fromArray', () => { U.strictEqual(_.fromArray([]), _.empty) const as = [1, 2, 3] const bs = _.fromArray(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('toArray', () => { U.deepStrictEqual(_.toArray(_.empty), []) assert.notStrictEqual(_.toArray(_.empty), _.empty) const as = [1, 2, 3] const bs = _.toArray(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('empty', () => { U.deepStrictEqual(_.empty.length, 0) }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) ), [{ a: 1, b: 'b', c: [1, 'b'] }] ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b'))), [{ a: 1, b: 'b' }]) }) it('every', () => { const isPositive: Predicate = (n) => n > 0 U.deepStrictEqual(pipe([1, 2, 3], _.every(isPositive)), true) U.deepStrictEqual(pipe([1, 2, -3], _.every(isPositive)), false) }) it('some', () => { const isPositive: Predicate = (n) => n > 0 U.deepStrictEqual(pipe([-1, -2, 3], _.some(isPositive)), true) U.deepStrictEqual(pipe([-1, -2, -3], _.some(isPositive)), false) }) it('size', () => { U.deepStrictEqual(_.size(_.empty), 0) U.deepStrictEqual(_.size([]), 0) U.deepStrictEqual(_.size(['a']), 1) }) describe('chainRec', () => { it('depth-first', () => { const chainRec = _.ChainRecDepthFirst.chainRec assert.deepStrictEqual( chainRec(1, () => []), [] ) assert.deepStrictEqual( chainRec(1, () => [E.right('foo')]), ['foo'] ) assert.deepStrictEqual( chainRec(1, (a) => { if (a < 5) { return [E.right(a), E.left(a + 1)] } else { return [E.right(a)] } }), [1, 2, 3, 4, 5] ) assert.deepStrictEqual( chainRec(1, (a) => { if (a < 5) { return [E.left(a + 1), E.right(a)] } else { return [E.right(a)] } }), [5, 4, 3, 2, 1] ) assert.deepStrictEqual( chainRec(1, (a) => { if (a < 5) { return a % 2 === 0 ? [E.right(a), E.left(a + 1)] : [E.left(a + 1), E.right(a)] } else { return [E.right(a)] } }), [2, 4, 5, 3, 1] ) assert.deepStrictEqual( chainRec(0, (a) => { if (a === 0) { return [E.right(a), E.left(a - 1), E.left(a + 1)] } else if (0 < a && a < 5) { return [E.right(a), E.left(a + 1)] } else if (-5 < a && a < 0) { return [E.right(a), E.left(a - 1)] } else { return [E.right(a)] } }), [0, -1, -2, -3, -4, -5, 1, 2, 3, 4, 5] ) assert.deepStrictEqual( chainRec(0, (a) => { if (a === 0) { return [E.left(a - 1), E.right(a), E.left(a + 1)] } else if (0 < a && a < 5) { return [E.right(a), E.left(a + 1)] } else if (-5 < a && a < 0) { return [E.left(a - 1), E.right(a)] } else { return [E.right(a)] } }), [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] ) }) it('breadth-first', () => { const chainRec = _.ChainRecBreadthFirst.chainRec assert.deepStrictEqual( chainRec(1, () => []), [] ) assert.deepStrictEqual( chainRec(1, () => [E.right('foo')]), ['foo'] ) assert.deepStrictEqual( chainRec(1, (a) => { if (a < 5) { return [E.right(a), E.left(a + 1)] } else { return [E.right(a)] } }), [1, 2, 3, 4, 5] ) assert.deepStrictEqual( chainRec(1, (a) => { if (a < 5) { return [E.left(a + 1), E.right(a)] } else { return [E.right(a)] } }), [1, 2, 3, 4, 5] ) assert.deepStrictEqual( chainRec(0, (a) => { if (a === 0) { return [E.right(a), E.left(a - 1), E.left(a + 1)] } else if (0 < a && a < 5) { return [E.right(a), E.left(a + 1)] } else if (-5 < a && a < 0) { return [E.right(a), E.left(a - 1)] } else { return [E.right(a)] } }), [0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5] ) assert.deepStrictEqual( chainRec(0, (a) => { if (a === 0) { return [E.left(a - 1), E.right(a), E.left(a + 1)] } else if (0 < a && a < 5) { return [E.right(a), E.left(a + 1)] } else if (-5 < a && a < 0) { return [E.left(a - 1), E.right(a)] } else { return [E.right(a)] } }), [0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5] ) }) }) describe('fromPredicate', () => { it('can create an array from a Refinement', () => { const refinement: Refinement = (a): a is string => typeof a === 'string' U.deepStrictEqual(_.fromPredicate(refinement)('hello'), ['hello']) U.deepStrictEqual(_.fromPredicate(refinement)(null), []) }) it('can create an array from a Predicate', () => { const predicate = (a: string) => a.length > 0 U.deepStrictEqual(_.fromPredicate(predicate)('hi'), ['hi']) U.deepStrictEqual(_.fromPredicate(predicate)(''), []) }) }) it('fromOption', () => { U.deepStrictEqual(_.fromOption(O.some('hello')), ['hello']) U.deepStrictEqual(_.fromOption(O.none), []) }) it('fromEither', () => { U.deepStrictEqual(_.fromEither(E.right(1)), [1]) U.strictEqual(_.fromEither(E.left('a')), _.empty) }) it('match', () => { const f = _.match( () => 'empty', (as) => `nonEmpty ${as.length}` ) U.deepStrictEqual(pipe(_.empty, f), 'empty') U.deepStrictEqual(pipe([1, 2, 3], f), 'nonEmpty 3') }) it('concatW', () => { U.deepStrictEqual(pipe([1], _.concatW(['a'])), [1, 'a']) const as = [1, 2, 3] U.strictEqual(pipe(_.empty, _.concatW(as)), as) U.strictEqual(pipe(as, _.concatW(_.empty)), as) const empty: ReadonlyArray = [] U.strictEqual(pipe(empty, _.concatW(as)), as) U.strictEqual(pipe(as, _.concatW(empty)), as) }) it('fromOptionK', () => { const f = (n: number) => (n > 0 ? O.some(n) : O.none) const g = _.fromOptionK(f) U.strictEqual(g(0), _.empty) U.deepStrictEqual(g(1), [1]) }) it('isOutOfBound', () => { U.deepStrictEqual(_.isOutOfBound(0, ['a']), false) U.deepStrictEqual(_.isOutOfBound(100, ['a']), true) U.deepStrictEqual(_.isOutOfBound(-1, ['a']), true) }) }) ================================================ FILE: test/ReadonlyMap.ts ================================================ import * as assert from 'assert' import { Either, left, right } from '../src/Either' import { Eq, fromEquals } from '../src/Eq' import { identity, pipe } from '../src/function' import * as IO from '../src/IO' import * as N from '../src/number' import * as O from '../src/Option' import * as Ord from '../src/Ord' import * as RA from '../src/ReadonlyArray' import * as _ from '../src/ReadonlyMap' import { Refinement } from '../src/Refinement' import * as Se from '../src/Semigroup' import { separated } from '../src/Separated' import { Show, struct } from '../src/Show' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' interface User { readonly id: string } const ordUser = pipe( S.Ord, Ord.contramap((u: User) => u.id) ) const eqUser: Eq = { equals: ordUser.equals } const p = ((n: number): boolean => n > 2) as Refinement interface Key { readonly id: number } interface Value { readonly value: number } const eqKey: Eq = fromEquals((x, y) => x.id % 3 === y.id % 3) const ordKey = Ord.fromCompare((x, y) => N.Ord.compare(x.id % 3, y.id % 3)) const eqValue: Eq = fromEquals((x, y) => x.value % 3 === y.value % 3) const semigroupValue = Se.struct({ value: N.SemigroupSum }) const key1 = { id: 1 } const value1 = { value: 1 } const repo = new Map([ [key1, value1], [{ id: 2 }, { value: 2 }] ]) describe('ReadonlyMap', () => { describe('pipeables', () => { it('map', () => { U.deepStrictEqual( pipe( new Map([ ['k1', 1], ['k2', 2] ]), _.map(U.double) ), new Map([ ['k1', 2], ['k2', 4] ]) ) }) it('filter', () => { U.deepStrictEqual( pipe( new Map([ ['a', 1], ['b', 3] ]), _.filter(p) ), new Map([['b', 3]]) ) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' U.deepStrictEqual( pipe( new Map([ ['a', 1], ['b', 'foo'] ]), _.filter(isNumber) ), new Map([['a', 1]]) ) }) it('filterMap', () => { const empty = new Map() const f = (n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(pipe(empty, _.filterMap(f)), empty) U.deepStrictEqual( pipe( new Map([ ['a', 1], ['b', 3] ]), _.filterMap(f) ), new Map([['b', 4]]) ) }) it('partitionMap', () => { const empty = new Map() const f = (n: number) => (p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(pipe(empty, _.partitionMap(f)), separated(empty, empty)) U.deepStrictEqual( pipe( new Map([ ['a', 1], ['b', 3] ]), _.partitionMap(f) ), separated(new Map([['a', 0]]), new Map([['b', 4]])) ) }) it('partition', () => { const empty = new Map() U.deepStrictEqual(pipe(empty, _.partition(p)), separated(empty, empty)) U.deepStrictEqual( pipe( new Map([ ['a', 1], ['b', 3] ]), _.partition(p) ), separated(new Map([['a', 1]]), new Map([['b', 3]])) ) }) }) it('size', () => { const emptyMap = new Map() const a1 = new Map([['a', 1]]) U.deepStrictEqual(_.size(emptyMap), 0) U.deepStrictEqual(_.size(a1), 1) U.deepStrictEqual(_.size(_.empty), 0) U.deepStrictEqual(_.size(new Map()), 0) U.deepStrictEqual(_.size(new Map([['a', 1]])), 1) }) it('isEmpty', () => { const emptyMap = new Map() const a1 = new Map([['a', 1]]) U.deepStrictEqual(_.isEmpty(emptyMap), true) U.deepStrictEqual(_.isEmpty(a1), false) U.deepStrictEqual(_.isEmpty(_.empty), true) U.deepStrictEqual(_.isEmpty(new Map()), true) U.deepStrictEqual(_.isEmpty(new Map([['a', 1]])), false) }) it('member', () => { const x = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const memberS = _.member(eqUser) U.deepStrictEqual(memberS({ id: 'a' }, x), true) U.deepStrictEqual(memberS({ id: 'c' }, x), false) U.deepStrictEqual(memberS({ id: 'a' })(x), true) U.deepStrictEqual(memberS({ id: 'c' })(x), false) const member = _.member(eqKey) U.deepStrictEqual(member({ id: 1 }, repo), true) U.deepStrictEqual(member({ id: 2 }, repo), true) U.deepStrictEqual(member({ id: 4 }, repo), true) U.deepStrictEqual(member({ id: 3 }, repo), false) U.deepStrictEqual(member({ id: 1 })(repo), true) U.deepStrictEqual(member({ id: 2 })(repo), true) U.deepStrictEqual(member({ id: 4 })(repo), true) U.deepStrictEqual(member({ id: 3 })(repo), false) }) it('elem', () => { const x = new Map([ ['a', 1], ['b', 2] ]) const elemS = _.elem(N.Eq) U.deepStrictEqual(elemS(2, x), true) U.deepStrictEqual(elemS(3, x), false) U.deepStrictEqual(elemS(2)(x), true) U.deepStrictEqual(elemS(3)(x), false) const elem = _.elem(eqValue) U.deepStrictEqual(elem({ value: 1 })(repo), true) U.deepStrictEqual(elem({ value: 2 })(repo), true) U.deepStrictEqual(elem({ value: 4 })(repo), true) U.deepStrictEqual(elem({ value: 3 })(repo), false) U.deepStrictEqual(elem({ value: 1 })(repo), true) U.deepStrictEqual(elem({ value: 2 })(repo), true) U.deepStrictEqual(elem({ value: 4 })(repo), true) U.deepStrictEqual(elem({ value: 3 })(repo), false) }) it('keys', () => { const m = new Map([ [{ id: 'b' }, 2], [{ id: 'a' }, 1] ]) const ks = _.keys(ordUser)(m) U.deepStrictEqual(ks, Array.from(m.keys()).sort(ordUser.compare)) U.deepStrictEqual(ks, [{ id: 'a' }, { id: 'b' }]) U.deepStrictEqual( _.keys(S.Ord)( new Map([ ['a', 1], ['b', 2] ]) ), ['a', 'b'] ) U.deepStrictEqual( _.keys(S.Ord)( new Map([ ['b', 2], ['a', 1] ]) ), ['a', 'b'] ) }) it('values', () => { const m = new Map([ [2, { id: 'b' }], [1, { id: 'a' }] ]) const vals = _.values(ordUser)(m) U.deepStrictEqual(vals, Array.from(m.values()).sort(ordUser.compare)) U.deepStrictEqual(vals, [{ id: 'a' }, { id: 'b' }]) }) it('collect', () => { const m1 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const m2 = new Map([ [{ id: 'b' }, 2], [{ id: 'a' }, 1] ]) const collectO = _.collect(ordUser) const f = (_k: User, a: number): number => a + 1 U.deepStrictEqual(collectO(f)(m1), [2, 3]) U.deepStrictEqual(collectO(f)(m2), [2, 3]) const collect = _.collect(ordKey) const g = (k: Key, a: Value): readonly [number, number] => [k.id, a.value] U.deepStrictEqual( collect(g)( new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ), [ [1, 1], [2, 2] ] ) U.deepStrictEqual( collect(g)( new Map([ [{ id: 2 }, { value: 2 }], [{ id: 1 }, { value: 1 }] ]) ), [ [1, 1], [2, 2] ] ) U.deepStrictEqual( collect(g)( new Map([ [{ id: 4 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ), [ [4, 1], [2, 2] ] ) U.deepStrictEqual( collect(g)( new Map([ [{ id: 2 }, { value: 2 }], [{ id: 4 }, { value: 1 }] ]) ), [ [4, 1], [2, 2] ] ) }) it('toReadonlyArray', () => { const m1 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const m2 = new Map([ [{ id: 'b' }, 2], [{ id: 'a' }, 1] ]) const toArrayO = _.toReadonlyArray(ordUser) U.deepStrictEqual(toArrayO(m1), [ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) U.deepStrictEqual(toArrayO(m2), [ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const toArray = _.toReadonlyArray(ordKey) U.deepStrictEqual( toArray( new Map([ [{ id: 1 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toArray( new Map([ [{ id: 2 }, 2], [{ id: 1 }, 1] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toArray( new Map([ [{ id: 4 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toArray( new Map([ [{ id: 2 }, 2], [{ id: 4 }, 1] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) }) it('toUnfoldable', () => { const a1 = new Map([[{ id: 'a' }, 1]]) const toUnfoldableO = _.toUnfoldable(ordUser, RA.Unfoldable) U.deepStrictEqual(toUnfoldableO(a1), [[{ id: 'a' }, 1]]) const toUnfoldable = _.toUnfoldable(ordKey, RA.Unfoldable) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 1 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 2 }, 2], [{ id: 1 }, 1] ]) ), [ [{ id: 1 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 4 }, 1], [{ id: 2 }, 2] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) U.deepStrictEqual( toUnfoldable( new Map([ [{ id: 2 }, 2], [{ id: 4 }, 1] ]) ), [ [{ id: 4 }, 1], [{ id: 2 }, 2] ] ) }) it('insertAt', () => { const emptyMap = new Map() const a1 = new Map([[{ id: 'a' }, 1]]) const a1b2 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const a2b2 = new Map([ [{ id: 'a' }, 2], [{ id: 'b' }, 2] ]) const a1b2c3 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2], [{ id: 'c' }, 3] ]) const insertS = _.insertAt(eqUser) U.deepStrictEqual(insertS({ id: 'a' }, 1)(emptyMap), a1) U.deepStrictEqual(insertS({ id: 'a' }, 1)(a1b2), a1b2) U.deepStrictEqual(insertS({ id: 'a' }, 2)(a1b2), a2b2) U.deepStrictEqual(insertS({ id: 'c' }, 3)(a1b2), a1b2c3) const insert = _.insertAt(eqKey) U.deepStrictEqual(insert({ id: 1 }, { value: 1 })(_.empty), new Map([[{ id: 1 }, { value: 1 }]])) const x = insert({ id: 1 }, value1)(repo) U.deepStrictEqual( x, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual(x.get(key1), value1) U.deepStrictEqual( insert({ id: 1 }, { value: 2 })(repo), new Map([ [{ id: 1 }, { value: 2 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual( insert({ id: 4 }, { value: 2 })(repo), new Map([ [{ id: 1 }, { value: 2 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual( insert({ id: 3 }, { value: 3 })(repo), new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }], [{ id: 3 }, { value: 3 }] ]) ) // should not modify the source U.deepStrictEqual( repo, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) }) it('deleteAt', () => { const a1b2 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const a1b2_ = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const b2 = new Map([[{ id: 'b' }, 2]]) const removeS = _.deleteAt(eqUser) U.deepStrictEqual(removeS({ id: 'a' })(a1b2), b2) U.deepStrictEqual(a1b2, a1b2_) U.deepStrictEqual(removeS({ id: 'c' })(a1b2), a1b2) const remove = _.deleteAt(eqKey) U.deepStrictEqual(remove({ id: 1 })(repo), new Map([[{ id: 2 }, { value: 2 }]])) U.deepStrictEqual(remove({ id: 4 })(repo), new Map([[{ id: 2 }, { value: 2 }]])) U.deepStrictEqual(remove({ id: 3 })(repo), repo) // should not modify the source U.deepStrictEqual( repo, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) }) it('pop', () => { const a1b2 = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const b2 = new Map([[{ id: 'b' }, 2]]) const popS = _.pop(eqUser) assert.deepStrictEqual(popS({ id: 'a' })(a1b2), O.some([1, b2])) U.deepStrictEqual(popS({ id: 'c' })(a1b2), O.none) const pop = _.pop(eqKey) assert.deepStrictEqual(pop({ id: 1 })(repo), O.some([{ value: 1 }, new Map([[{ id: 2 }, { value: 2 }]])])) assert.deepStrictEqual(pop({ id: 4 })(repo), O.some([{ value: 1 }, new Map([[{ id: 2 }, { value: 2 }]])])) U.deepStrictEqual(pop({ id: 3 })(repo), O.none) // should not modify the source U.deepStrictEqual( repo, new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]) ) }) it('lookupWithKey', () => { const x = new Map([[{ id: 'a' }, 1]]) const lookupWithKeyS = _.lookupWithKey(eqUser) assert.deepStrictEqual(lookupWithKeyS({ id: 'a' }, x), O.some([{ id: 'a' }, 1])) U.deepStrictEqual(lookupWithKeyS({ id: 'b' }, x), O.none) assert.deepStrictEqual(lookupWithKeyS({ id: 'a' })(x), O.some([{ id: 'a' }, 1])) U.deepStrictEqual(lookupWithKeyS({ id: 'b' })(x), O.none) const lookupWithKey = _.lookupWithKey(eqKey) assert.deepStrictEqual(lookupWithKey({ id: 1 }, repo), O.some([{ id: 1 }, { value: 1 }])) assert.deepStrictEqual(lookupWithKey({ id: 4 }, repo), O.some([{ id: 1 }, { value: 1 }])) U.deepStrictEqual(lookupWithKey({ id: 3 }, repo), O.none) assert.deepStrictEqual(lookupWithKey({ id: 1 })(repo), O.some([{ id: 1 }, { value: 1 }])) assert.deepStrictEqual(lookupWithKey({ id: 4 })(repo), O.some([{ id: 1 }, { value: 1 }])) U.deepStrictEqual(lookupWithKey({ id: 3 })(repo), O.none) }) it('lookup', () => { const x = new Map([[{ id: 'a' }, 1]]) const lookupS = _.lookup(eqUser) U.deepStrictEqual(lookupS({ id: 'a' }, x), O.some(1)) U.deepStrictEqual(lookupS({ id: 'b' }, x), O.none) U.deepStrictEqual(lookupS({ id: 'a' })(x), O.some(1)) U.deepStrictEqual(lookupS({ id: 'b' })(x), O.none) const lookup = _.lookup(eqKey) U.deepStrictEqual(lookup({ id: 1 }, repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 4 }, repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 3 }, repo), O.none) U.deepStrictEqual(lookup({ id: 1 })(repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 4 })(repo), O.some({ value: 1 })) U.deepStrictEqual(lookup({ id: 3 })(repo), O.none) }) it('isSubmap', () => { const me = new Map([[{ id: 'a' }, 1]]) const that = new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 2] ]) const isSubmapS = _.isSubmap(eqUser, N.Eq) U.deepStrictEqual(isSubmapS(me, that), true) U.deepStrictEqual(isSubmapS(that)(me), true) const isSubmap = _.isSubmap(eqKey, eqValue) U.deepStrictEqual(isSubmap(new Map([[{ id: 1 }, { value: 1 }]]), repo), true) U.deepStrictEqual(isSubmap(new Map([[{ id: 1 }, { value: 2 }]]), repo), false) U.deepStrictEqual(isSubmap(new Map([[{ id: 1 }, { value: 4 }]]), repo), true) U.deepStrictEqual(isSubmap(new Map([[{ id: 4 }, { value: 1 }]]), repo), true) U.deepStrictEqual(isSubmap(new Map([[{ id: 3 }, { value: 3 }]]), repo), false) U.deepStrictEqual(pipe(new Map([[{ id: 1 }, { value: 1 }]]), isSubmap(repo)), true) U.deepStrictEqual(pipe(new Map([[{ id: 1 }, { value: 2 }]]), isSubmap(repo)), false) U.deepStrictEqual(pipe(new Map([[{ id: 1 }, { value: 4 }]]), isSubmap(repo)), true) U.deepStrictEqual(pipe(new Map([[{ id: 4 }, { value: 1 }]]), isSubmap(repo)), true) U.deepStrictEqual(pipe(new Map([[{ id: 3 }, { value: 3 }]]), isSubmap(repo)), false) }) it('empty', () => { assert.deepStrictEqual(_.empty, new Map()) U.deepStrictEqual(_.isEmpty(_.empty), true) }) it('singleton', () => { U.deepStrictEqual(_.singleton('k1', 0), new Map([['k1', 0]])) }) it('getEq', () => { const a1 = new Map([[{ id: 'a' }, 1]]) const a1_ = new Map([[{ id: 'a' }, 1]]) const a2 = new Map([[{ id: 'a' }, 2]]) const b1 = new Map([[{ id: 'b' }, 1]]) const S = _.getEq(eqUser, N.Eq) U.deepStrictEqual(S.equals(a1, a1), true) U.deepStrictEqual(S.equals(a1, a1_), true) U.deepStrictEqual(S.equals(a1_, a1), true) U.deepStrictEqual(S.equals(a1, a2), false) U.deepStrictEqual(S.equals(a2, a1), false) U.deepStrictEqual(S.equals(a1, b1), false) U.deepStrictEqual(S.equals(b1, a1), false) const equals = _.getEq(eqKey, eqValue).equals U.deepStrictEqual(equals(repo, repo), true) U.deepStrictEqual( equals( new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]), repo ), true ) U.deepStrictEqual( equals( new Map([ [{ id: 1 }, { value: 2 }], [{ id: 2 }, { value: 2 }] ]), repo ), false ) U.deepStrictEqual( equals( new Map([ [{ id: 1 }, { value: 4 }], [{ id: 2 }, { value: 2 }] ]), repo ), true ) U.deepStrictEqual( equals( new Map([ [{ id: 4 }, { value: 1 }], [{ id: 2 }, { value: 2 }] ]), repo ), true ) U.deepStrictEqual( equals( new Map([ [{ id: 3 }, { value: 3 }], [{ id: 2 }, { value: 2 }] ]), repo ), false ) }) it('getMonoid', () => { const d1 = new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 3] ]) const d2 = new Map([ [{ id: 'k2' }, 2], [{ id: 'k3' }, 4] ]) const expected = new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 5], [{ id: 'k3' }, 4] ]) const M1 = _.getMonoid(eqUser, N.SemigroupSum) U.deepStrictEqual(M1.concat(d1, d2), expected) U.deepStrictEqual(M1.concat(d1, M1.empty), d1) U.deepStrictEqual(M1.concat(M1.empty, d2), d2) const M2 = _.getMonoid(eqKey, semigroupValue) U.deepStrictEqual( M2.concat(repo, new Map([[{ id: 3 }, { value: 3 }]])), new Map([ [{ id: 1 }, { value: 1 }], [{ id: 2 }, { value: 2 }], [{ id: 3 }, { value: 3 }] ]) ) U.deepStrictEqual( M2.concat(repo, new Map([[{ id: 1 }, { value: 2 }]])), new Map([ [{ id: 1 }, { value: 3 }], [{ id: 2 }, { value: 2 }] ]) ) U.deepStrictEqual( M2.concat(repo, new Map([[{ id: 4 }, { value: 2 }]])), new Map([ [{ id: 1 }, { value: 3 }], [{ id: 2 }, { value: 2 }] ]) ) }) describe('readonlyMap', () => { describe('compactable', () => { it('compact', () => { const fooBar = new Map>([ ['foo', O.none], ['bar', O.some(123)] ]) const bar = new Map([['bar', 123]]) U.deepStrictEqual(_.compact(fooBar), bar) }) it('separate', () => { const fooBar = new Map>([ ['foo', left(123)], ['bar', right(123)] ]) const foo = new Map([['foo', 123]]) const bar = new Map([['bar', 123]]) U.deepStrictEqual(_.separate(fooBar), separated(foo, bar)) }) }) }) describe('getTraversable', () => { const T = _.getTraversable(ordUser) it('traverse', () => { const traverse = T.traverse(O.Applicative) const x = new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 2] ]) U.deepStrictEqual( traverse(x, (n) => (n <= 2 ? O.some(n) : O.none)), O.some(x) ) U.deepStrictEqual( traverse(x, (n) => (n >= 2 ? O.some(n) : O.none)), O.none ) }) it('sequence', () => { const sequence = T.sequence(O.Applicative) U.deepStrictEqual( sequence( new Map([ [{ id: 'k1' }, O.some(1)], [{ id: 'k2' }, O.some(2)] ]) ), O.some( new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 2] ]) ) ) U.deepStrictEqual( sequence( new Map([ [{ id: 'k1' }, O.none], [{ id: 'k2' }, O.some(2)] ]) ), O.none ) }) }) describe('getWitherable', () => { const W = _.getWitherable(ordUser) it('traverseWithIndex should sort the keys', () => { const W = _.getWitherable(S.Ord) const log: Array = [] const append = (message: string): IO.IO => () => { log.push(message) } W.traverseWithIndex(IO.Applicative)( new Map([ ['b', append('b')], ['a', append('a')] ]), (_, io) => io )() U.deepStrictEqual(log, ['a', 'b']) }) it('reduce', () => { const d1 = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) const reduceO = W.reduce U.deepStrictEqual( reduceO(d1, '', (b, a) => b + a), 'ab' ) const d2 = new Map([ [{ id: 'k2' }, 'b'], [{ id: 'k1' }, 'a'] ]) U.deepStrictEqual( reduceO(d2, '', (b, a) => b + a), 'ab' ) }) it('foldMap', () => { const foldMapOM = W.foldMap(S.Monoid) const m = new Map([ [{ id: 'a' }, 'a'], [{ id: 'a' }, 'b'] ]) U.deepStrictEqual(foldMapOM(m, identity), 'ab') }) it('reduceRight', () => { const reduceRightO = W.reduceRight const m = new Map([ [{ id: 'a' }, 'a'], [{ id: 'b' }, 'b'] ]) const init = '' const f = (a: string, acc: string) => acc + a U.deepStrictEqual(reduceRightO(m, init, f), 'ba') }) it('reduceWithIndex', () => { const d1 = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) const reduceWithIndexO = W.reduceWithIndex U.deepStrictEqual( reduceWithIndexO(d1, '', (k, b, a) => b + k.id + a), 'k1ak2b' ) const d2 = new Map([ [{ id: 'k2' }, 'b'], [{ id: 'k1' }, 'a'] ]) U.deepStrictEqual( reduceWithIndexO(d2, '', (k, b, a) => b + k.id + a), 'k1ak2b' ) }) it('foldMapWithIndex', () => { const foldMapWithIndexOM = W.foldMapWithIndex(S.Monoid) const m = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) U.deepStrictEqual( foldMapWithIndexOM(m, (k, a) => k.id + a), 'k1ak2b' ) }) it('reduceRightWithIndex', () => { const reduceRightWithIndexO = W.reduceRightWithIndex const m = new Map([ [{ id: 'k1' }, 'a'], [{ id: 'k2' }, 'b'] ]) U.deepStrictEqual( reduceRightWithIndexO(m, '', (k, a, b) => b + k.id + a), 'k2bk1a' ) }) it('traverseWithIndex', () => { const traverseWithIndex = W.traverseWithIndex(O.Applicative) U.deepStrictEqual( traverseWithIndex( new Map([ [{ id: 'k1' }, 1], [{ id: 'k2' }, 2] ]), (k, n): O.Option => (!ordUser.equals(k, { id: 'k1' }) ? O.some(n) : O.none) ), O.none ) U.deepStrictEqual( traverseWithIndex( new Map([ [{ id: 'k1' }, 2], [{ id: 'k2' }, 3] ]), (k, n): O.Option => (!ordUser.equals(k, { id: 'k3' }) ? O.some(n) : O.none) ), O.some( new Map([ [{ id: 'k1' }, 2], [{ id: 'k2' }, 3] ]) ) ) U.deepStrictEqual(_.empty, new Map()) }) it('wither', async () => { const wither = W.wither(T.ApplicativePar) const f = (n: number) => T.of(p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(await wither(_.empty, f)(), _.empty) U.deepStrictEqual( await wither( new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 3] ]), f )(), new Map([[{ id: 'b' }, 4]]) ) }) it('wilt', async () => { const wilt = W.wilt(T.ApplicativePar) const f = (n: number) => T.of(p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(await wilt(_.empty, f)(), separated(_.empty, _.empty)) U.deepStrictEqual( await wilt( new Map([ [{ id: 'a' }, 1], [{ id: 'b' }, 3] ]), f )(), separated(new Map([[{ id: 'a' }, 0]]), new Map([[{ id: 'b' }, 4]])) ) }) }) describe('getFilterableWithIndex', () => { it('partitionMapWithIndex', () => { const partitionMapWithIndex = _.getFilterableWithIndex().partitionMapWithIndex const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const a0 = new Map([['a', 0]]) const b4 = new Map([['b', 4]]) const f = (_: string, n: number) => (p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(partitionMapWithIndex(emptyMap, f), separated(emptyMap, emptyMap)) U.deepStrictEqual(partitionMapWithIndex(a1b3, f), separated(a0, b4)) }) it('partitionWithIndex', () => { const partitionWithIndex = _.getFilterableWithIndex().partitionWithIndex const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const a1 = new Map([['a', 1]]) const b3 = new Map([['b', 3]]) const f = (_: string, n: number) => p(n) U.deepStrictEqual(partitionWithIndex(emptyMap, f), separated(emptyMap, emptyMap)) U.deepStrictEqual(partitionWithIndex(a1b3, f), separated(a1, b3)) }) it('filterMapWithIndex', () => { const filterMapWithIndex = _.getFilterableWithIndex().filterMapWithIndex const emptyMap = new Map() const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const b4 = new Map([['b', 4]]) const f = (_: string, n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(filterMapWithIndex(emptyMap, f), emptyMap) U.deepStrictEqual(filterMapWithIndex(a1b3, f), b4) }) it('filterWithIndex', () => { const filterWithIndex = _.getFilterableWithIndex().filterWithIndex const a1b3 = new Map([ ['a', 1], ['b', 3] ]) const b3 = new Map([['b', 3]]) const f = (_: string, n: number) => p(n) U.deepStrictEqual(filterWithIndex(a1b3, f), b3) // refinements const filterWithIndexStr = _.getFilterableWithIndex().filterWithIndex const isNumber = (_: string, u: string | number): u is number => typeof u === 'number' const y = new Map([ ['a', 1], ['b', 'foo'] ]) const a1 = new Map([['a', 1]]) const actual = filterWithIndexStr(y, isNumber) U.deepStrictEqual(actual, a1) }) }) it('fromFoldable', () => { const a1 = new Map([[{ id: 'a' }, 1]]) const a2 = new Map([[{ id: 'a' }, 2]]) const fromFoldableS1 = _.fromFoldable(eqUser, Se.first(), RA.Foldable) U.deepStrictEqual(fromFoldableS1([[{ id: 'a' }, 1]]), a1) U.deepStrictEqual( fromFoldableS1([ [{ id: 'a' }, 1], [{ id: 'a' }, 2] ]), a1 ) const fromFoldableS2 = _.fromFoldable(eqUser, Se.last(), RA.Foldable) U.deepStrictEqual( fromFoldableS2([ [{ id: 'a' }, 1], [{ id: 'a' }, 2] ]), a2 ) }) it('getShow', () => { const showUser: Show = struct({ id: S.Show }) const Sh = _.getShow(showUser, S.Show) const m1 = new Map([]) U.deepStrictEqual(Sh.show(m1), `new Map([])`) const m2 = new Map([[{ id: 'a' }, 'b']]) U.deepStrictEqual(Sh.show(m2), `new Map([[{ id: "a" }, "b"]])`) const m3 = new Map([ [{ id: 'c' }, 'd'], [{ id: 'a' }, 'b'] ]) U.deepStrictEqual(Sh.show(m3), `new Map([[{ id: "a" }, "b"], [{ id: "c" }, "d"]])`) }) it('updateAt', () => { const m1 = new Map([]) U.deepStrictEqual(_.updateAt(eqUser)({ id: 'a' }, 'a')(m1), O.none) const m2 = new Map([[{ id: 'a' }, 'b']]) U.deepStrictEqual(_.updateAt(eqUser)({ id: 'a' }, 'a')(m2), O.some(new Map([[{ id: 'a' }, 'a']]))) }) it('modifyAt', () => { const m1 = new Map([]) U.deepStrictEqual(_.modifyAt(eqUser)({ id: 'a' }, (n: number) => n * 2)(m1), O.none) const m2 = new Map([[{ id: 'a' }, 1]]) U.deepStrictEqual( _.modifyAt(eqUser)({ id: 'a' }, (n: number) => n * 2)(m2), O.some(new Map([[{ id: 'a' }, 2]])) ) // should return the same reference if nothing changed const input: ReadonlyMap = new Map([['a', 1]]) U.deepStrictEqual( pipe( input, _.modifyAt(S.Eq)('a', identity), O.map((out) => out === input) ), O.some(true) ) }) it('fromMap', () => { const as = new Map([[1, 'a']]) const bs = _.fromMap(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('toMap', () => { const as: ReadonlyMap = new Map([[1, 'a']]) const bs = _.toMap(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('mapWithIndex', () => { const aa1 = new Map([[{ id: 'aa' }, 1]]) const aa3 = new Map([[{ id: 'aa' }, 3]]) U.deepStrictEqual( pipe( aa1, _.mapWithIndex((k, a) => a + k.id.length) ), aa3 ) }) it('getFunctorWithIndex', () => { const FWI = _.getFunctorWithIndex() const aa1 = new Map([[{ id: 'aa' }, 1]]) const aa3 = new Map([[{ id: 'aa' }, 3]]) U.deepStrictEqual( FWI.mapWithIndex(aa1, (k, a) => a + k.id.length), aa3 ) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(eqUser, S.Semigroup) const x = new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1'], [{ id: 'c' }, 'c1'] ]) const y = new Map([ [{ id: 'b' }, 'b2'], [{ id: 'c' }, 'c2'], [{ id: 'd' }, 'd2'] ]) U.strictEqual(M.concat(x, M.empty), x) U.strictEqual(M.concat(M.empty, x), x) U.strictEqual(M.concat(x, new Map()), x) U.strictEqual(M.concat(new Map(), x), x) U.deepStrictEqual( M.concat(x, y), new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1b2'], [{ id: 'c' }, 'c1c2'], [{ id: 'd' }, 'd2'] ]) ) }) it('getIntersectionSemigroup', () => { const M = _.getIntersectionSemigroup(eqUser, S.Semigroup) const x = new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1'], [{ id: 'c' }, 'c1'] ]) const y = new Map([ [{ id: 'b' }, 'b2'], [{ id: 'c' }, 'c2'], [{ id: 'd' }, 'd2'] ]) U.strictEqual(M.concat(x, _.empty), _.empty) U.strictEqual(M.concat(_.empty, x), _.empty) U.strictEqual(M.concat(x, new Map()), _.empty) U.strictEqual(M.concat(new Map(), x), _.empty) U.deepStrictEqual( M.concat(x, y), new Map([ [{ id: 'b' }, 'b1b2'], [{ id: 'c' }, 'c1c2'] ]) ) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma(eqUser)() const x = new Map([ [{ id: 'a' }, 'a1'], [{ id: 'b' }, 'b1'], [{ id: 'c' }, 'c1'] ]) const y = new Map([ [{ id: 'b' }, 'b2'], [{ id: 'c' }, 'c2'], [{ id: 'd' }, 'd2'] ]) U.strictEqual(M.concat(x, _.empty), x) U.strictEqual(M.concat(_.empty, x), x) U.strictEqual(M.concat(x, new Map()), x) U.strictEqual(M.concat(new Map(), x), x) U.deepStrictEqual( M.concat(x, y), new Map([ [{ id: 'a' }, 'a1'], [{ id: 'd' }, 'd2'] ]) ) }) }) ================================================ FILE: test/ReadonlyNonEmptyArray.ts ================================================ import * as assert from 'assert' import * as B from '../src/boolean' import { Endomorphism } from '../src/Endomorphism' import * as Eq from '../src/Eq' import { identity, pipe } from '../src/function' import * as N from '../src/number' import * as O from '../src/Option' import * as Ord from '../src/Ord' import * as _ from '../src/ReadonlyNonEmptyArray' import * as Se from '../src/Semigroup' import * as S from '../src/string' import * as U from './util' describe('ReadonlyNonEmptyArray', () => { describe('pipeables', () => { it('traverse', () => { assert.deepStrictEqual( pipe( [1, 2, 3], _.traverse(O.Applicative)((n) => (n >= 0 ? O.some(n) : O.none)) ), O.some([1, 2, 3]) ) U.deepStrictEqual( pipe( [1, 2, 3], _.traverse(O.Applicative)((n) => (n >= 2 ? O.some(n) : O.none)) ), O.none ) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) assert.deepStrictEqual(sequence([O.some(1), O.some(2), O.some(3)]), O.some([1, 2, 3])) U.deepStrictEqual(sequence([O.none, O.some(2), O.some(3)]), O.none) }) it('traverseWithIndex', () => { assert.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length >= 1 ? O.some(s + i) : O.none)) ), O.some(['a0', 'bb1']) ) U.deepStrictEqual( pipe( ['a', 'bb'], _.traverseWithIndex(O.Applicative)((i, s) => (s.length > 1 ? O.some(s + i) : O.none)) ), O.none ) }) }) it('head', () => { U.deepStrictEqual(_.head([1, 2]), 1) }) it('tail', () => { U.deepStrictEqual(_.tail([1, 2]), [2]) }) it('map', () => { U.deepStrictEqual( pipe( [1, 2], _.map((n) => n * 2) ), [2, 4] ) }) it('mapWithIndex', () => { const add = (i: number, n: number) => n + i U.deepStrictEqual(pipe([1, 2], _.mapWithIndex(add)), [1, 3]) }) it('of', () => { U.deepStrictEqual(_.of(1), [1]) }) it('ap', () => { const fab: _.ReadonlyNonEmptyArray<(n: number) => number> = [U.double, U.double] U.deepStrictEqual(pipe(fab, _.ap([1, 2])), [2, 4, 2, 4]) }) it('flatMap', () => { const f = (a: number): _.ReadonlyNonEmptyArray => [a, 4] U.deepStrictEqual(pipe([1, 2], _.flatMap(f)), [1, 4, 2, 4]) U.deepStrictEqual(_.flatMap([1, 2], f), [1, 4, 2, 4]) }) it('chain', () => { const f = (a: number): _.ReadonlyNonEmptyArray => [a, 4] U.deepStrictEqual(pipe([1, 2], _.chain(f)), [1, 4, 2, 4]) }) it('extend', () => { const sum = (as: _.ReadonlyNonEmptyArray): number => { const head = _.head(as) assert.ok(typeof (head as any) === 'number') return Se.concatAll(N.MonoidSum)(head)(_.tail(as)) } U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(sum)), [10, 9, 7, 4]) U.deepStrictEqual(pipe([1], _.extend(sum)), [1]) }) it('extract', () => { U.deepStrictEqual(_.extract([1, 2, 3]), 1) }) it('min', () => { U.deepStrictEqual(_.min(N.Ord)([2, 1, 3]), 1) U.deepStrictEqual(_.min(N.Ord)([3]), 3) }) it('max', () => { U.deepStrictEqual(_.max(N.Ord)([1, 2, 3]), 3) U.deepStrictEqual(_.max(N.Ord)([1]), 1) }) it('reduce', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduce('', (b, a) => b + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe(['a', 'b', 'c'], _.foldMap(S.Monoid)(identity)), 'abc') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(['a', 'b', 'c'], _.reduceRight('', f)), 'cba') }) it('fromReadonlyArray', () => { U.deepStrictEqual(_.fromReadonlyArray([]), O.none) assert.deepStrictEqual(_.fromReadonlyArray([1]), O.some([1])) assert.deepStrictEqual(_.fromReadonlyArray([1, 2]), O.some([1, 2])) }) it('getSemigroup', () => { const S = _.getSemigroup() U.deepStrictEqual(S.concat([1], [2]), [1, 2]) U.deepStrictEqual(S.concat([1, 2], [3, 4]), [1, 2, 3, 4]) }) it('getEq', () => { const S = _.getEq(N.Eq) U.deepStrictEqual(S.equals([1], [1]), true) U.deepStrictEqual(S.equals([1], [1, 2]), false) }) it('group', () => { U.deepStrictEqual(_.group(N.Eq)([]), []) U.deepStrictEqual(_.group(N.Eq)([1, 2, 1, 1]), [[1], [2], [1, 1]]) U.deepStrictEqual(_.group(N.Eq)([1, 2, 1, 1, 3]), [[1], [2], [1, 1], [3]]) }) it('groupSort', () => { U.deepStrictEqual(_.groupSort(N.Ord)([]), []) U.deepStrictEqual(_.groupSort(N.Ord)([1, 2, 1, 1]), [[1, 1, 1], [2]]) }) it('last', () => { U.deepStrictEqual(_.last([1, 2, 3]), 3) U.deepStrictEqual(_.last([1]), 1) }) it('init', () => { U.deepStrictEqual(_.init([1, 2, 3]), [1, 2]) U.deepStrictEqual(_.init([1]), []) }) it('sort', () => { const sort = _.sort(N.Ord) U.deepStrictEqual(sort([3, 2, 1]), [1, 2, 3]) // should optimize `1`-length `ReadonlyNonEmptyArray`s const singleton: _.ReadonlyNonEmptyArray = [1] U.strictEqual(sort(singleton), singleton) }) it('prependAll', () => { U.deepStrictEqual(_.prependAll(0)([1, 2, 3]), [0, 1, 0, 2, 0, 3]) U.deepStrictEqual(_.prependAll(0)([1]), [0, 1]) U.deepStrictEqual(_.prependAll(0)([1, 2, 3, 4]), [0, 1, 0, 2, 0, 3, 0, 4]) }) it('intersperse', () => { U.deepStrictEqual(_.intersperse(0)([1, 2, 3]), [1, 0, 2, 0, 3]) U.deepStrictEqual(_.intersperse(0)([1]), [1]) U.deepStrictEqual(_.intersperse(0)([1, 2]), [1, 0, 2]) U.deepStrictEqual(_.intersperse(0)([1, 2, 3, 4]), [1, 0, 2, 0, 3, 0, 4]) }) it('intercalate', () => { U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a']), 'a') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', 'b', 'c']), 'a-b-c') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', '', 'c']), 'a--c') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', 'b']), 'a-b') U.deepStrictEqual(_.intercalate(S.Semigroup)('-')(['a', 'b', 'c', 'd']), 'a-b-c-d') }) it('reverse', () => { const singleton: _.ReadonlyNonEmptyArray = [1] U.strictEqual(_.reverse(singleton), singleton) U.deepStrictEqual(_.reverse([1, 2, 3]), [3, 2, 1]) }) it('groupBy', () => { U.deepStrictEqual(_.groupBy((_) => '')([]), {}) U.deepStrictEqual(_.groupBy(String)([1]), { '1': [1] }) U.deepStrictEqual(_.groupBy((s: string) => String(s.length))(['foo', 'bar', 'foobar']), { '3': ['foo', 'bar'], '6': ['foobar'] }) }) it('insertAt', () => { const make = (x: number) => ({ x }) const a1 = make(1) const a2 = make(1) const a3 = make(2) const a4 = make(3) U.deepStrictEqual(pipe([], _.insertAt(1, 1)), O.none) assert.deepStrictEqual(_.insertAt(0, a4)([a1, a2, a3]), O.some([a4, a1, a2, a3])) U.deepStrictEqual(_.insertAt(-1, a4)([a1, a2, a3]), O.none) assert.deepStrictEqual(_.insertAt(3, a4)([a1, a2, a3]), O.some([a1, a2, a3, a4])) assert.deepStrictEqual(_.insertAt(1, a4)([a1, a2, a3]), O.some([a1, a4, a2, a3])) U.deepStrictEqual(_.insertAt(4, a4)([a1, a2, a3]), O.none) }) it('updateAt', () => { const make2 = (x: number) => ({ x }) const a1 = make2(1) const a2 = make2(1) const a3 = make2(2) const a4 = make2(3) const arr: _.ReadonlyNonEmptyArray<{ readonly x: number }> = [a1, a2, a3] assert.deepStrictEqual(_.updateAt(0, a4)(arr), O.some([a4, a2, a3])) U.deepStrictEqual(_.updateAt(-1, a4)(arr), O.none) U.deepStrictEqual(_.updateAt(3, a4)(arr), O.none) assert.deepStrictEqual(_.updateAt(1, a4)(arr), O.some([a1, a4, a3])) // should return the same reference if nothing changed const r1 = _.updateAt(0, a1)(arr) if (O.isSome(r1)) { U.deepStrictEqual(r1.value, arr) } else { assert.fail('is not a Some') } const r2 = _.updateAt(2, a3)(arr) if (O.isSome(r2)) { U.deepStrictEqual(r2.value, arr) } else { assert.fail('is not a Some') } }) it('modifyAt', () => { U.deepStrictEqual(_.modifyAt(1, U.double)([1]), O.none) U.deepStrictEqual(_.modifyAt(1, U.double)([1, 2]), O.some([1, 4] as const)) // should return the same reference if nothing changed const input: _.ReadonlyNonEmptyArray = [1, 2, 3] U.deepStrictEqual( pipe( input, _.modifyAt(1, identity), O.map((out) => out === input) ), O.some(true) ) }) it('filter', () => { const make = (x: number) => ({ x }) const a1 = make(1) const a2 = make(1) const a3 = make(2) assert.deepStrictEqual(_.filter(({ x }) => x !== 1)([a1, a2, a3]), O.some([a3])) assert.deepStrictEqual(_.filter(({ x }) => x !== 2)([a1, a2, a3]), O.some([a1, a2])) U.deepStrictEqual( _.filter(({ x }) => { return !(x === 1 || x === 2) })([a1, a2, a3]), O.none ) assert.deepStrictEqual(_.filter(({ x }) => x !== 10)([a1, a2, a3]), O.some([a1, a2, a3])) // refinements const actual1 = _.filter(O.isSome)([O.some(3), O.some(2), O.some(1)]) assert.deepStrictEqual(actual1, O.some([O.some(3), O.some(2), O.some(1)])) const actual2 = _.filter(O.isSome)([O.some(3), O.none, O.some(1)]) assert.deepStrictEqual(actual2, O.some([O.some(3), O.some(1)])) }) it('filterWithIndex', () => { assert.deepStrictEqual(_.filterWithIndex((i) => i % 2 === 0)([1, 2, 3]), O.some([1, 3])) U.deepStrictEqual(_.filterWithIndex((i, a: number) => i % 2 === 1 && a > 2)([1, 2, 3]), O.none) }) it('reduceWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceWithIndex('', (i, b, a) => b + i + a) ), '0a1b' ) }) it('foldMapWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.foldMapWithIndex(S.Monoid)((i, a) => i + a) ), '0a1b' ) }) it('reduceRightWithIndex', () => { U.deepStrictEqual( pipe( ['a', 'b'], _.reduceRightWithIndex('', (i, a, b) => b + i + a) ), '1b0a' ) }) it('cons', () => { U.deepStrictEqual(_.cons(1, [2, 3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(pipe([2, 3, 4], _.cons(1)), [1, 2, 3, 4]) }) it('snoc', () => { U.deepStrictEqual(_.snoc([], 0), [0]) U.deepStrictEqual(_.snoc([1, 2, 3], 4), [1, 2, 3, 4]) }) it('unprepend', () => { U.deepStrictEqual(_.unprepend([0]), [0, []]) U.deepStrictEqual(_.unprepend([1, 2, 3, 4]), [1, [2, 3, 4]]) }) it('unappend', () => { U.deepStrictEqual(_.unappend([0]), [[], 0]) U.deepStrictEqual(_.unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) U.deepStrictEqual(_.unappend([0]), [[], 0]) U.deepStrictEqual(_.unappend([1, 2, 3, 4]), [[1, 2, 3], 4]) }) it('getShow', () => { const Sh = _.getShow(S.Show) U.deepStrictEqual(Sh.show(['a']), `["a"]`) U.deepStrictEqual(Sh.show(['a', 'b', 'c']), `["a", "b", "c"]`) }) it('alt', () => { U.deepStrictEqual( pipe( ['a'], _.alt(() => ['b']) ), ['a', 'b'] ) }) it('foldMap', () => { const f = _.foldMap(N.SemigroupSum)((s: string) => s.length) U.deepStrictEqual(f(['a']), 1) U.deepStrictEqual(f(['a', 'bb']), 3) }) it('foldMapWithIndex', () => { const f = _.foldMapWithIndex(N.SemigroupSum)((i: number, s: string) => s.length + i) U.deepStrictEqual(f(['a']), 1) U.deepStrictEqual(f(['a', 'bb']), 4) }) it('fromArray', () => { U.strictEqual(_.fromArray([]), O.none) const as = [1, 2, 3] const bs = _.fromArray(as) assert.deepStrictEqual(bs, O.some(as)) assert.notStrictEqual((bs as any).value, as) }) it('fromReadonlyArray', () => { const as: ReadonlyArray = [1, 2, 3] const bs = _.fromReadonlyArray(as) U.deepStrictEqual(bs, O.some(as)) U.strictEqual((bs as any).value, as) }) it('concatAll', () => { const f = _.concatAll(S.Semigroup) U.deepStrictEqual(f(['a']), 'a') U.deepStrictEqual(f(['a', 'bb']), 'abb') }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) ), [{ a: 1, b: 'b', c: [1, 'b'] }] ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b'))), [{ a: 1, b: 'b' }]) }) it('zipWith', () => { U.deepStrictEqual( _.zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n), ['a1', 'b2', 'c3'] ) }) it('zip', () => { U.deepStrictEqual(_.zip([1, 2, 3], ['a', 'b', 'c', 'd']), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) U.deepStrictEqual(pipe([1, 2, 3] as const, _.zip(['a', 'b', 'c', 'd'])), [ [1, 'a'], [2, 'b'], [3, 'c'] ]) }) it('unzip', () => { U.deepStrictEqual( _.unzip([ [1, 'a'], [2, 'b'], [3, 'c'] ]), [ [1, 2, 3], ['a', 'b', 'c'] ] ) }) it('splitAt', () => { const assertSplitAt = ( input: _.ReadonlyNonEmptyArray, index: number, expectedInit: ReadonlyArray, expectedRest: ReadonlyArray ) => { const [init, rest] = _.splitAt(index)(input) U.strictEqual(init, expectedInit) U.strictEqual(rest, expectedRest) } const two: _.ReadonlyNonEmptyArray = [1, 2] U.deepStrictEqual(_.splitAt(1)(two), [[1], [2]]) assertSplitAt(two, 2, two, _.empty) const singleton: _.ReadonlyNonEmptyArray = [1] assertSplitAt(singleton, 1, singleton, _.empty) // out of bounds assertSplitAt(singleton, 0, singleton, _.empty) assertSplitAt(singleton, 2, singleton, _.empty) U.deepStrictEqual(_.splitAt(0)(two), [[1], [2]]) assertSplitAt(two, 3, two, _.empty) }) it('chunksOf', () => { U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]]) U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5, 6]), [ [1, 2], [3, 4], [5, 6] ]) U.deepStrictEqual(_.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]]) // out of bounds U.deepStrictEqual(_.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) U.deepStrictEqual(_.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]]) const assertSingleChunk = (input: _.ReadonlyNonEmptyArray, n: number) => { const chunks = _.chunksOf(n)(input) U.strictEqual(chunks.length, 1) U.strictEqual(_.head(chunks), input) } // n = length assertSingleChunk([1, 2], 2) // n out of bounds assertSingleChunk([1, 2], 3) }) it('rotate', () => { const singleton: _.ReadonlyNonEmptyArray = [1] U.strictEqual(_.rotate(1)(singleton), singleton) U.strictEqual(_.rotate(2)(singleton), singleton) U.strictEqual(_.rotate(-1)(singleton), singleton) U.strictEqual(_.rotate(-2)(singleton), singleton) const two: _.ReadonlyNonEmptyArray = [1, 2] U.strictEqual(_.rotate(2)(two), two) U.strictEqual(_.rotate(0)(two), two) U.strictEqual(_.rotate(-2)(two), two) U.deepStrictEqual(_.rotate(1)([1, 2]), [2, 1]) U.deepStrictEqual(_.rotate(1)([1, 2, 3, 4, 5]), [5, 1, 2, 3, 4]) U.deepStrictEqual(_.rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-1)([1, 2, 3, 4, 5]), [2, 3, 4, 5, 1]) U.deepStrictEqual(_.rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) U.deepStrictEqual(_.rotate(7)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-7)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) U.deepStrictEqual(_.rotate(2.2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3]) U.deepStrictEqual(_.rotate(-2.2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2]) }) it('uniq', () => { interface A { readonly a: string readonly b: number } const eqA = pipe( N.Eq, Eq.contramap((f: A) => f.b) ) const arrA: A = { a: 'a', b: 1 } const arrB: A = { a: 'b', b: 1 } const arrC: A = { a: 'c', b: 2 } const arrD: A = { a: 'd', b: 2 } const arrUniq: _.ReadonlyNonEmptyArray = [arrA, arrC] U.deepStrictEqual(_.uniq(eqA)(arrUniq), arrUniq) U.deepStrictEqual(_.uniq(eqA)([arrA, arrB, arrC, arrD]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrB, arrA, arrC, arrD]), [arrB, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrA, arrA, arrC, arrD, arrA]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrA, arrC]), [arrA, arrC]) U.deepStrictEqual(_.uniq(eqA)([arrC, arrA]), [arrC, arrA]) U.deepStrictEqual(_.uniq(B.Eq)([true, false, true, false]), [true, false]) U.deepStrictEqual(_.uniq(N.Eq)([-0, -0]), [-0]) U.deepStrictEqual(_.uniq(N.Eq)([0, -0]), [0]) U.deepStrictEqual(_.uniq(N.Eq)([1]), [1]) U.deepStrictEqual(_.uniq(N.Eq)([2, 1, 2]), [2, 1]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 1]), [1, 2]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(N.Eq)([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'a']), ['a', 'b']) U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'A']), ['a', 'b', 'A']) const as: _.ReadonlyNonEmptyArray = [1] U.strictEqual(_.uniq(N.Eq)(as), as) }) it('sortBy', () => { interface X { readonly a: string readonly b: number readonly c: boolean } const byName = pipe( S.Ord, Ord.contramap((p: { readonly a: string; readonly b: number }) => p.a) ) const byAge = pipe( N.Ord, Ord.contramap((p: { readonly a: string; readonly b: number }) => p.b) ) const f = _.sortBy([byName, byAge]) const xs: _.ReadonlyNonEmptyArray = [ { a: 'a', b: 1, c: true }, { a: 'b', b: 3, c: true }, { a: 'c', b: 2, c: true }, { a: 'b', b: 2, c: true } ] U.deepStrictEqual(f(xs), [ { a: 'a', b: 1, c: true }, { a: 'b', b: 2, c: true }, { a: 'b', b: 3, c: true }, { a: 'c', b: 2, c: true } ]) const sortByAgeByName = _.sortBy([byAge, byName]) U.deepStrictEqual(sortByAgeByName(xs), [ { a: 'a', b: 1, c: true }, { a: 'b', b: 2, c: true }, { a: 'c', b: 2, c: true }, { a: 'b', b: 3, c: true } ]) U.deepStrictEqual(_.sortBy([])(xs), xs) }) it('union', () => { const concat = _.getUnionSemigroup(N.Eq).concat U.deepStrictEqual(concat([1, 2], [3, 4]), [1, 2, 3, 4]) U.deepStrictEqual(concat([1, 2], [2, 3]), [1, 2, 3]) U.deepStrictEqual(concat([1, 2], [1, 2]), [1, 2]) }) it('matchLeft', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.matchLeft((head, tail) => [head, tail]) ), [1, [2, 3]] ) }) it('matchRight', () => { U.deepStrictEqual( pipe( [1, 2, 3], _.matchRight((init, last) => [init, last]) ), [[1, 2], 3] ) }) it('modifyHead', () => { const f: Endomorphism = (s) => s + '!' U.deepStrictEqual(pipe(['a'], _.modifyHead(f)), ['a!']) U.deepStrictEqual(pipe(['a', 'b'], _.modifyHead(f)), ['a!', 'b']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.modifyHead(f)), ['a!', 'b', 'c']) }) it('modifyLast', () => { const f: Endomorphism = (s) => s + '!' U.deepStrictEqual(pipe(['a'], _.modifyLast(f)), ['a!']) U.deepStrictEqual(pipe(['a', 'b'], _.modifyLast(f)), ['a', 'b!']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.modifyLast(f)), ['a', 'b', 'c!']) }) it('makeBy', () => { const f = _.makeBy(U.double) U.deepStrictEqual(f(5), [0, 2, 4, 6, 8]) // If `n` (must be a natural number) is non positive return `[f(0)]`. U.deepStrictEqual(f(0), [0]) U.deepStrictEqual(f(-1), [0]) }) it('range', () => { U.deepStrictEqual(_.range(0, 0), [0]) U.deepStrictEqual(_.range(0, 1), [0, 1]) U.deepStrictEqual(_.range(1, 5), [1, 2, 3, 4, 5]) U.deepStrictEqual(_.range(10, 15), [10, 11, 12, 13, 14, 15]) U.deepStrictEqual(_.range(-1, 0), [-1, 0]) U.deepStrictEqual(_.range(-5, -1), [-5, -4, -3, -2, -1]) // out of bound U.deepStrictEqual(_.range(2, 1), [2]) U.deepStrictEqual(_.range(-1, -2), [-1]) }) it('replicate', () => { const f = _.replicate('a') U.deepStrictEqual(pipe(0, f), ['a']) U.deepStrictEqual(pipe(1, f), ['a']) U.deepStrictEqual(pipe(2, f), ['a', 'a']) }) it('updateHead', () => { U.deepStrictEqual(pipe(['a'], _.updateHead('d')), ['d']) U.deepStrictEqual(pipe(['a', 'b'], _.updateHead('d')), ['d', 'b']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.updateHead('d')), ['d', 'b', 'c']) }) it('updateLast', () => { U.deepStrictEqual(pipe(['a'], _.updateLast('d')), ['d']) U.deepStrictEqual(pipe(['a', 'b'], _.updateLast('d')), ['a', 'd']) U.deepStrictEqual(pipe(['a', 'b', 'c'], _.updateLast('d')), ['a', 'b', 'd']) }) it('concatW', () => { U.deepStrictEqual(pipe(['a'], _.concatW(['b'])), ['a', 'b']) }) it('concat', () => { U.deepStrictEqual(pipe(['a'], _.concat(['b'])), ['a', 'b']) U.deepStrictEqual(pipe(_.empty, _.concat(['b'])), ['b']) U.deepStrictEqual(pipe(['a'], _.concat(_.empty)), ['a']) U.deepStrictEqual(_.concat(['a'], ['b']), ['a', 'b']) U.deepStrictEqual(_.concat(['a'], _.empty), ['a']) U.deepStrictEqual(_.concat(_.empty, ['b']), ['b']) }) it('isOutOfBound', () => { U.deepStrictEqual(_.isOutOfBound(0, ['a']), false) U.deepStrictEqual(_.isOutOfBound(100, ['a']), true) U.deepStrictEqual(_.isOutOfBound(-1, ['a']), true) }) }) ================================================ FILE: test/ReadonlyRecord.ts ================================================ import * as assert from 'assert' import * as E from '../src/Either' import { identity, pipe } from '../src/function' import * as IO from '../src/IO' import * as N from '../src/number' import * as O from '../src/Option' import { reverse } from '../src/Ord' import * as RA from '../src/ReadonlyArray' import * as _ from '../src/ReadonlyRecord' import * as Se from '../src/Semigroup' import { separated } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' const p = (n: number) => n > 2 const noPrototype = Object.create(null) describe('ReadonlyRecord', () => { describe('pipeables', () => { it('collect', () => { const x: { readonly a: string; readonly b: boolean } = { a: 'c', b: false } U.deepStrictEqual(_.collect(S.Ord)((key, val) => ({ key: key, value: val }))(x), [ { key: 'a', value: 'c' }, { key: 'b', value: false } ]) U.deepStrictEqual(_.collect((key, val) => ({ key: key, value: val }))(x), [ { key: 'a', value: 'c' }, { key: 'b', value: false } ]) }) it('map', () => { U.deepStrictEqual(pipe({ k1: 1, k2: 2 }, _.map(U.double)), { k1: 2, k2: 4 }) U.deepStrictEqual(pipe({ a: 1, b: 2 }, _.map(U.double)), { a: 2, b: 4 }) U.deepStrictEqual(_.Functor.map({ a: 1, b: 2 }, U.double), { a: 2, b: 4 }) }) it('reduce', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduce(S.Ord)('', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduce(S.Ord)('', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduce('', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduce('', (b, a) => b + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.foldMap(S.Ord)(S.Monoid)(identity)), 'ab') U.deepStrictEqual(_.getFoldable(S.Ord).foldMap(S.Monoid)({ a: 'a', b: 'b' }, identity), 'ab') U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.foldMap(S.Monoid)(identity)), 'ab') U.deepStrictEqual(_.Foldable.foldMap(S.Monoid)({ a: 'a', b: 'b' }, identity), 'ab') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.reduceRight(S.Ord)('', f)), 'ba') U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.reduceRight('', f)), 'ba') }) it('compact', () => { U.deepStrictEqual(_.compact({ foo: O.none, bar: O.some(123) }), { bar: 123 }) // should ignore non own properties const o: _.ReadonlyRecord> = Object.create({ a: 1 }) U.deepStrictEqual(pipe(o, _.compact), {}) }) it('separate', () => { U.deepStrictEqual(_.separate({ foo: E.left(123), bar: E.right(123) }), separated({ foo: 123 }, { bar: 123 })) // should ignore non own properties const o: _.ReadonlyRecord> = Object.create({ a: 1 }) U.deepStrictEqual(pipe(o, _.separate), separated({}, {})) }) it('filter', () => { const d = { a: 1, b: 3 } U.deepStrictEqual(pipe(d, _.filter(p)), { b: 3 }) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const y: _.ReadonlyRecord = { a: 1, b: 'foo' } const actual = pipe(y, _.filter(isNumber)) U.deepStrictEqual(actual, { a: 1 }) U.deepStrictEqual( pipe( y, _.filter((_) => true) ), y ) const x = Object.assign(Object.create({ c: true }), { a: 1, b: 'foo' }) U.deepStrictEqual(pipe(x, _.filter(isNumber)), { a: 1 }) U.deepStrictEqual(pipe(noPrototype, _.filter(isNumber)), noPrototype) }) it('filterMap', () => { const f = (n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(pipe({}, _.filterMap(f)), {}) U.deepStrictEqual(pipe({ a: 1, b: 3 }, _.filterMap(f)), { b: 4 }) }) it('partition', () => { U.deepStrictEqual(pipe({}, _.partition(p)), separated({}, {})) U.deepStrictEqual(pipe({ a: 1, b: 3 }, _.partition(p)), separated({ a: 1 }, { b: 3 })) }) it('partitionMap', () => { const f = (n: number) => (p(n) ? E.right(n + 1) : E.left(n - 1)) U.deepStrictEqual(pipe({}, _.partitionMap(f)), separated({}, {})) U.deepStrictEqual(pipe({ a: 1, b: 3 }, _.partitionMap(f)), separated({ a: 0 }, { b: 4 })) }) it('reduceWithIndex', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceWithIndex(S.Ord)('', (k, b, a) => b + k + a) ), 'k1ak2b' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduceWithIndex(S.Ord)('', (k, b, a) => b + k + a) ), 'k1ak2b' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceWithIndex('', (k, b, a) => b + k + a) ), 'k1ak2b' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduceWithIndex('', (k, b, a) => b + k + a) ), 'k1ak2b' ) }) it('foldMapWithIndex', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.foldMapWithIndex(S.Ord)(S.Monoid)((k, a) => k + a) ), 'k1ak2b' ) U.deepStrictEqual( _.getFoldableWithIndex(S.Ord).foldMapWithIndex(S.Monoid)({ k1: 'a', k2: 'b' }, (k, a) => k + a), 'k1ak2b' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.foldMapWithIndex(S.Monoid)((k, a) => k + a) ), 'k1ak2b' ) U.deepStrictEqual( _.FoldableWithIndex.foldMapWithIndex(S.Monoid)({ k1: 'a', k2: 'b' }, (k, a) => k + a), 'k1ak2b' ) }) it('reduceRightWithIndex', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceRightWithIndex(S.Ord)('', (k, a, b) => b + k + a) ), 'k2bk1a' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceRightWithIndex('', (k, a, b) => b + k + a) ), 'k2bk1a' ) }) it('partitionMapWithIndex', () => { const f = _.partitionMapWithIndex((k, a: number) => (a > 1 ? E.right(a) : E.left(k))) U.deepStrictEqual(pipe({ a: 1, b: 2 }, f), separated({ a: 'a' }, { b: 2 })) // should ignore non own properties const o: _.ReadonlyRecord = Object.create({ a: 1 }) U.deepStrictEqual(pipe(o, f), separated({}, {})) }) it('partitionWithIndex', () => { const f = _.partitionWithIndex((_, a: number) => a > 1) U.deepStrictEqual(pipe({ a: 1, b: 2 }, f), separated({ a: 1 }, { b: 2 })) // should ignore non own properties const o: _.ReadonlyRecord = Object.create({ a: 1 }) U.deepStrictEqual(pipe(o, f), separated({}, {})) }) it('filterMapWithIndex', () => { const f = _.filterMapWithIndex((_, a: number) => (a > 1 ? O.some(a) : O.none)) U.deepStrictEqual(pipe({ a: 1, b: 2 }, f), { b: 2 }) // should ignore non own properties const o: _.ReadonlyRecord = Object.create({ a: 1 }) U.deepStrictEqual(pipe(o, f), {}) }) it('filterWithIndex', () => { U.deepStrictEqual( pipe( { a: 1, b: 2 }, _.filterWithIndex((_, a: number) => a > 1) ), { b: 2 } ) }) it('traverse', () => { U.deepStrictEqual( _.traverse(O.Applicative)((n: number) => (n <= 2 ? O.some(n) : O.none))({ a: 1, b: 2 }), O.some({ a: 1, b: 2 }) ) U.deepStrictEqual(_.traverse(O.Applicative)((n: number) => (n >= 2 ? O.some(n) : O.none))({ a: 1, b: 2 }), O.none) }) it('getTraversable', () => { const T = _.getTraversable(reverse(S.Ord)) const f = (n: number) => (n <= 2 ? O.some(n) : O.none) U.deepStrictEqual(T.traverse(O.Applicative)({ a: 1, b: 2 }, f), O.some({ a: 1, b: 2 })) U.deepStrictEqual(T.traverse(O.Applicative)({ a: 1, b: 3 }, f), O.none) // should respect the order U.deepStrictEqual(pipe(T.traverse(O.Applicative)({ b: 2, a: 1 }, f), O.map(Object.keys)), O.some(['b', 'a'])) U.deepStrictEqual( pipe(T.sequence(O.Applicative)({ b: O.some(2), a: O.some(1) }), O.map(Object.keys)), O.some(['b', 'a']) ) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence({ a: O.some(1), b: O.some(2) }), O.some({ a: 1, b: 2 })) U.deepStrictEqual(sequence({ a: O.none, b: O.some(2) }), O.none) U.deepStrictEqual( _.readonlyRecord.sequence(O.Applicative)({ a: O.some(1), b: O.some(2) }), O.some({ a: 1, b: 2 }) ) }) describe('traverseWithIndex', () => { it('simple Traversal', () => { const f = (k: string, n: number): O.Option => (k !== 'a' ? O.some(n) : O.none) const traverseWithIndex = _.traverseWithIndex(O.Applicative)(f) U.deepStrictEqual(pipe({ a: 1, b: 2 }, traverseWithIndex), O.none) U.deepStrictEqual(pipe({ b: 2 }, traverseWithIndex), O.some({ b: 2 })) }) it('should not modify arrays in place', () => { const result = pipe( { a: 2, b: 3 }, _.fromRecord, _.traverseWithIndex(RA.Applicative)((_, n) => RA.makeBy(n, (i) => i * 4)) ) U.deepStrictEqual(result, [ { a: 0, b: 0 }, { a: 0, b: 4 }, { a: 0, b: 8 }, { a: 4, b: 0 }, { a: 4, b: 4 }, { a: 4, b: 8 } ]) }) }) it('getTraversableWithIndex', () => { const TWI = _.getTraversableWithIndex(reverse(S.Ord)) const f = (k: string, n: number): O.Option => (k !== 'a' ? O.some(n) : O.none) U.deepStrictEqual(TWI.traverseWithIndex(O.Applicative)({ b: 2 }, f), O.some({ b: 2 })) U.deepStrictEqual(TWI.traverseWithIndex(O.Applicative)({ a: 1, b: 2 }, f), O.none) // should respect the order U.deepStrictEqual( pipe(TWI.traverseWithIndex(O.Applicative)({ b: 2, c: 1 }, f), O.map(Object.keys)), O.some(['c', 'b']) ) }) it('wither', async () => { const f = (n: number) => T.of(p(n) ? O.some(n + 1) : O.none) const wither = _.wither(T.ApplicativePar)(f) U.deepStrictEqual(await pipe({}, wither)(), {}) U.deepStrictEqual(await pipe({ a: 1, b: 3 }, wither)(), { b: 4 }) U.deepStrictEqual(await _.getWitherable(S.Ord).wither(T.ApplicativePar)({ a: 1, b: 3 }, f)(), { b: 4 }) }) it('wilt', async () => { const wilt = _.wilt(T.ApplicativePar)((n: number) => T.of(p(n) ? E.right(n + 1) : E.left(n - 1))) U.deepStrictEqual(await pipe({}, wilt)(), separated({}, {})) U.deepStrictEqual(await pipe({ a: 1, b: 3 }, wilt)(), separated({ a: 0 }, { b: 4 })) }) }) it('getMonoid', () => { const d1 = { k1: 1, k2: 3 } const d2 = { k2: 2, k3: 4 } const M = _.getMonoid(N.SemigroupSum) U.deepStrictEqual(M.concat(d1, d2), { k1: 1, k2: 5, k3: 4 }) U.deepStrictEqual(M.concat(d1, M.empty), d1) U.deepStrictEqual(M.concat(M.empty, d2), d2) U.deepStrictEqual(M.concat(d1, {}), d1) // should ignore non own properties const o = Object.create({ a: 1 }) o.k2 = 2 o.k3 = 4 U.deepStrictEqual(M.concat(d1, o), { k1: 1, k2: 5, k3: 4 }) }) it('getEq', () => { U.deepStrictEqual(_.getEq(N.Eq).equals({ a: 1 }, { a: 1 }), true) U.deepStrictEqual(_.getEq(N.Eq).equals({ a: 1 }, { a: 2 }), false) U.deepStrictEqual(_.getEq(N.Eq).equals({ a: 1 }, { b: 1 }), false) U.deepStrictEqual(_.getEq(N.Eq).equals(noPrototype, { b: 1 }), false) }) it('lookup', () => { U.deepStrictEqual(_.lookup('a', { a: 1 }), O.some(1)) U.deepStrictEqual(_.lookup('b', { a: 1 }), O.none) U.deepStrictEqual(_.lookup('b', noPrototype), O.none) U.deepStrictEqual(_.lookup('a')({ a: 1 }), O.some(1)) U.deepStrictEqual(_.lookup('b')({ a: 1 }), O.none) U.deepStrictEqual(_.lookup('b')(noPrototype), O.none) }) it('fromFoldable', () => { const First = Se.first() U.deepStrictEqual(_.fromFoldable(First, RA.Foldable)([['a', 1]]), { a: 1 }) U.deepStrictEqual( _.fromFoldable( First, RA.Foldable )([ ['a', 1], ['a', 2] ]), { a: 1 } ) const Last = Se.last() U.deepStrictEqual( _.fromFoldable( Last, RA.Foldable )([ ['a', 1], ['a', 2] ]), { a: 2 } ) }) it('toReadonlyArray', () => { U.deepStrictEqual(_.toReadonlyArray({ a: 1, b: 2 }), [ ['a', 1], ['b', 2] ]) U.deepStrictEqual(_.toReadonlyArray({ b: 2, a: 1 }), [ ['a', 1], ['b', 2] ]) }) it('toUnfoldable', () => { U.deepStrictEqual(_.toUnfoldable(RA.Unfoldable)({ a: 1 }), [['a', 1]]) }) it('toEntries', () => { U.deepStrictEqual(_.toEntries({ a: 1, b: 2 }), [ ['a', 1], ['b', 2] ]) }) it('fromEntries', () => { U.deepStrictEqual( _.fromEntries([ ['a', 1], ['b', 2], ['a', 3] ]), { b: 2, a: 3 } ) }) it('traverseWithIndex should sort the keys', () => { const log: Array = [] const append = (message: string): IO.IO => () => { log.push(message) } pipe( { b: append('b'), a: append('a') }, _.traverseWithIndex(IO.Applicative)((_, io) => io) )() U.deepStrictEqual(log, ['a', 'b']) }) it('size', () => { U.deepStrictEqual(_.size({}), 0) U.deepStrictEqual(_.size({ a: 1 }), 1) }) it('isEmpty', () => { U.deepStrictEqual(_.isEmpty(_.empty), true) U.deepStrictEqual(_.isEmpty({}), true) U.deepStrictEqual(_.isEmpty({ a: 1 }), false) // should ignore non own properties U.deepStrictEqual(_.isEmpty(Object.create({ a: 1 })), true) }) it('insertAt', () => { U.deepStrictEqual(_.insertAt('a', 1)({}), { a: 1 }) U.deepStrictEqual(_.insertAt('c', 3)({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 }) // should return the same reference if the value is already there const x = { a: 1 } U.deepStrictEqual(_.insertAt('a', 1)(x), x) }) it('deleteAt', () => { U.deepStrictEqual(_.deleteAt('a')({ a: 1, b: 2 }), { b: 2 }) // should return the same reference if the key is missing const x = { a: 1 } U.deepStrictEqual(_.deleteAt('b')(x), x) U.deepStrictEqual(_.deleteAt('b')(noPrototype), noPrototype) }) it('pop', () => { assert.deepStrictEqual(_.pop('a')({ a: 1, b: 2 }), O.some([1, { b: 2 }])) U.deepStrictEqual(_.pop('c')({ a: 1, b: 2 }), O.none) }) it('every', () => { const x: _.ReadonlyRecord = { a: 1, b: 2 } const y: _.ReadonlyRecord = { a: 1, b: 2 } U.deepStrictEqual(_.every((n: number) => n <= 2)(x), true) U.deepStrictEqual(_.every((n: number) => n <= 1)(y), false) }) it('some', () => { const x: _.ReadonlyRecord = { a: 1, b: 2 } const y: _.ReadonlyRecord = { a: 1, b: 2 } U.deepStrictEqual(_.some((n: number) => n <= 1)(x), true) U.deepStrictEqual(_.some((n: number) => n <= 0)(y), false) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(1, { a: 1, b: 2 }), true) U.deepStrictEqual(_.elem(N.Eq)(3, { a: 1, b: 2 }), false) U.deepStrictEqual(_.elem(N.Eq)(1)({ a: 1, b: 2 }), true) U.deepStrictEqual(_.elem(N.Eq)(3)({ a: 1, b: 2 }), false) }) it('fromFoldableMap', () => { const zipObject = (keys: ReadonlyArray, values: ReadonlyArray): _.ReadonlyRecord => _.fromFoldableMap(Se.last(), RA.Foldable)(RA.zip(keys, values), identity) U.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 }) interface User { readonly id: string readonly name: string } const users: ReadonlyArray = [ { id: 'id1', name: 'name1' }, { id: 'id2', name: 'name2' }, { id: 'id1', name: 'name3' } ] U.deepStrictEqual( _.fromFoldableMap(Se.last(), RA.Foldable)(users, (user) => [user.id, user]), { id1: { id: 'id1', name: 'name3' }, id2: { id: 'id2', name: 'name2' } } ) }) it('getShow', () => { const Sh = _.getShow(S.Ord)(S.Show) U.deepStrictEqual(Sh.show({}), `{}`) U.deepStrictEqual(Sh.show({ a: 'a' }), `{ "a": "a" }`) U.deepStrictEqual(Sh.show({ a: 'a', b: 'b' }), `{ "a": "a", "b": "b" }`) const DepSh = _.getShow(S.Show) U.deepStrictEqual(DepSh.show({}), `{}`) U.deepStrictEqual(DepSh.show({ a: 'a' }), `{ "a": "a" }`) U.deepStrictEqual(DepSh.show({ a: 'a', b: 'b' }), `{ "a": "a", "b": "b" }`) }) it('singleton', () => { U.deepStrictEqual(_.singleton('a', 1), { a: 1 }) }) it('has', () => { const x: _.ReadonlyRecord = { a: 1 } U.deepStrictEqual(_.has('a', x), true) U.deepStrictEqual(_.has('b', x), false) // TODO: remove in v3 // #1249 // eslint-disable-next-line no-prototype-builtins U.deepStrictEqual(_.hasOwnProperty('a', x), true) // eslint-disable-next-line no-prototype-builtins U.deepStrictEqual(_.hasOwnProperty('b', x), false) // eslint-disable-next-line deprecation/deprecation const hasOwnProperty: any = _.hasOwnProperty U.deepStrictEqual(hasOwnProperty.call(x, 'a'), true) U.deepStrictEqual(hasOwnProperty.call(x, 'b'), false) }) it('updateAt', () => { const x: _.ReadonlyRecord = { a: 1 } U.deepStrictEqual(_.updateAt('b', 2)(x), O.none) U.deepStrictEqual(_.updateAt('a', 2)(x), O.some({ a: 2 })) const r = _.updateAt('a', 1)(x) if (O.isSome(r)) { U.deepStrictEqual(r.value, x) } else { assert.fail() } }) it('modifyAt', () => { const x: _.ReadonlyRecord = { a: 1 } U.deepStrictEqual(_.modifyAt('b', (n: number) => n * 2)(x), O.none) U.deepStrictEqual(_.modifyAt('a', (n: number) => n * 2)(x), O.some({ a: 2 })) // should return the same reference if nothing changed const input: _.ReadonlyRecord = { a: 1 } U.deepStrictEqual( pipe( input, _.modifyAt('a', identity), O.map((out) => out === input) ), O.some(true) ) }) it('fromRecord', () => { const as = { a: 1, b: 2 } const bs = _.fromRecord(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('toRecord', () => { const as: _.ReadonlyRecord = { a: 1, b: 2 } const bs = _.toRecord(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(S.Semigroup) const x: _.ReadonlyRecord = { a: 'a1', b: 'b1', c: 'c1' } const y: _.ReadonlyRecord = { b: 'b2', c: 'c2', d: 'd2' } U.strictEqual(M.concat(x, M.empty), x) U.strictEqual(M.concat(M.empty, x), x) U.strictEqual(M.concat(x, {}), x) U.strictEqual(M.concat({}, x), x) U.deepStrictEqual(M.concat(x, y), { a: 'a1', b: 'b1b2', c: 'c1c2', d: 'd2' }) }) it('getIntersectionSemigroup', () => { const M = _.getIntersectionSemigroup(S.Semigroup) const x: _.ReadonlyRecord = { a: 'a1', b: 'b1', c: 'c1' } const y: _.ReadonlyRecord = { b: 'b2', c: 'c2', d: 'd2' } U.strictEqual(M.concat(x, _.empty), _.empty) U.strictEqual(M.concat(x, _.empty), _.empty) U.strictEqual(M.concat(x, {}), _.empty) U.strictEqual(M.concat(x, {}), _.empty) U.deepStrictEqual(M.concat(x, y), { b: 'b1b2', c: 'c1c2' }) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma() const x: _.ReadonlyRecord = { a: 'a1', b: 'b1', c: 'c1' } const y: _.ReadonlyRecord = { b: 'b2', c: 'c2', d: 'd2' } U.strictEqual(M.concat(_.empty, x), x) U.strictEqual(M.concat(x, _.empty), x) U.strictEqual(M.concat({}, x), x) U.strictEqual(M.concat(x, {}), x) U.deepStrictEqual(M.concat(x, y), { a: 'a1', d: 'd2' }) }) it('mapWithIndex', () => { // should ignore non own properties const o: _.ReadonlyRecord = Object.create({ a: 1 }) U.deepStrictEqual( pipe( o, _.mapWithIndex((_, a) => U.double(a)) ), {} ) }) }) ================================================ FILE: test/ReadonlySet.ts ================================================ import * as assert from 'assert' import { getMonoid } from '../src/Array' import { left, right } from '../src/Either' import * as Eq from '../src/Eq' import { pipe } from '../src/function' import * as N from '../src/number' import { none, some as optionSome } from '../src/Option' import * as _ from '../src/ReadonlySet' import { separated } from '../src/Separated' import * as S from '../src/string' import * as U from './util' const gte2 = (n: number) => n >= 2 interface Foo { readonly x: string } const foo = (x: string): Foo => ({ x }) const fooEq: Eq.Eq = { equals: (a: Foo, b: Foo) => a.x === b.x } describe('ReadonlySet', () => { it('toReadonlyArray', () => { U.deepStrictEqual(_.toReadonlyArray(N.Ord)(new Set()), []) U.deepStrictEqual(_.toReadonlyArray(N.Ord)(new Set([1, 2, 3])), [1, 2, 3]) U.deepStrictEqual(_.toReadonlyArray(N.Ord)(new Set([3, 2, 1])), [1, 2, 3]) }) it('getEq', () => { const E = _.getEq(N.Eq) U.deepStrictEqual(E.equals(new Set([1, 2, 3]), new Set([1, 2, 3])), true) U.deepStrictEqual(E.equals(new Set([1, 2, 3]), new Set([1, 2])), false) U.deepStrictEqual(E.equals(new Set([1, 2]), new Set([1, 2, 3])), false) }) it('some', () => { U.deepStrictEqual(_.some((s: string) => s.trim() === '')(new Set()), false) U.deepStrictEqual(_.some(gte2)(new Set([1, 2, 3])), true) U.deepStrictEqual(_.some(gte2)(new Set([1])), false) }) it('map', () => { U.deepStrictEqual(_.map(N.Eq)((n: number) => n % 2)(new Set([])), new Set([])) U.deepStrictEqual(_.map(N.Eq)((n: number) => n % 2)(new Set([1, 2, 3, 4])), new Set([0, 1])) U.deepStrictEqual(_.map(S.Eq)((n: number) => `${n % 2}`)(new Set([1, 2, 3, 4])), new Set(['0', '1'])) }) it('every', () => { U.deepStrictEqual(_.every(gte2)(new Set([1, 2, 3])), false) U.deepStrictEqual(_.every(gte2)(new Set([2, 3])), true) }) it('chain', () => { U.deepStrictEqual(_.chain(S.Eq)((n: number) => new Set([n.toString()]))(new Set([])), new Set([])) U.deepStrictEqual(_.chain(S.Eq)(() => new Set([]))(new Set([1, 2])), new Set([])) U.deepStrictEqual( _.chain(S.Eq)((n: number) => new Set([`${n}`, `${n + 1}`]))(new Set([1, 2])), new Set(['1', '2', '3']) ) }) it('isSubset', () => { U.deepStrictEqual(_.isSubset(N.Eq)(new Set([1, 2]), new Set([1, 2, 3])), true) U.deepStrictEqual(_.isSubset(N.Eq)(new Set([1, 2, 4]), new Set([1, 2, 3])), false) U.deepStrictEqual(pipe(new Set([1, 2]), _.isSubset(N.Eq)(new Set([1, 2, 3]))), true) U.deepStrictEqual(pipe(new Set([1, 2, 4]), _.isSubset(N.Eq)(new Set([1, 2, 3]))), false) }) it('filter', () => { U.deepStrictEqual(_.filter(gte2)(new Set([1, 2, 3])), new Set([2, 3])) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const actual = _.filter(isNumber)(new Set([1, 'a', 2])) U.deepStrictEqual(actual, new Set([1, 2])) }) it('partition', () => { U.deepStrictEqual(_.partition(() => true)(new Set([])), separated(new Set([]), new Set([]))) U.deepStrictEqual(_.partition(() => true)(new Set([1])), separated(new Set([]), new Set([1]))) U.deepStrictEqual(_.partition(() => false)(new Set([1])), separated(new Set([1]), new Set([]))) U.deepStrictEqual( _.partition((n: number) => n % 2 === 0)(new Set([1, 2, 3, 4])), separated(new Set([1, 3]), new Set([2, 4])) ) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const actual = _.partition(isNumber)(new Set([1, 'a', 2])) U.deepStrictEqual(actual, separated(new Set(['a']), new Set([1, 2]))) }) it('union', () => { U.deepStrictEqual(_.union(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([1, 2, 3])) U.deepStrictEqual(pipe(new Set([1, 2]), _.union(N.Eq)(new Set([1, 3]))), new Set([1, 2, 3])) }) it('intersection', () => { U.deepStrictEqual(_.intersection(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([1])) U.deepStrictEqual(pipe(new Set([1, 2]), _.intersection(N.Eq)(new Set([1, 3]))), new Set([1])) }) it('partitionMap', () => { U.deepStrictEqual( _.partitionMap(N.Eq, S.Eq)((n: number) => left(n))(new Set([])), separated(new Set([]), new Set([])) ) U.deepStrictEqual( _.partitionMap(N.Eq, S.Eq)((n: number) => (n % 2 === 0 ? left(n) : right(`${n}`)))(new Set([1, 2, 3])), separated(new Set([2]), new Set(['1', '3'])) ) const SL = Eq.struct({ value: N.Eq }) const SR = Eq.struct({ value: S.Eq }) U.deepStrictEqual( _.partitionMap( SL, SR )((x: { readonly value: number }) => (x.value % 2 === 0 ? left({ value: 2 }) : right({ value: 'odd' })))( new Set([{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]) ), separated(new Set([{ value: 2 }]), new Set([{ value: 'odd' }])) ) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(N.Eq) U.deepStrictEqual(M.concat(new Set([1, 2]), new Set([1, 3])), new Set([1, 2, 3])) U.deepStrictEqual(M.concat(new Set([1, 2]), M.empty), new Set([1, 2])) U.deepStrictEqual(M.concat(M.empty, new Set([1, 3])), new Set([1, 3])) }) it('getIntersectionSemigroup', () => { const IS = _.getIntersectionSemigroup(N.Eq) U.deepStrictEqual(IS.concat(new Set([1, 2]), new Set([1, 3])), new Set([1])) U.deepStrictEqual(IS.concat(new Set([1, 2]), _.empty), _.empty) U.deepStrictEqual(IS.concat(_.empty, new Set([1, 3])), _.empty) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma(N.Eq) U.deepStrictEqual(M.concat(new Set([1, 2]), new Set([1, 3])), new Set([2])) }) it('difference', () => { U.deepStrictEqual(_.difference(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([2])) U.deepStrictEqual(pipe(new Set([1, 2]), _.difference(N.Eq)(new Set([1, 3]))), new Set([2])) }) it('reduce', () => { U.deepStrictEqual(_.reduce(N.Ord)('', (b, a) => b + a)(new Set([1, 2, 3])), '123') U.deepStrictEqual(_.reduce(N.Ord)('', (b, a) => b + a)(new Set([3, 2, 1])), '123') }) it('foldMap', () => { U.deepStrictEqual(_.foldMap(N.Ord, getMonoid())((a) => [a])(new Set([1, 2, 3])), [1, 2, 3]) U.deepStrictEqual(_.foldMap(N.Ord, getMonoid())((a) => [a])(new Set([3, 2, 1])), [1, 2, 3]) }) it('reduceRight', () => { const f = _.reduceRight(N.Ord)('', (a, b) => b + a) U.deepStrictEqual(f(new Set([1, 2, 3])), '321') U.deepStrictEqual(f(new Set([3, 2, 1])), '321') }) it('singleton', () => { U.deepStrictEqual(_.singleton(1), new Set([1])) }) it('insert', () => { const x = new Set([1, 2]) U.deepStrictEqual(_.insert(N.Eq)(3)(x), new Set([1, 2, 3])) // should return the same ference if the element is already a member U.deepStrictEqual(_.insert(N.Eq)(2)(x), x) }) it('remove', () => { U.deepStrictEqual(_.remove(N.Eq)(3)(new Set([1, 2])), new Set([1, 2])) U.deepStrictEqual(_.remove(N.Eq)(1)(new Set([1, 2])), new Set([2])) }) it('fromArray', () => { U.deepStrictEqual(_.fromArray(N.Eq)([]), new Set([])) U.deepStrictEqual(_.fromArray(N.Eq)([1]), new Set([1])) U.deepStrictEqual(_.fromArray(N.Eq)([1, 1]), new Set([1])) U.deepStrictEqual(_.fromArray(N.Eq)([1, 2]), new Set([1, 2])) U.deepStrictEqual(_.fromArray(fooEq)(['a', 'a', 'b'].map(foo)), new Set(['a', 'b'].map(foo))) }) it('compact', () => { U.deepStrictEqual(_.compact(N.Eq)(new Set([optionSome(1), none, optionSome(2)])), new Set([1, 2])) type R = { readonly id: string } const E: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.compact(E)(new Set([optionSome({ id: 'a' }), none, optionSome({ id: 'a' })])), new Set([{ id: 'a' }]) ) }) it('separate', () => { U.deepStrictEqual( _.separate(S.Eq, N.Eq)(new Set([right(1), left('a'), right(2)])), separated(new Set(['a']), new Set([1, 2])) ) type L = { readonly error: string } type R = { readonly id: string } const SL: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.error) ) const SR: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.separate( SL, SR )(new Set([right({ id: 'a' }), left({ error: 'error' }), right({ id: 'a' }), left({ error: 'error' })])), separated(new Set([{ error: 'error' }]), new Set([{ id: 'a' }])) ) }) it('filterMap', () => { U.deepStrictEqual( _.filterMap(N.Eq)((s: string) => (s.length > 1 ? optionSome(s.length) : none))(new Set(['a', 'bb', 'ccc'])), new Set([2, 3]) ) type R = { readonly id: string } const E: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.filterMap(E)((x: { readonly id: string }) => optionSome(x))(new Set([{ id: 'a' }, { id: 'a' }])), new Set([{ id: 'a' }]) ) }) it('getShow', () => { const Sh = _.getShow(S.Show) const s1 = new Set([]) U.deepStrictEqual(Sh.show(s1), `new Set([])`) const s2 = new Set(['a']) U.deepStrictEqual(Sh.show(s2), `new Set(["a"])`) const s3 = new Set(['b', 'a']) U.deepStrictEqual(Sh.show(s3), `new Set(["a", "b"])`) }) it('fromSet', () => { const as = new Set(['a']) const bs = _.fromSet(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('toSet', () => { const as: ReadonlySet = new Set(['a']) const bs = _.toSet(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('isEmpty', () => { U.deepStrictEqual(_.isEmpty(_.empty), true) U.deepStrictEqual(_.isEmpty(new Set()), true) U.deepStrictEqual(_.isEmpty(new Set(['a'])), false) }) it('size', () => { U.deepStrictEqual(_.size(_.empty), 0) U.deepStrictEqual(_.size(new Set()), 0) U.deepStrictEqual(_.size(new Set(['a'])), 1) }) it('toggle', () => { U.deepStrictEqual(_.toggle(N.Eq)(1)(new Set([2])), new Set([1, 2])) U.deepStrictEqual(_.toggle(N.Eq)(1)(new Set([1, 2])), new Set([2])) }) }) ================================================ FILE: test/ReadonlyTuple.ts ================================================ import * as assert from 'assert' import { getMonoid } from '../src/Array' import { left, right } from '../src/Either' import { identity, pipe } from '../src/function' import * as O from '../src/Option' import * as _ from '../src/ReadonlyTuple' import * as S from '../src/string' import * as U from './util' describe('ReadonlyTuple', () => { describe('pipeables', () => { it('compose', () => { U.deepStrictEqual(pipe([true, 2] as const, _.compose([1, 'a'])), [true, 'a']) }) it('mapFst', () => { U.deepStrictEqual(pipe([1, 'a'] as const, _.mapFst(U.double)), [2, 'a']) }) it('extract', () => { U.deepStrictEqual(pipe([1, 'a'] as const, _.extract), 1) }) it('extend', () => { const f = (fa: readonly [number, string]): number => _.snd(fa).length + _.fst(fa) U.deepStrictEqual(pipe([1, 'bb'], _.extend(f)), [3, 'bb']) }) it('bimap', () => { U.deepStrictEqual(pipe([1, 'a'], _.bimap(S.size, U.double)), [2, 1]) }) it('mapSnd', () => { U.deepStrictEqual(pipe([1, 'a'] as const, _.mapSnd(S.size)), [1, 1]) }) it('duplicate', () => { U.deepStrictEqual(pipe([1, 'a'] as const, _.duplicate), [[1, 'a'], 'a']) }) it('reduce', () => { U.deepStrictEqual( pipe( ['b', 1] as const, _.reduce('a', (acc, a) => acc + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe(['a', 1] as const, _.foldMap(S.Monoid)(identity)), 'a') }) it('reduceRight', () => { U.deepStrictEqual( pipe( ['b', 1] as const, _.reduceRight('a', (acc, a) => acc + a) ), 'ba' ) }) it('traverse', () => { const traverse = _.traverse(O.Applicative)((n: number) => (n > 1 ? O.some(n) : O.none)) assert.deepStrictEqual(traverse([2, 'a']), O.some([2, 'a'])) U.deepStrictEqual(traverse([1, 'a']), O.none) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) assert.deepStrictEqual(sequence([O.some(1), 'a']), O.some([1, 'a'])) U.deepStrictEqual(sequence([O.none, 'a']), O.none) }) }) it('swap', () => { U.deepStrictEqual(_.swap([1, 'a']), ['a', 1]) }) it('getApply', () => { const apply = _.getApply(S.Monoid) U.deepStrictEqual(apply.ap([U.double, 'a'], [1, 'b']), [2, 'ab']) }) it('getApplicative', () => { const applicative = _.getApplicative(S.Monoid) U.deepStrictEqual(applicative.of(1), [1, '']) }) it('getMonad', () => { const monad = _.getMonad(S.Monoid) U.deepStrictEqual( monad.chain([1, 'a'], (a) => [a * 2, 'b']), [2, 'ab'] ) }) it('chainRec', () => { const { chainRec } = _.getChainRec(getMonoid()) function seqReq(upper: number): readonly [number, ReadonlyArray] { return chainRec(1, (init) => [init >= upper ? right(init) : left(init + 1), [init]]) } const xs = _.snd(seqReq(10000)) U.deepStrictEqual(xs.length, 10000) U.deepStrictEqual(xs[0], 1) U.deepStrictEqual(xs[xs.length - 1], 10000) }) }) ================================================ FILE: test/Record.ts ================================================ import * as assert from 'assert' import * as A from '../src/Array' import { left, right } from '../src/Either' import { identity, pipe } from '../src/function' import * as IO from '../src/IO' import * as N from '../src/number' import * as O from '../src/Option' import { reverse } from '../src/Ord' import * as _ from '../src/Record' import * as Se from '../src/Semigroup' import { separated } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as U from './util' const p = (n: number) => n > 2 const noPrototype = Object.create(null) describe('Record', () => { describe('pipeables', () => { it('collect', () => { const x: { readonly a: string; readonly b: boolean } = { a: 'c', b: false } U.deepStrictEqual(_.collect(S.Ord)((key, val) => ({ key: key, value: val }))(x), [ { key: 'a', value: 'c' }, { key: 'b', value: false } ]) U.deepStrictEqual(_.collect((key, val) => ({ key: key, value: val }))(x), [ { key: 'a', value: 'c' }, { key: 'b', value: false } ]) }) it('map', () => { U.deepStrictEqual(pipe({ k1: 1, k2: 2 }, _.map(U.double)), { k1: 2, k2: 4 }) U.deepStrictEqual(pipe({ a: 1, b: 2 }, _.map(U.double)), { a: 2, b: 4 }) }) it('mapWithIndex', () => { const doubleWithIndex = (_: string, n: number): number => n * 2 U.deepStrictEqual(pipe({ a: 1, b: 2 }, _.mapWithIndex(doubleWithIndex)), { a: 2, b: 4 }) }) it('reduce', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduce(S.Ord)('', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduce(S.Ord)('', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduce('', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduce('', (b, a) => b + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.foldMap(S.Ord)(S.Monoid)(identity)), 'ab') U.deepStrictEqual(_.getFoldable(S.Ord).foldMap(S.Monoid)({ a: 'a', b: 'b' }, identity), 'ab') U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.foldMap(S.Monoid)(identity)), 'ab') U.deepStrictEqual(_.Foldable.foldMap(S.Monoid)({ a: 'a', b: 'b' }, identity), 'ab') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.reduceRight(S.Ord)('', f)), 'ba') U.deepStrictEqual(pipe({ a: 'a', b: 'b' }, _.reduceRight('', f)), 'ba') }) it('compact', () => { U.deepStrictEqual(_.compact({ foo: O.none, bar: O.some(123) }), { bar: 123 }) }) it('separate', () => { U.deepStrictEqual(_.separate({ foo: left(123), bar: right(123) }), separated({ foo: 123 }, { bar: 123 })) }) it('filter', () => { const d = { a: 1, b: 3 } U.deepStrictEqual(pipe(d, _.filter(p)), { b: 3 }) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const y: Record = { a: 1, b: 'foo' } const actual = pipe(y, _.filter(isNumber)) U.deepStrictEqual(actual, { a: 1 }) U.deepStrictEqual( pipe( y, _.filter((_) => true) ), y ) const x = Object.assign(Object.create({ c: true }), { a: 1, b: 'foo' }) U.deepStrictEqual(pipe(x, _.filter(isNumber)), { a: 1 }) U.deepStrictEqual(pipe(noPrototype, _.filter(isNumber)), noPrototype) }) it('filterMap', () => { const f = (n: number) => (p(n) ? O.some(n + 1) : O.none) U.deepStrictEqual(pipe({}, _.filterMap(f)), {}) U.deepStrictEqual(pipe({ a: 1, b: 3 }, _.filterMap(f)), { b: 4 }) }) it('partition', () => { U.deepStrictEqual(pipe({}, _.partition(p)), separated({}, {})) U.deepStrictEqual(pipe({ a: 1, b: 3 }, _.partition(p)), separated({ a: 1 }, { b: 3 })) }) it('partitionMap', () => { const f = (n: number) => (p(n) ? right(n + 1) : left(n - 1)) U.deepStrictEqual(pipe({}, _.partitionMap(f)), separated({}, {})) U.deepStrictEqual(pipe({ a: 1, b: 3 }, _.partitionMap(f)), separated({ a: 0 }, { b: 4 })) }) it('reduceWithIndex', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceWithIndex(S.Ord)('', (k, b, a) => b + k + a) ), 'k1ak2b' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduceWithIndex(S.Ord)('', (k, b, a) => b + k + a) ), 'k1ak2b' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceWithIndex('', (k, b, a) => b + k + a) ), 'k1ak2b' ) U.deepStrictEqual( pipe( { k2: 'b', k1: 'a' }, _.reduceWithIndex('', (k, b, a) => b + k + a) ), 'k1ak2b' ) }) it('foldMapWithIndex', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.foldMapWithIndex(S.Ord)(S.Monoid)((k, a) => k + a) ), 'k1ak2b' ) U.deepStrictEqual( _.getFoldableWithIndex(S.Ord).foldMapWithIndex(S.Monoid)({ k1: 'a', k2: 'b' }, (k, a) => k + a), 'k1ak2b' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.foldMapWithIndex(S.Monoid)((k, a) => k + a) ), 'k1ak2b' ) U.deepStrictEqual( _.FoldableWithIndex.foldMapWithIndex(S.Monoid)({ k1: 'a', k2: 'b' }, (k, a) => k + a), 'k1ak2b' ) }) it('reduceRightWithIndex', () => { U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceRightWithIndex(S.Ord)('', (k, a, b) => b + k + a) ), 'k2bk1a' ) U.deepStrictEqual( pipe( { k1: 'a', k2: 'b' }, _.reduceRightWithIndex('', (k, a, b) => b + k + a) ), 'k2bk1a' ) }) it('partitionMapWithIndex', () => { assert.deepStrictEqual( pipe( { a: 1, b: 2 }, _.partitionMapWithIndex((k, a: number) => (a > 1 ? right(a) : left(k))) ), separated({ a: 'a' }, { b: 2 }) ) }) it('partitionWithIndex', () => { U.deepStrictEqual( pipe( { a: 1, b: 2 }, _.partitionWithIndex((_, a: number) => a > 1) ), separated({ a: 1 }, { b: 2 }) ) }) it('filterMapWithIndex', () => { U.deepStrictEqual( pipe( { a: 1, b: 2 }, _.filterMapWithIndex((_, a: number) => (a > 1 ? O.some(a) : O.none)) ), { b: 2 } ) }) it('filterWithIndex', () => { U.deepStrictEqual( pipe( { a: 1, b: 2 }, _.filterWithIndex((_, a: number) => a > 1) ), { b: 2 } ) }) it('traverse', () => { U.deepStrictEqual( _.traverse(O.Applicative)((n: number) => (n <= 2 ? O.some(n) : O.none))({ a: 1, b: 2 }), O.some({ a: 1, b: 2 }) ) U.deepStrictEqual(_.traverse(O.Applicative)((n: number) => (n >= 2 ? O.some(n) : O.none))({ a: 1, b: 2 }), O.none) }) it('getTraversable', () => { const T = _.getTraversable(reverse(S.Ord)) const f = (n: number) => (n <= 2 ? O.some(n) : O.none) U.deepStrictEqual(T.traverse(O.Applicative)({ a: 1, b: 2 }, f), O.some({ a: 1, b: 2 })) U.deepStrictEqual(T.traverse(O.Applicative)({ a: 1, b: 3 }, f), O.none) // should respect the order U.deepStrictEqual(pipe(T.traverse(O.Applicative)({ b: 2, a: 1 }, f), O.map(Object.keys)), O.some(['b', 'a'])) U.deepStrictEqual( pipe(T.sequence(O.Applicative)({ b: O.some(2), a: O.some(1) }), O.map(Object.keys)), O.some(['b', 'a']) ) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence({ a: O.some(1), b: O.some(2) }), O.some({ a: 1, b: 2 })) U.deepStrictEqual(sequence({ a: O.none, b: O.some(2) }), O.none) U.deepStrictEqual(_.record.sequence(O.Applicative)({ a: O.some(1), b: O.some(2) }), O.some({ a: 1, b: 2 })) }) it('traverseWithIndex', () => { const f = (k: string, n: number): O.Option => (k !== 'a' ? O.some(n) : O.none) const traverseWithIndex = _.traverseWithIndex(O.Applicative)(f) U.deepStrictEqual(pipe({ a: 1, b: 2 }, traverseWithIndex), O.none) U.deepStrictEqual(pipe({ b: 2 }, traverseWithIndex), O.some({ b: 2 })) U.deepStrictEqual(pipe({}, traverseWithIndex), O.some({})) }) it('getTraversableWithIndex', () => { const TWI = _.getTraversableWithIndex(reverse(S.Ord)) const f = (k: string, n: number): O.Option => (k !== 'a' ? O.some(n) : O.none) U.deepStrictEqual(TWI.traverseWithIndex(O.Applicative)({ b: 2 }, f), O.some({ b: 2 })) U.deepStrictEqual(TWI.traverseWithIndex(O.Applicative)({ a: 1, b: 2 }, f), O.none) U.deepStrictEqual(TWI.traverseWithIndex(O.Applicative)({}, f), O.some({})) // should respect the order U.deepStrictEqual( pipe(TWI.traverseWithIndex(O.Applicative)({ b: 2, c: 1 }, f), O.map(Object.keys)), O.some(['c', 'b']) ) }) it('wither', async () => { const f = (n: number) => T.of(p(n) ? O.some(n + 1) : O.none) const wither = _.wither(T.ApplicativePar)(f) U.deepStrictEqual(await pipe({}, wither)(), {}) U.deepStrictEqual(await pipe({ a: 1, b: 3 }, wither)(), { b: 4 }) U.deepStrictEqual(await _.getWitherable(S.Ord).wither(T.ApplicativePar)({ a: 1, b: 3 }, f)(), { b: 4 }) }) it('wilt', async () => { const wilt = _.wilt(T.ApplicativePar)((n: number) => T.of(p(n) ? right(n + 1) : left(n - 1))) U.deepStrictEqual(await pipe({}, wilt)(), separated({}, {})) U.deepStrictEqual(await pipe({ a: 1, b: 3 }, wilt)(), separated({ a: 0 }, { b: 4 })) }) }) it('getMonoid', () => { const d1 = { k1: 1, k2: 3 } const d2 = { k2: 2, k3: 4 } const M = _.getMonoid(N.SemigroupSum) U.deepStrictEqual(M.concat(d1, d2), { k1: 1, k2: 5, k3: 4 }) U.deepStrictEqual(M.concat(d1, M.empty), d1) U.deepStrictEqual(M.concat(M.empty, d2), d2) U.deepStrictEqual(M.concat(d1, {}), d1) }) it('getEq', () => { U.deepStrictEqual(_.getEq(N.Eq).equals({ a: 1 }, { a: 1 }), true) U.deepStrictEqual(_.getEq(N.Eq).equals({ a: 1 }, { a: 2 }), false) U.deepStrictEqual(_.getEq(N.Eq).equals({ a: 1 }, { b: 1 }), false) U.deepStrictEqual(_.getEq(N.Eq).equals(noPrototype, { b: 1 }), false) }) it('lookup', () => { U.deepStrictEqual(_.lookup('a', { a: 1 }), O.some(1)) U.deepStrictEqual(_.lookup('b', { a: 1 }), O.none) U.deepStrictEqual(_.lookup('b', noPrototype), O.none) U.deepStrictEqual(_.lookup('a')({ a: 1 }), O.some(1)) U.deepStrictEqual(_.lookup('b')({ a: 1 }), O.none) U.deepStrictEqual(_.lookup('b')(noPrototype), O.none) }) it('fromFoldable', () => { const First = Se.first() U.deepStrictEqual(_.fromFoldable(First, A.Foldable)([['a', 1]]), { a: 1 }) U.deepStrictEqual( _.fromFoldable( First, A.Foldable )([ ['a', 1], ['a', 2] ]), { a: 1 } ) const Last = Se.last() U.deepStrictEqual( _.fromFoldable( Last, A.Foldable )([ ['a', 1], ['a', 2] ]), { a: 2 } ) }) it('toUnfoldable', () => { U.deepStrictEqual(_.toUnfoldable(A.Unfoldable)({ a: 1 }), [['a', 1]]) }) it('toEntries', () => { U.deepStrictEqual(_.toEntries({ a: 1, b: 2 }), [ ['a', 1], ['b', 2] ]) }) it('fromEntries', () => { U.deepStrictEqual( _.fromEntries([ ['a', 1], ['b', 2], ['a', 3] ]), { b: 2, a: 3 } ) }) it('traverseWithIndex should sort the keys', () => { const log: Array = [] const append = (message: string): IO.IO => () => { log.push(message) } pipe( { b: append('b'), a: append('a') }, _.traverseWithIndex(IO.Applicative)((_, io) => io) )() U.deepStrictEqual(log, ['a', 'b']) }) it('size', () => { U.deepStrictEqual(_.size({}), 0) U.deepStrictEqual(_.size({ a: 1 }), 1) }) it('isEmpty', () => { U.deepStrictEqual(_.isEmpty({}), true) U.deepStrictEqual(_.isEmpty({ a: 1 }), false) }) it('insertAt', () => { U.deepStrictEqual(_.insertAt('a', 1)({}), { a: 1 }) U.deepStrictEqual(_.insertAt('c', 3)({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 }) // should return the same reference if the value is already there const x = { a: 1 } U.deepStrictEqual(_.insertAt('a', 1)(x), x) }) it('deleteAt', () => { U.deepStrictEqual(_.deleteAt('a')({ a: 1, b: 2 }), { b: 2 }) // should return the same reference if the key is missing const x = { a: 1 } U.deepStrictEqual(_.deleteAt('b')(x), x) U.deepStrictEqual(_.deleteAt('b')(noPrototype), noPrototype) }) it('pop', () => { U.deepStrictEqual(_.pop('a')({ a: 1, b: 2 }), O.some([1, { b: 2 }])) U.deepStrictEqual(_.pop('c')({ a: 1, b: 2 }), O.none) }) it('every', () => { const x: Record = { a: 1, b: 2 } const y: Record = { a: 1, b: 2 } U.deepStrictEqual(_.every((n: number) => n <= 2)(x), true) U.deepStrictEqual(_.every((n: number) => n <= 1)(y), false) }) it('some', () => { const x: Record = { a: 1, b: 2 } const y: Record = { a: 1, b: 2 } U.deepStrictEqual(_.some((n: number) => n <= 1)(x), true) U.deepStrictEqual(_.some((n: number) => n <= 0)(y), false) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(1, { a: 1, b: 2 }), true) U.deepStrictEqual(_.elem(N.Eq)(3, { a: 1, b: 2 }), false) U.deepStrictEqual(_.elem(N.Eq)(1)({ a: 1, b: 2 }), true) U.deepStrictEqual(_.elem(N.Eq)(3)({ a: 1, b: 2 }), false) }) it('fromFoldableMap', () => { const zipObject = (keys: Array, values: Array): Record => _.fromFoldableMap(Se.last(), A.Foldable)(A.zip(keys, values), identity) U.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 }) interface User { readonly id: string readonly name: string } const users: Array = [ { id: 'id1', name: 'name1' }, { id: 'id2', name: 'name2' }, { id: 'id1', name: 'name3' } ] U.deepStrictEqual( _.fromFoldableMap(Se.last(), A.Foldable)(users, (user) => [user.id, user]), { id1: { id: 'id1', name: 'name3' }, id2: { id: 'id2', name: 'name2' } } ) }) it('getShow', () => { const Sh = _.getShow(S.Ord)(S.Show) U.deepStrictEqual(Sh.show({}), `{}`) U.deepStrictEqual(Sh.show({ a: 'a' }), `{ "a": "a" }`) U.deepStrictEqual(Sh.show({ a: 'a', b: 'b' }), `{ "a": "a", "b": "b" }`) const DepSh = _.getShow(S.Show) U.deepStrictEqual(DepSh.show({}), `{}`) U.deepStrictEqual(DepSh.show({ a: 'a' }), `{ "a": "a" }`) U.deepStrictEqual(DepSh.show({ a: 'a', b: 'b' }), `{ "a": "a", "b": "b" }`) }) it('singleton', () => { U.deepStrictEqual(_.singleton('a', 1), { a: 1 }) }) it('has', () => { const x: Record = { a: 1 } U.deepStrictEqual(_.has('a', x), true) U.deepStrictEqual(_.has('b', x), false) }) it('updateAt', () => { const x: Record = { a: 1 } U.deepStrictEqual(_.updateAt('b', 2)(x), O.none) U.deepStrictEqual(_.updateAt('a', 2)(x), O.some({ a: 2 })) const r = _.updateAt('a', 1)(x) if (O.isSome(r)) { U.deepStrictEqual(r.value, x) } else { assert.fail() } }) it('modifyAt', () => { const x: Record = { a: 1 } U.deepStrictEqual(_.modifyAt('b', (n: number) => n * 2)(x), O.none) U.deepStrictEqual(_.modifyAt('a', (n: number) => n * 2)(x), O.some({ a: 2 })) // should not return the same reference if nothing changed const input: Record = { a: 1 } U.deepStrictEqual( pipe( input, _.modifyAt('a', identity), O.map((out) => out === input) ), O.some(false) ) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(S.Semigroup) const x: Record = { a: 'a1', b: 'b1', c: 'c1' } const y: Record = { b: 'b2', c: 'c2', d: 'd2' } U.deepStrictEqual(M.concat(x, M.empty), x) U.deepStrictEqual(M.concat(M.empty, x), x) U.deepStrictEqual(M.concat(x, {}), x) U.deepStrictEqual(M.concat({}, x), x) U.deepStrictEqual(M.concat(x, y), { a: 'a1', b: 'b1b2', c: 'c1c2', d: 'd2' }) }) it('getIntersectionSemigroup', () => { const M = _.getIntersectionSemigroup(S.Semigroup) const x: Record = { a: 'a1', b: 'b1', c: 'c1' } const y: Record = { b: 'b2', c: 'c2', d: 'd2' } U.deepStrictEqual(M.concat(x, {}), {}) U.deepStrictEqual(M.concat(x, {}), {}) U.deepStrictEqual(M.concat(x, {}), {}) U.deepStrictEqual(M.concat(x, {}), {}) U.deepStrictEqual(M.concat(x, y), { b: 'b1b2', c: 'c1c2' }) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma() const x: Record = { a: 'a1', b: 'b1', c: 'c1' } const y: Record = { b: 'b2', c: 'c2', d: 'd2' } U.deepStrictEqual(M.concat({}, x), x) U.deepStrictEqual(M.concat(x, {}), x) U.deepStrictEqual(M.concat({}, x), x) U.deepStrictEqual(M.concat(x, {}), x) U.deepStrictEqual(M.concat(x, y), { a: 'a1', d: 'd2' }) }) }) ================================================ FILE: test/Refinement.ts ================================================ import * as B from '../src/boolean' import * as E from '../src/Either' import { pipe } from '../src/function' import * as N from '../src/number' import * as O from '../src/Option' import { ReadonlyRecord } from '../src/ReadonlyRecord' import * as _ from '../src/Refinement' import * as S from '../src/string' import * as U from './util' interface NonEmptyStringBrand { readonly NonEmptyString: unique symbol } type NonEmptyString = string & NonEmptyStringBrand const NonEmptyString: _.Refinement = (s): s is NonEmptyString => s.length > 0 describe('Refinement', () => { it('not', () => { const r1: _.Refinement = S.isString const r2 = _.not(r1) U.deepStrictEqual(r2('a'), false) U.deepStrictEqual(r2(1), true) }) it('or', () => { const r = pipe(S.isString, _.or(N.isNumber), _.or(B.isBoolean)) U.deepStrictEqual(r({}), false) U.deepStrictEqual(r('a'), true) U.deepStrictEqual(r(1), true) U.deepStrictEqual(r(true), true) }) it('and', () => { const ra = (r: ReadonlyRecord): r is { readonly a: string } => S.isString(r['a']) const rb = (r: ReadonlyRecord): r is { readonly b: number } => N.isNumber(r['b']) const r = pipe(ra, _.and(rb)) U.deepStrictEqual(r({ a: 'a' }), false) U.deepStrictEqual(r({ b: 1 }), false) U.deepStrictEqual(r({}), false) U.deepStrictEqual(r({ a: 'a', b: 'b' }), false) U.deepStrictEqual(r({ a: 1, b: 2 }), false) U.deepStrictEqual(r({ a: 'a', b: 1 }), true) }) it('fromOptionK', () => { const f = (s: string | number): O.Option => (typeof s === 'string' ? O.some(s) : O.none) const isString = _.fromOptionK(f) U.deepStrictEqual(isString('s'), true) U.deepStrictEqual(isString(1), false) type A = { readonly type: 'A' } type B = { readonly type: 'B' } type C = A | B const isA = _.fromOptionK((c) => (c.type === 'A' ? O.some(c) : O.none)) U.deepStrictEqual(isA({ type: 'A' }), true) U.deepStrictEqual(isA({ type: 'B' }), false) }) it('zero', () => { const refinement = _.zero() U.strictEqual(refinement('a'), false) }) it('id', () => { const refinement = _.id() U.strictEqual(refinement('a'), true) }) it('compose', () => { const refinement = pipe(S.isString, _.compose(NonEmptyString)) U.strictEqual(refinement('a'), true) U.strictEqual(refinement(null), false) U.strictEqual(refinement(''), false) }) it('fromEitherK', () => { const f = (s: string | number): E.Either => typeof s === 'string' ? E.right(s) : E.left('not a string') const isString = _.fromEitherK(f) U.deepStrictEqual(isString('s'), true) U.deepStrictEqual(isString(1), false) type A = { readonly type: 'A' } type B = { readonly type: 'B' } type C = A | B const isA = _.fromEitherK((c) => (c.type === 'A' ? E.right(c) : E.left('not as A'))) U.deepStrictEqual(isA({ type: 'A' }), true) U.deepStrictEqual(isA({ type: 'B' }), false) }) }) ================================================ FILE: test/Ring.ts ================================================ import * as N from '../src/number' import * as _ from '../src/Ring' import * as U from './util' describe('Ring', () => { it('tuple', () => { const R = _.tuple(N.Field, N.Field, N.Field) U.deepStrictEqual(R.add([1, 2, 3], [4, 5, 6]), [5, 7, 9]) U.deepStrictEqual(R.mul([1, 2, 3], [4, 5, 6]), [4, 10, 18]) U.deepStrictEqual(R.one, [1, 1, 1]) U.deepStrictEqual(R.sub([1, 2, 3], [4, 5, 6]), [-3, -3, -3]) U.deepStrictEqual(R.zero, [0, 0, 0]) }) it('negate', () => { U.deepStrictEqual(_.negate(N.Field)(1), -1) }) }) ================================================ FILE: test/Semigroup.ts ================================================ import * as B from '../src/boolean' import * as N from '../src/number' import * as _ from '../src/Semigroup' import * as S from '../src/string' import * as U from './util' describe('Semigroup', () => { it('tuple', () => { const S1 = _.tuple(S.Semigroup, N.SemigroupSum) U.deepStrictEqual(S1.concat(['a', 1], ['b', 2]), ['ab', 3]) const S2 = _.tuple(S.Semigroup, N.SemigroupSum, B.SemigroupAll) U.deepStrictEqual(S2.concat(['a', 1, true], ['b', 2, false]), ['ab', 3, false]) }) it('concatAll', () => { U.deepStrictEqual(_.concatAll(S.Monoid)('')(['a', 'b', 'c']), 'abc') }) it('fold', () => { U.deepStrictEqual(_.fold(S.Monoid)('', ['a', 'b', 'c']), 'abc') U.deepStrictEqual(_.fold(S.Monoid)('')(['a', 'b', 'c']), 'abc') }) it('min', () => { U.deepStrictEqual(_.min(N.Ord).concat(1, 2), 1) }) it('max', () => { U.deepStrictEqual(_.max(N.Ord).concat(1, 2), 2) }) it('first', () => { U.deepStrictEqual(_.first().concat(1, 2), 1) }) it('semigroupVoid', () => { U.deepStrictEqual(_.semigroupVoid.concat(undefined, undefined), undefined) }) it('reverse', () => { const DS = _.reverse(S.Semigroup) U.deepStrictEqual(DS.concat('a', 'b'), 'ba') }) it('intercalate', () => { const IS = _.intercalate(' ')(S.Semigroup) U.strictEqual(IS.concat('a', 'b'), 'a b') U.strictEqual(IS.concat(IS.concat('a', 'b'), 'c'), IS.concat('a', IS.concat('b', 'c'))) }) it('struct', () => { // should ignore non own properties const S = _.struct(Object.create({ a: 1 })) U.deepStrictEqual(S.concat({}, {}), {}) }) it('semigroupAll', () => { const S = _.semigroupAll U.deepStrictEqual(S.concat(true, true), true) U.deepStrictEqual(S.concat(false, true), false) U.deepStrictEqual(S.concat(true, false), false) U.deepStrictEqual(S.concat(false, false), false) }) it('semigroupAny', () => { const S = _.semigroupAny U.deepStrictEqual(S.concat(true, true), true) U.deepStrictEqual(S.concat(false, true), true) U.deepStrictEqual(S.concat(true, false), true) U.deepStrictEqual(S.concat(false, false), false) }) it('semigroupSum', () => { U.deepStrictEqual(_.semigroupSum.concat(2, 3), 5) }) it('semigroupProduct', () => { U.deepStrictEqual(_.semigroupProduct.concat(2, 3), 6) }) it('getObjectSemigroup', () => { type T = { readonly foo?: number readonly bar: string } const foo: T = { foo: 123, bar: '456' } const bar: T = { bar: '123' } const S = _.getObjectSemigroup() U.deepStrictEqual(S.concat(foo, bar), Object.assign({}, foo, bar)) }) }) ================================================ FILE: test/Separated.ts ================================================ import * as fc from 'fast-check' import { isDeepStrictEqual } from 'util' import { pipe } from '../src/function' import * as _ from '../src/Separated' describe('Separated', () => { describe('pipeables', () => { it('mapLeft', () => fc.assert( fc.property(fc.integer(), fc.integer(), (left, right) => { isDeepStrictEqual( pipe( _.separated(left, right), _.mapLeft((n) => n.toString()) ), _.separated(`${left}`, right) ) isDeepStrictEqual( _.Bifunctor.mapLeft(_.separated(left, right), (n) => n.toString()), _.separated(`${left}`, right) ) }) )) it('map', () => fc.assert( fc.property(fc.integer(), fc.integer(), (left, right) => { isDeepStrictEqual( pipe( _.separated(left, right), _.map((n) => n.toString()) ), _.separated(left, `${right}`) ) isDeepStrictEqual( _.Functor.map(_.separated(left, right), (n) => n.toString()), _.separated(left, `${right}`) ) }) )) it('bimap', () => fc.assert( fc.property(fc.integer(), fc.integer(), (left, right) => { isDeepStrictEqual( pipe( _.separated(left, right), _.bimap( (n) => n.toString(), (n) => n.toString() ) ), _.separated(`${left}`, `${right}`) ) isDeepStrictEqual( _.Bifunctor.bimap( _.separated(left, right), (n) => n.toString(), (n) => n.toString() ), _.separated(`${left}`, `${right}`) ) }) )) }) }) ================================================ FILE: test/Set.ts ================================================ import { getMonoid } from '../src/Array' import { left, right } from '../src/Either' import * as Eq from '../src/Eq' import { pipe } from '../src/function' import * as N from '../src/number' import { none, some as optionSome } from '../src/Option' import { separated } from '../src/Separated' import * as _ from '../src/Set' import * as S from '../src/string' import * as U from './util' const gte2 = (n: number) => n >= 2 interface Foo { readonly x: string } const foo = (x: string): Foo => ({ x }) const fooEq: Eq.Eq = { equals: (a: Foo, b: Foo) => a.x === b.x } describe('Set', () => { it('toArray', () => { U.deepStrictEqual(_.toArray(N.Ord)(new Set()), []) U.deepStrictEqual(_.toArray(N.Ord)(new Set([1, 2, 3])), [1, 2, 3]) U.deepStrictEqual(_.toArray(N.Ord)(new Set([3, 2, 1])), [1, 2, 3]) }) it('getEq', () => { const E = _.getEq(N.Eq) U.deepStrictEqual(E.equals(new Set([1, 2, 3]), new Set([1, 2, 3])), true) U.deepStrictEqual(E.equals(new Set([1, 2, 3]), new Set([1, 2])), false) U.deepStrictEqual(E.equals(new Set([1, 2]), new Set([1, 2, 3])), false) }) it('some', () => { U.deepStrictEqual(_.some((s: string) => s.trim() === '')(new Set()), false) U.deepStrictEqual(_.some(gte2)(new Set([1, 2, 3])), true) U.deepStrictEqual(_.some(gte2)(new Set([1])), false) }) it('map', () => { U.deepStrictEqual(_.map(N.Eq)((n: number) => n % 2)(new Set([])), new Set([])) U.deepStrictEqual(_.map(N.Eq)((n: number) => n % 2)(new Set([1, 2, 3, 4])), new Set([0, 1])) U.deepStrictEqual(_.map(S.Eq)((n: number) => `${n % 2}`)(new Set([1, 2, 3, 4])), new Set(['0', '1'])) }) it('every', () => { U.deepStrictEqual(_.every(gte2)(new Set([1, 2, 3])), false) U.deepStrictEqual(_.every(gte2)(new Set([2, 3])), true) }) it('chain', () => { U.deepStrictEqual(_.chain(S.Eq)((n: number) => new Set([n.toString()]))(new Set([])), new Set([])) U.deepStrictEqual(_.chain(S.Eq)(() => new Set([]))(new Set([1, 2])), new Set([])) U.deepStrictEqual( _.chain(S.Eq)((n: number) => new Set([`${n}`, `${n + 1}`]))(new Set([1, 2])), new Set(['1', '2', '3']) ) }) it('isSubset', () => { U.deepStrictEqual(pipe(new Set([1, 2]), _.isSubset(N.Eq)(new Set([1, 2, 3]))), true) U.deepStrictEqual(pipe(new Set([1, 2, 4]), _.isSubset(N.Eq)(new Set([1, 2, 3]))), false) }) it('filter', () => { U.deepStrictEqual(_.filter(gte2)(new Set([1, 2, 3])), new Set([2, 3])) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const actual = _.filter(isNumber)(new Set([1, 'a', 2])) U.deepStrictEqual(actual, new Set([1, 2])) }) it('partition', () => { U.deepStrictEqual(_.partition(() => true)(new Set([])), separated(new Set([]), new Set([]))) U.deepStrictEqual(_.partition(() => true)(new Set([1])), separated(new Set([]), new Set([1]))) U.deepStrictEqual(_.partition(() => false)(new Set([1])), separated(new Set([1]), new Set([]))) U.deepStrictEqual( _.partition((n: number) => n % 2 === 0)(new Set([1, 2, 3, 4])), separated(new Set([1, 3]), new Set([2, 4])) ) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const actual = _.partition(isNumber)(new Set([1, 'a', 2])) U.deepStrictEqual(actual, separated(new Set(['a']), new Set([1, 2]))) }) it('union', () => { U.deepStrictEqual(_.union(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([1, 2, 3])) U.deepStrictEqual(pipe(new Set([1, 2]), _.union(N.Eq)(new Set([1, 3]))), new Set([1, 2, 3])) }) it('intersection', () => { U.deepStrictEqual(_.intersection(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([1])) U.deepStrictEqual(pipe(new Set([1, 2]), _.intersection(N.Eq)(new Set([1, 3]))), new Set([1])) }) it('partitionMap', () => { U.deepStrictEqual( _.partitionMap(N.Eq, S.Eq)((n: number) => left(n))(new Set([])), separated(new Set([]), new Set([])) ) U.deepStrictEqual( _.partitionMap(N.Eq, S.Eq)((n: number) => (n % 2 === 0 ? left(n) : right(`${n}`)))(new Set([1, 2, 3])), separated(new Set([2]), new Set(['1', '3'])) ) const SL = Eq.struct({ value: N.Eq }) const SR = Eq.struct({ value: S.Eq }) U.deepStrictEqual( _.partitionMap( SL, SR )((x: { readonly value: number }) => (x.value % 2 === 0 ? left({ value: 2 }) : right({ value: 'odd' })))( new Set([{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]) ), separated(new Set([{ value: 2 }]), new Set([{ value: 'odd' }])) ) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(N.Eq) U.deepStrictEqual(M.concat(new Set([1, 2]), new Set([1, 3])), new Set([1, 2, 3])) U.deepStrictEqual(M.concat(new Set([1, 2]), M.empty), new Set([1, 2])) U.deepStrictEqual(M.concat(M.empty, new Set([1, 3])), new Set([1, 3])) }) it('getIntersectionSemigroup', () => { const IS = _.getIntersectionSemigroup(N.Eq) U.deepStrictEqual(IS.concat(new Set([1, 2]), new Set([1, 3])), new Set([1])) U.deepStrictEqual(IS.concat(new Set([1, 2]), _.empty), _.empty) U.deepStrictEqual(IS.concat(_.empty, new Set([1, 3])), _.empty) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma(N.Eq) U.deepStrictEqual(M.concat(new Set([1, 2]), new Set([1, 3])), new Set([2])) }) it('difference', () => { U.deepStrictEqual(_.difference(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([2])) U.deepStrictEqual(pipe(new Set([1, 2]), _.difference(N.Eq)(new Set([1, 3]))), new Set([2])) }) it('reduce', () => { U.deepStrictEqual(_.reduce(N.Ord)('', (b, a) => b + a)(new Set([1, 2, 3])), '123') U.deepStrictEqual(_.reduce(N.Ord)('', (b, a) => b + a)(new Set([3, 2, 1])), '123') }) it('foldMap', () => { U.deepStrictEqual(_.foldMap(N.Ord, getMonoid())((a) => [a])(new Set([1, 2, 3])), [1, 2, 3]) U.deepStrictEqual(_.foldMap(N.Ord, getMonoid())((a) => [a])(new Set([3, 2, 1])), [1, 2, 3]) }) it('singleton', () => { U.deepStrictEqual(_.singleton(1), new Set([1])) }) it('insert', () => { const x = new Set([1, 2]) U.deepStrictEqual(_.insert(N.Eq)(3)(x), new Set([1, 2, 3])) // should return the same ference if the element is already a member U.deepStrictEqual(_.insert(N.Eq)(2)(x), x) }) it('remove', () => { U.deepStrictEqual(_.remove(N.Eq)(3)(new Set([1, 2])), new Set([1, 2])) U.deepStrictEqual(_.remove(N.Eq)(1)(new Set([1, 2])), new Set([2])) }) it('toggle', () => { U.deepStrictEqual(_.toggle(N.Eq)(1)(new Set([2])), new Set([1, 2])) U.deepStrictEqual(_.toggle(N.Eq)(1)(new Set([1, 2])), new Set([2])) }) it('fromArray', () => { U.deepStrictEqual(_.fromArray(N.Eq)([]), new Set([])) U.deepStrictEqual(_.fromArray(N.Eq)([1]), new Set([1])) U.deepStrictEqual(_.fromArray(N.Eq)([1, 1]), new Set([1])) U.deepStrictEqual(_.fromArray(N.Eq)([1, 2]), new Set([1, 2])) U.deepStrictEqual(_.fromArray(fooEq)(['a', 'a', 'b'].map(foo)), new Set(['a', 'b'].map(foo))) }) it('compact', () => { U.deepStrictEqual(_.compact(N.Eq)(new Set([optionSome(1), none, optionSome(2)])), new Set([1, 2])) type R = { readonly id: string } const E: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.compact(E)(new Set([optionSome({ id: 'a' }), none, optionSome({ id: 'a' })])), new Set([{ id: 'a' }]) ) }) it('separate', () => { U.deepStrictEqual( _.separate(S.Eq, N.Eq)(new Set([right(1), left('a'), right(2)])), separated(new Set(['a']), new Set([1, 2])) ) type L = { readonly error: string } type R = { readonly id: string } const SL: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.error) ) const SR: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.separate( SL, SR )(new Set([right({ id: 'a' }), left({ error: 'error' }), right({ id: 'a' }), left({ error: 'error' })])), separated(new Set([{ error: 'error' }]), new Set([{ id: 'a' }])) ) }) it('filterMap', () => { U.deepStrictEqual( _.filterMap(N.Eq)((s: string) => (s.length > 1 ? optionSome(s.length) : none))(new Set(['a', 'bb', 'ccc'])), new Set([2, 3]) ) type R = { readonly id: string } const E: Eq.Eq = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.filterMap(E)((x: { readonly id: string }) => optionSome(x))(new Set([{ id: 'a' }, { id: 'a' }])), new Set([{ id: 'a' }]) ) }) it('getShow', () => { const Sh = _.getShow(S.Show) const s1 = new Set([]) U.deepStrictEqual(Sh.show(s1), `new Set([])`) const s2 = new Set(['a']) U.deepStrictEqual(Sh.show(s2), `new Set(["a"])`) const s3 = new Set(['b', 'a']) U.deepStrictEqual(Sh.show(s3), `new Set(["a", "b"])`) }) it('isEmpty', () => { U.deepStrictEqual(_.isEmpty(_.empty), true) U.deepStrictEqual(_.isEmpty(new Set()), true) U.deepStrictEqual(_.isEmpty(new Set(['a'])), false) }) it('size', () => { U.deepStrictEqual(_.size(_.empty), 0) U.deepStrictEqual(_.size(new Set()), 0) U.deepStrictEqual(_.size(new Set(['a'])), 1) }) }) ================================================ FILE: test/Show.ts ================================================ import * as N from '../src/number' import * as _ from '../src/Show' import * as S from '../src/string' import * as U from './util' describe('Show', () => { it('struct', () => { U.deepStrictEqual(_.struct({ a: S.Show }).show({ a: 'a' }), '{ a: "a" }') U.deepStrictEqual(_.struct({ a: S.Show, b: N.Show }).show({ a: 'a', b: 1 }), '{ a: "a", b: 1 }') // should ignore non own properties const shows = Object.create({ a: 1 }) const s = _.struct(shows) U.deepStrictEqual(s.show({}), '{}') }) it('tuple', () => { const Sh = _.tuple(S.Show, N.Show) U.deepStrictEqual(Sh.show(['a', 1]), '["a", 1]') }) it('showBoolean', () => { const Sh = _.showBoolean U.deepStrictEqual(Sh.show(true), 'true') U.deepStrictEqual(Sh.show(false), 'false') }) it('showNumber', () => { U.deepStrictEqual(_.showNumber.show(1), '1') }) it('showString', () => { U.deepStrictEqual(_.showString.show('a'), '"a"') }) }) ================================================ FILE: test/State.ts ================================================ import { pipe, tuple } from '../src/function' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import * as _ from '../src/State' import * as U from './util' describe('State', () => { describe('pipeables', () => { it('map', () => { const x = (s: number) => tuple(s - 1, s + 1) U.deepStrictEqual(pipe(x, _.map(U.double))(0), [-2, 1]) }) it('ap', () => { U.deepStrictEqual(pipe(_.of(U.double), _.ap(_.of(1)))(0), [2, 0]) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.of('a'), _.apFirst(_.of('b')))(0), ['a', 0]) }) it('apSecond', () => { U.deepStrictEqual(pipe(_.of('a'), _.apSecond(_.of('b')))(0), ['b', 0]) }) it('flatMap', () => { const f = (_n: number) => (s: number) => tuple(s - 1, s + 1) const x = (s: number) => tuple(s - 1, s + 1) U.deepStrictEqual(pipe(x, _.flatMap(f))(0), [0, 2]) U.deepStrictEqual(_.flatMap(x, f)(0), [0, 2]) }) it('chain', () => { const f = (_n: number) => (s: number) => tuple(s - 1, s + 1) const x = (s: number) => tuple(s - 1, s + 1) U.deepStrictEqual(pipe(x, _.chain(f))(0), [0, 2]) }) it('tap', () => { const f = (_n: number) => (s: number) => tuple(s - 1, s + 1) const x = (s: number) => tuple(s - 1, s + 1) U.deepStrictEqual(pipe(x, _.tap(f))(0), [-1, 2]) U.deepStrictEqual(_.tap(x, f)(0), [-1, 2]) }) it('chainFirst', () => { const f = (_n: number) => (s: number) => tuple(s - 1, s + 1) const x = (s: number) => tuple(s - 1, s + 1) U.deepStrictEqual(pipe(x, _.chainFirst(f))(0), [-1, 2]) }) it('flatten', () => { U.deepStrictEqual(pipe(_.of(_.of('a')), _.flatten)(0), ['a', 0]) }) }) it('evalState', () => { U.deepStrictEqual(_.evalState(_.of('a'), 0), 'a') }) it('execState', () => { U.deepStrictEqual(_.execState(_.of('a'), 0), 0) }) it('evaluate', () => { U.deepStrictEqual(pipe(_.of('a'), _.evaluate(0)), 'a') }) it('execute', () => { U.deepStrictEqual(pipe(_.of('a'), _.execute(0)), 0) }) it('put', () => { U.deepStrictEqual(_.put(2)(1), [undefined, 2]) }) it('get', () => { U.deepStrictEqual(_.get()(1), [1, 1]) }) it('modify', () => { U.deepStrictEqual(_.modify(U.double)(1), [undefined, 2]) }) it('gets', () => { U.deepStrictEqual(_.gets(U.double)(1), [2, 1]) }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) )('state'), [{ a: 1, b: 'b', c: [1, 'b'] }, 'state'] ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b')))(undefined), [{ a: 1, b: 'b' }, undefined]) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => _.of(a + i)) U.deepStrictEqual(pipe(RA.empty, f)({}), [RA.empty, {}]) U.deepStrictEqual(pipe(input, f)({}), [['a0', 'b1'], {}]) }) // old it('sequenceArray', () => { const append = (n: number): _.State, number> => (s) => [n, [...s, n]] U.deepStrictEqual(pipe([append(1), append(2)], _.sequenceArray)([]), [ [1, 2], [1, 2] ]) }) }) }) ================================================ FILE: test/StateReaderTaskEither.ts ================================================ import * as assert from 'assert' import * as A from '../src/Array' import * as E from '../src/Either' import { pipe, SK, tuple } from '../src/function' import * as I from '../src/IO' import * as IE from '../src/IOEither' import * as O from '../src/Option' import * as R from '../src/Reader' import * as RE from '../src/ReaderEither' import * as RTE from '../src/ReaderTaskEither' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { of as stateOf, State } from '../src/State' import * as _ from '../src/StateReaderTaskEither' import * as S from '../src/string' import * as T from '../src/Task' import * as TE from '../src/TaskEither' import * as U from './util' const state: unknown = {} describe('StateReaderTaskEither', () => { describe('pipeables', () => { it('alt', async () => { const e1 = await pipe( _.right('a'), _.alt(() => _.left(1)), _.evaluate(state) )({})() U.deepStrictEqual(e1, E.right('a')) const e2 = await pipe( pipe( _.left(1), _.alt(() => _.right('b')), _.evaluate(state) ) )({})() U.deepStrictEqual(e2, E.right('b')) const e3 = await pipe( pipe( _.left(1), _.alt(() => _.left(2)), _.evaluate(state) ) )({})() U.deepStrictEqual(e3, E.left(2)) }) it('map', async () => { const e = await pipe(_.right('aaa'), _.map(S.size), _.evaluate(state))({})() U.deepStrictEqual(e, E.right(3)) }) it('ap', async () => { const e = await pipe(_.right(S.size), _.ap(_.right('aaa')), _.evaluate(state))({})() U.deepStrictEqual(e, E.right(3)) }) it('apFirst', async () => { const e = await pipe(_.right('a'), _.apFirst(_.right('b')), _.evaluate(state))({})() U.deepStrictEqual(e, E.right('a')) }) it('apFirstW', async () => { const fa = _.right('a') const fb = _.right(6) const e = await pipe(fa, _.apFirstW(fb), _.evaluate(state))({ k: 'v', x: 5 })() U.deepStrictEqual(e, E.right('a')) }) it('apSecond', async () => { const e = await pipe(_.right('a'), _.apSecond(_.right('b')), _.evaluate(state))({})() U.deepStrictEqual(e, E.right('b')) }) it('apSecondW', async () => { const fa = _.right('a') const fb = _.right(6) const e = await pipe(fa, _.apSecondW(fb), _.evaluate(state))({ k: 'v', x: 5 })() U.deepStrictEqual(e, E.right(6)) }) it('flatMap', async () => { const f = (s: string) => (s.length > 2 ? _.right(s.length) : _.right(0)) U.deepStrictEqual(await pipe(_.right('aaa'), _.flatMap(f), _.evaluate(state))({})(), E.right(3)) U.deepStrictEqual(await pipe(_.flatMap(_.right('aaa'), f), _.evaluate(state))({})(), E.right(3)) }) it('chain', async () => { const f = (s: string) => (s.length > 2 ? _.right(s.length) : _.right(0)) const e = await pipe(_.right('aaa'), _.chain(f), _.evaluate(state))({})() U.deepStrictEqual(e, E.right(3)) }) it('tap', async () => { const f = (s: string) => (s.length > 2 ? _.right(s.length) : _.right(0)) U.deepStrictEqual(await pipe(_.right('aaa'), _.tap(f), _.evaluate(state))({})(), E.right('aaa')) U.deepStrictEqual(await pipe(_.tap(_.right('aaa'), f), _.evaluate(state))({})(), E.right('aaa')) }) it('chainFirst', async () => { const f = (s: string) => (s.length > 2 ? _.right(s.length) : _.right(0)) const e = await pipe(_.right('aaa'), _.chainFirst(f), _.evaluate(state))({})() U.deepStrictEqual(e, E.right('aaa')) }) it('flatten', async () => { const e = await pipe(_.right(_.right('a')), _.flatten, _.evaluate(state))({})() U.deepStrictEqual(e, E.right('a')) }) type S = unknown type R1 = { readonly env1: unknown } type R2 = { readonly env2: unknown } type E1 = { readonly left1: unknown } type E2 = { readonly left2: unknown } it('flattenW', async () => { const e = await pipe( _.right>(_.right('a')), _.flattenW, _.evaluate(state) )({ env1: '', env2: '' })() U.deepStrictEqual(e, E.right('a')) }) it('bimap', async () => { const gt2 = (n: number): boolean => n > 2 const e1 = await pipe(_.right('aaa'), _.bimap(gt2, S.size), _.evaluate(state))({})() U.deepStrictEqual(e1, E.right(3)) const e2 = await pipe(_.left(3), _.bimap(gt2, S.size), _.evaluate(state))({})() U.deepStrictEqual(e2, E.left(true)) }) it('mapLeft', async () => { const gt2 = (n: number): boolean => n > 2 const e = await pipe(_.left(3), _.mapLeft(gt2), _.evaluate(state))({})() U.deepStrictEqual(e, E.left(true)) }) it('fromPredicate', async () => { const predicate = (n: number) => n >= 2 const gt2 = _.fromPredicate(predicate, (n) => `Invalid number ${n}`) const refinement = (u: string | number): u is number => typeof u === 'number' const isNumber = _.fromPredicate(refinement, (u) => `Invalid number ${String(u)}`) const e1 = await pipe(gt2(3), _.evaluate(state))({})() const e2 = await pipe(gt2(1), _.evaluate(state))({})() const e3 = await pipe(isNumber(4), _.evaluate(state))({})() U.deepStrictEqual(e1, E.right(3)) U.deepStrictEqual(e2, E.left('Invalid number 1')) U.deepStrictEqual(e3, E.right(4)) }) it('filterOrElse', async () => { const e1 = await pipe( _.right(12), _.filterOrElse( (n) => n > 10, () => 'a' ), _.evaluate(state) )({})() U.deepStrictEqual(e1, E.right(12)) const e2 = await pipe( _.right(8), _.filterOrElse( (n) => n > 10, () => 'a' ), _.evaluate(state) )({})() U.deepStrictEqual(e2, E.left('a')) }) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('applicativeStateReaderTaskEither', async () => { await U.assertSeq(_.Applicative, _.FromTask, (fa) => fa(null)(null)()) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('run', async () => { const ma = _.right('a') const e = await ma({})({})() assert.deepStrictEqual(e, E.right(['a', {}])) }) it('applicativeReaderTaskEitherSeq', async () => { const log: Array = [] const append = (message: string): _.StateReaderTaskEither<{}, {}, void, number> => _.rightTask(() => Promise.resolve(log.push(message))) const t1 = pipe( append('start 1'), _.chain(() => append('end 1')) ) const t2 = pipe( append('start 2'), _.chain(() => append('end 2')) ) const sequence = A.sequence(_.Applicative) U.deepStrictEqual(await sequence([t1, t2])({})({})(), E.right([[2, 4], {}])) U.deepStrictEqual(log, ['start 1', 'end 1', 'start 2', 'end 2']) }) it('execute', async () => { const ma = _.right('a') const e = await pipe(ma, _.execute(state))({})() U.deepStrictEqual(e, E.right({})) }) it('rightState', async () => { const s: State = (s) => [1, s] const e = await pipe(_.rightState(s), _.evaluate(state))({})() U.deepStrictEqual(e, E.right(1)) }) it('leftState', async () => { const s: State = (s) => [1, s] const e = await pipe(_.leftState(s), _.evaluate(state))({})() U.deepStrictEqual(e, E.left(1)) }) it('fromReaderTaskEither', async () => { const rte: RTE.ReaderTaskEither<{}, string, number> = RTE.right(1) const e = await pipe(_.fromReaderTaskEither(rte), _.evaluate(state))({})() U.deepStrictEqual(e, E.right(1)) }) it('left', async () => { const e = await _.left(1)({})({})() U.deepStrictEqual(e, E.left(1)) }) it('rightTask', async () => { const e = await _.rightTask(T.of(1))({})({})() assert.deepStrictEqual(e, E.right([1, {}])) }) it('leftTask', async () => { const e = await _.leftTask(T.of(1))({})({})() U.deepStrictEqual(e, E.left(1)) }) it('fromTaskEither', async () => { const e = await _.fromTaskEither(TE.of(1))({})({})() assert.deepStrictEqual(e, E.right([1, {}])) }) it('rightReader', async () => { const e = await _.rightReader(R.of(1))({})({})() assert.deepStrictEqual(e, E.right([1, {}])) }) it('leftReader', async () => { const e = await _.leftReader(R.of(1))({})({})() U.deepStrictEqual(e, E.left(1)) }) it('fromIOEither', async () => { const e1 = await _.fromIOEither(IE.right(1))({})({})() assert.deepStrictEqual(e1, E.right([1, {}])) const e2 = await _.fromIOEither(IE.left(1))({})({})() U.deepStrictEqual(e2, E.left(1)) }) it('fromEither', async () => { const e1 = await _.fromEither(E.right(1))({})({})() assert.deepStrictEqual(e1, E.right([1, {}])) const e2 = await _.fromEither(E.left(1))({})({})() U.deepStrictEqual(e2, E.left(1)) }) it('fromOption', async () => { const e1 = await _.fromOption(() => 'err')(O.some(1))({})({})() assert.deepStrictEqual(e1, E.right([1, {}])) const e2 = await _.fromOption(() => 'err')(O.none)({})({})() U.deepStrictEqual(e2, E.left('err')) }) it('rightIO', async () => { const e = await _.rightIO(I.of(1))({})({})() assert.deepStrictEqual(e, E.right([1, {}])) }) it('leftIO', async () => { const e = await _.leftIO(I.of(1))({})({})() U.deepStrictEqual(e, E.left(1)) }) it('fromOption', async () => { const e1 = await _.fromOption(() => 'none')(O.none)({})({})() U.deepStrictEqual(e1, E.left('none')) const e2 = await _.fromOption(() => 'none')(O.some(1))({})({})() assert.deepStrictEqual(e2, E.right([1, {}])) }) it('fromReaderEither', async () => { const e1 = await _.fromReaderEither(RE.left('a'))({})({})() U.deepStrictEqual(e1, E.left('a')) const e2 = await _.fromReaderEither(RE.right(1))({})({})() assert.deepStrictEqual(e2, E.right([1, {}])) }) it('chainEitherK', async () => { const f = (s: string) => E.right(s.length) const x = await pipe(_.right('a'), _.chainEitherK(f))(undefined)(undefined)() assert.deepStrictEqual(x, E.right([1, undefined])) }) it('chainIOEitherK', async () => { const f = (s: string) => IE.right(s.length) const x = await pipe(_.right('a'), _.chainIOEitherK(f))(undefined)(undefined)() assert.deepStrictEqual(x, E.right([1, undefined])) }) it('chainTaskEitherK', async () => { const f = (s: string) => TE.right(s.length) const x = await pipe(_.right('a'), _.chainTaskEitherK(f))(undefined)(undefined)() assert.deepStrictEqual(x, E.right([1, undefined])) }) it('flatMapTaskEither', async () => { const f = (s: string) => TE.right(s.length) const x = await pipe(_.right('a'), _.flatMapTaskEither(f))(undefined)(undefined)() assert.deepStrictEqual(x, E.right([1, undefined])) }) it('chainReaderTaskEitherK', async () => { const f = (s: string) => RTE.right(s.length) const x = await pipe(_.right('a'), _.chainReaderTaskEitherK(f))(undefined)(undefined)() assert.deepStrictEqual(x, E.right([1, undefined])) }) it('put', async () => { assert.deepStrictEqual(await _.put(2)(1)({})(), E.right([undefined, 2])) }) it('get', async () => { assert.deepStrictEqual(await _.get()(1)({})(), E.right([1, 1])) }) it('modify', async () => { assert.deepStrictEqual(await _.modify(U.double)(1)({})(), E.right([undefined, 2])) }) it('gets', async () => { U.deepStrictEqual(await _.gets(U.double)(1)({})(), E.right([2, 1])) }) it('do notation', async () => { assert.deepStrictEqual( await pipe( _.right(1), _.bindTo('a'), _.bind('b', () => _.right('b')), _.let('c', ({ a, b }) => [a, b]) )(undefined)(undefined)(), E.right([{ a: 1, b: 'b', c: [1, 'b'] }, undefined]) ) }) it('apS', async () => { assert.deepStrictEqual( await pipe(_.right(1), _.bindTo('a'), _.apS('b', _.right('b')))(undefined)( undefined )(), E.right([{ a: 1, b: 'b' }, undefined]) ) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(undefined)(undefined)(), E.right(tuple(RA.empty, undefined))) U.deepStrictEqual(await pipe(input, f)(undefined)(undefined)(), E.right(tuple(['a0', 'b1'], undefined))) U.deepStrictEqual(await pipe(['a', ''], f)(undefined)(undefined)(), E.left('e')) const append = (_i: number, n: number): _.StateReaderTaskEither, {}, Error, void> => _.modify((a) => [...a, n]) U.deepStrictEqual( await pipe( [1, 2, 3], _.traverseReadonlyArrayWithIndex(append), _.map(() => undefined) )([])({})(), E.right(tuple(undefined, [1, 2, 3])) ) }) it('sequenceReadonlyArray', async () => { const log: Array = [] const right = (n: number): _.StateReaderTaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.StateReaderTaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual( await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndex(SK))(undefined)(undefined)(), E.right(tuple([1, 2], undefined)) ) U.deepStrictEqual( await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndex(SK))(undefined)(undefined)(), E.left('a') ) U.deepStrictEqual( await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndex(SK))(undefined)(undefined)(), E.left('b') ) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) // old it('sequenceArray', async () => { const log: Array = [] const right = (n: number): _.StateReaderTaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.StateReaderTaskEither => _.leftIO(() => { log.push(s) return s }) assert.deepStrictEqual( await pipe([right(1), right(2)], _.sequenceArray)(undefined)(undefined)(), E.right([[1, 2], undefined]) ) U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceArray)(undefined)(undefined)(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceArray)(undefined)(undefined)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) it('#1486', async () => { const append = (n: number): _.StateReaderTaskEither, {}, Error, void> => _.modify((a) => [...a, n]) U.deepStrictEqual( await pipe( [1, 2, 3], _.traverseArray(append), _.map(() => undefined) )([])({})(), E.right(tuple(undefined, [1, 2, 3])) ) }) }) it('fromState', async () => { const s: State = (s) => [1, s] const e = await pipe(_.fromState(s), _.evaluate(state))({})() U.deepStrictEqual(e, E.right(1)) }) it('fromStateK', async () => { const ma = _.fromStateK( (n: number): State => (s) => [n * 2, s + 1] ) U.deepStrictEqual(await ma(3)(2)({})(), E.right([6, 3])) }) it('chainStateK', async () => { const f = _.chainStateK( (n: number): State => (s) => [n * 2, s + 1] ) const right: _.StateReaderTaskEither = _.right(3) U.deepStrictEqual(await pipe(right, f)(2)({})(), E.right([6, 3])) const left: _.StateReaderTaskEither = _.left('a') U.deepStrictEqual(await pipe(left, f)(2)({})(), E.left('a')) }) it('local', async () => { U.deepStrictEqual( await pipe( _.asks((n: number) => n + 1), _.local(S.size) )({})('aaa')(), E.right(tuple(4, {})) ) }) it('asksStateReaderTaskEither', async () => { interface Env { readonly count: number } const e: Env = { count: 0 } const f = (e: Env) => _.of(e.count + 1) U.deepStrictEqual(await _.asksStateReaderTaskEither(f)({})(e)(), E.right(tuple(1, {}))) }) it('tapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.tapEither(f), _.evaluate(state))({})(), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.tapEither(g), _.evaluate(state))({})(), E.left(1)) }) it('chainFirstEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainFirstEitherK(f), _.evaluate(state))({})(), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainFirstEitherK(g), _.evaluate(state))({})(), E.left(1)) }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(await pipe(_.ask(), _.tapIO(add), _.evaluate(state))(1)(), E.of(1)) U.deepStrictEqual(await pipe(_.left('error'), _.tapIO(add), _.evaluate(state))(undefined)(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('tapTask', async () => { const ref: Array = [] const add = (value: number) => T.fromIO(() => ref.push(value)) U.deepStrictEqual(await pipe(_.ask(), _.tapTask(add), _.evaluate(state))(1)(), E.of(1)) U.deepStrictEqual(await pipe(_.left('error'), _.tapTask(add), _.evaluate(state))(undefined)(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('as', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.as('b'), _.evaluate(state))(undefined)(), E.right('b')) U.deepStrictEqual(await pipe(_.as(_.left('error'), 'b'), _.evaluate(state))(undefined)(), E.left('error')) }) it('asUnit', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.asUnit, _.evaluate(state))(undefined)(), E.of(undefined)) }) it('tapReader', async () => { U.deepStrictEqual( await pipe( _.tapReader(_.of(1), () => R.of(2)), _.evaluate(state) )({})(), E.of(1) ) }) it('flatMapIO', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIO(() => I.of(2)), _.evaluate(state) )(undefined)(), E.of(2) ) }) it('flatMapTask', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.flatMapTask(f), _.evaluate(state))(undefined)(), E.of(1)) }) it('flatMapReader', async () => { U.deepStrictEqual( await pipe( _.flatMapReader(_.of(1), () => R.of(2)), _.evaluate(state) )(undefined)(), E.of(2) ) }) it('flatMapIOEither', async () => { U.deepStrictEqual( await pipe( _.flatMapIOEither(_.of(1), () => IE.of(2)), _.evaluate(state) )(undefined)(), E.of(2) ) }) it('flatMapEither', async () => { U.deepStrictEqual( await pipe( _.flatMapEither(_.of(1), () => E.of(2)), _.evaluate(state) )(undefined)(), E.of(2) ) }) it('flatMapOption', async () => { U.deepStrictEqual( await pipe( _.flatMapOption( _.of(1), () => O.of(2), () => 'error' ), _.evaluate(state) )(undefined)(), E.of(2) ) U.deepStrictEqual( await pipe( _.flatMapOption( _.of(1), () => O.none, () => 'error' ), _.evaluate(state) )(undefined)(), E.left('error') ) }) it('flatMapReaderTaskEither', async () => { U.deepStrictEqual( await pipe( _.flatMapReaderTaskEither(_.of(1), () => RTE.of(2)), _.evaluate(state) )(undefined)(), E.of(2) ) }) it('flatMapState', async () => { U.deepStrictEqual( await pipe( _.flatMapState(_.of(1), () => stateOf(2)), _.evaluate(state) )(undefined)(), E.of(2) ) }) }) ================================================ FILE: test/Store.ts ================================================ import { pipe } from '../src/function' import * as RA from '../src/ReadonlyArray' import * as _ from '../src/Store' import * as S from '../src/string' import * as U from './util' describe('Store', () => { describe('pipeables', () => { it('map', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual( _.extract( pipe( wa, _.map((n) => n + 1) ) ), 2 ) }) it('extend', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual( _.extract( pipe( wa, _.extend((wa) => _.extract( pipe( wa, _.map((n) => n + 1) ) ) ) ) ), 2 ) }) it('duplicate', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual(_.extract(_.extract(pipe(wa, _.duplicate))), 1) }) }) it('seek', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual(_.extract(pipe(wa, _.seek('aa'))), 2) }) it('seeks', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual( _.extract( pipe( wa, _.seeks((s) => s + 'a') ) ), 2 ) }) it('peeks', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual( pipe( wa, _.peeks((s) => s + 'a') ), 2 ) }) it('experiment', () => { const wa: _.Store = { peek: S.size, pos: 'a' } U.deepStrictEqual( pipe( wa, _.experiment(RA.Functor)((s) => [s, s + 'a']) ), [1, 2] ) }) }) ================================================ FILE: test/Strong.ts ================================================ import * as R from '../src/Reader' import { fanout, splitStrong } from '../src/Strong' import * as U from './util' describe('Strong', () => { it('splitStrong', () => { const ab = (s: string) => s.length const cd = (n: number) => n >= 2 U.deepStrictEqual(splitStrong({ ...R.Strong, ...R.Category })(ab, cd)(['foo', 2]), [3, true]) U.deepStrictEqual(splitStrong({ ...R.Strong, ...R.Category })(ab, cd)(['a', 1]), [1, false]) }) it('fanout', () => { const ab = (s: string) => s.length const ac = (s: string) => s === s.toLowerCase() U.deepStrictEqual(fanout({ ...R.Strong, ...R.Category })(ab, ac)('foo'), [3, true]) U.deepStrictEqual(fanout({ ...R.Strong, ...R.Category })(ab, ac)('A'), [1, false]) }) }) ================================================ FILE: test/Task.ts ================================================ import * as assert from 'assert' import { pipe, SK } from '../src/function' import * as I from '../src/IO' import * as RA from '../src/ReadonlyArray' import * as RNEA from '../src/ReadonlyNonEmptyArray' import * as S from '../src/string' import * as _ from '../src/Task' import * as U from './util' const delayReject = (n: number, a: A): _.Task => () => new Promise((_, reject) => { setTimeout(() => reject(a), n) }) const delay = (millis: number, a: A): _.Task => _.delay(millis)(_.of(a)) const assertOp = (f: (a: _.Task, b: _.Task) => _.Task) => async (a: _.Task, b: _.Task, expected: C, expectedLog: ReadonlyArray) => { const log: Array = [] const append: (ma: _.Task) => _.Task = _.chainFirst((x) => _.fromIO(() => { log.push(x) }) ) const c = await pipe(f(pipe(a, append), pipe(b, append)))() U.deepStrictEqual(c, expected) assert.deepStrictEqual(log, expectedLog) } describe('Task', () => { // ------------------------------------------------------------------------------------- // safety // ------------------------------------------------------------------------------------- // it('stack-safe', async () => { // const doProcessing = (number: number) => _.of(number * 2) // const pipeline = pipe(_.of(RNEA.range(1, 55000)), _.chain(RNEA.traverse(_.ApplicativeSeq)(doProcessing))) // const res = await pipeline() // expect(res.length).toBe(55000) // }) // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- it('map', async () => { U.deepStrictEqual(await pipe(delay(1, 2), _.map(U.double))(), 4) }) it('ap', async () => { const deepStrictEqual = assertOp((a, b) => pipe( _.of((a: string) => (b: string) => a + b), _.ap(a), _.ap(b) ) ) const a = pipe(_.of('a'), _.delay(100)) const b = _.of('b') await deepStrictEqual(a, b, 'ab', ['b', 'a']) }) it('apFirst', async () => { const deepStrictEqual = assertOp((a, b) => pipe(a, _.apFirst(b))) const a = pipe(_.of('a'), _.delay(100)) const b = _.of('b') await deepStrictEqual(a, b, 'a', ['b', 'a']) }) it('apSecond', async () => { const deepStrictEqual = assertOp((a, b) => pipe(a, _.apSecond(b))) const a = pipe(_.of('a'), _.delay(100)) const b = _.of('b') await deepStrictEqual(a, b, 'b', ['b', 'a']) }) it('flatMap', async () => { const f = (n: number): _.Task => () => Promise.resolve(n * 2) U.deepStrictEqual(await pipe(delay(1, 2), _.flatMap(f))(), 4) U.deepStrictEqual(await _.flatMap(delay(1, 2), f)(), 4) }) it('chain', async () => { const f = (n: number): _.Task => () => Promise.resolve(n * 2) U.deepStrictEqual(await pipe(delay(1, 2), _.chain(f))(), 4) }) it('tap', async () => { const f = (n: number): _.Task => () => Promise.resolve(n * 2) U.deepStrictEqual(await pipe(delay(1, 2), _.tap(f))(), 2) U.deepStrictEqual(await _.tap(delay(1, 2), f)(), 2) }) it('chainFirst', async () => { const f = (n: number): _.Task => () => Promise.resolve(n * 2) U.deepStrictEqual(await pipe(delay(1, 2), _.chainFirst(f))(), 2) }) it('flatten', async () => { U.deepStrictEqual(await pipe(_.of(_.of('a')), _.flatten)(), 'a') }) it('fromIO', async () => { const io = () => 1 const t = _.fromIO(io) U.deepStrictEqual(await t(), 1) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('applicativeTaskSeq', async () => { await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa()) }) it('applicativeTaskPar', async () => { await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa()) }) describe('getRaceMonoid', () => { const M = _.getRaceMonoid() it('concat', async () => { U.deepStrictEqual(await M.concat(delay(10, 1), delay(10, 2))(), 1) }) it('empty (right)', async () => { U.deepStrictEqual(await M.concat(delay(10, 1), M.empty)(), 1) }) it('empty (left)', async () => { U.deepStrictEqual(await M.concat(M.empty, delay(10, 1))(), 1) }) it('concat (rejected)', async () => { try { await M.concat(delayReject(10, 1), delayReject(10, 2))() } catch (actual) { return U.deepStrictEqual(actual, 1) } }) }) it('getMonoid', async () => { const M = _.getMonoid(S.Monoid) const deepStrictEqual = assertOp(M.concat) const a = pipe(_.of('a'), _.delay(100)) const b = _.of('b') await deepStrictEqual(a, b, 'ab', ['a', 'b']) await deepStrictEqual(a, M.empty, 'a', ['a', '']) await deepStrictEqual(M.empty, b, 'b', ['', 'b']) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('chainIOK', async () => { const f = (s: string) => I.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainIOK(f))(), 1) }) it('chainFirstIOK', async () => { const f = (s: string) => I.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.chainFirstIOK(f))(), 'a') }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(await pipe(_.of(1), _.tapIO(add))(), 1) U.deepStrictEqual(ref, [1]) }) it('do notation', async () => { U.deepStrictEqual( await pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) )(), { a: 1, b: 'b', c: [1, 'b'] } ) }) it('apS', async () => { U.deepStrictEqual(await pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b')))(), { a: 1, b: 'b' }) }) describe('array utils', () => { const input: RNEA.ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => _.of(a + i)) U.deepStrictEqual(await pipe(RA.empty, f)(), RA.empty) U.deepStrictEqual(await pipe(input, f)(), ['a0', 'b1']) }) it('traverseReadonlyArrayWithIndexSeq', async () => { const f = _.traverseReadonlyArrayWithIndexSeq((i, a: string) => _.of(a + i)) U.deepStrictEqual(await pipe(RA.empty, f)(), RA.empty) U.deepStrictEqual(await pipe(input, f)(), ['a0', 'b1']) }) it('sequenceReadonlyArray', async () => { const log: Array = [] const append = (n: number): _.Task => _.delay(n % 2 === 0 ? 50 : 100)( _.fromIO(() => { log.push(n) return n }) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.traverseReadonlyArrayWithIndex(SK))(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 2, 1, 3]) }) it('sequenceReadonlyArraySeq', async () => { const log: Array = [] const append = (n: number): _.Task => _.delay(n % 2 === 0 ? 50 : 100)( _.fromIO(() => { log.push(n) return n }) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.traverseReadonlyArrayWithIndexSeq(SK))(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 1, 2, 3]) }) // old it('sequenceArray', async () => { const log: Array = [] const append = (n: number): _.Task => _.delay(n % 2 === 0 ? 50 : 100)( _.fromIO(() => { log.push(n) return n }) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.sequenceArray)(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 2, 1, 3]) }) it('sequenceSeqArray', async () => { const log: Array = [] const append = (n: number): _.Task => _.delay(n % 2 === 0 ? 50 : 100)( _.fromIO(() => { log.push(n) return n }) ) const as = RA.makeBy(4, append) U.deepStrictEqual(await pipe(as, _.sequenceSeqArray)(), [0, 1, 2, 3]) U.deepStrictEqual(log, [0, 1, 2, 3]) }) }) it('as', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.as('b'))(), 'b') }) it('asUnit', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.asUnit)(), undefined) }) it('flatMapIO', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(), 2 ) }) }) ================================================ FILE: test/TaskEither.ts ================================================ import { sequenceT } from '../src/Apply' import * as E from '../src/Either' import { constVoid, identity, pipe, SK } from '../src/function' import * as I from '../src/IO' import * as IE from '../src/IOEither' import { monoidString } from '../src/Monoid' import * as N from '../src/number' import { none, some } from '../src/Option' import { pipeable } from '../src/pipeable' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import { left, right } from '../src/Separated' import * as S from '../src/string' import * as T from '../src/Task' import * as _ from '../src/TaskEither' import * as TO from '../src/TaskOption' import * as U from './util' describe('TaskEither', () => { // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- it('alt', async () => { U.deepStrictEqual( await pipe( _.left('a'), _.alt(() => _.right(1)) )(), E.right(1) ) }) it('map', async () => { U.deepStrictEqual(await pipe(_.right(1), _.map(U.double))(), E.right(2)) }) it('ap', async () => { U.deepStrictEqual(await pipe(_.right(U.double), _.ap(_.right(1)))(), E.right(2)) }) it('apFirst', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.apFirst(_.right('b')))(), E.right('a')) }) it('apFirstW', async () => { U.deepStrictEqual( await pipe(_.right('foo'), _.apFirstW(_.right(true)))(), E.right('foo') ) }) it('apSecond', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.apSecond(_.right('b')))(), E.right('b')) }) it('apSecondW', async () => { U.deepStrictEqual( await pipe(_.right('foo'), _.apSecondW(_.right(true)))(), E.right(true) ) }) it('flatMap', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.flatMap((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right(3) ) U.deepStrictEqual( await _.flatMap(_.right('foo'), (a) => (a.length > 2 ? _.right(a.length) : _.left('foo')))(), E.right(3) ) U.deepStrictEqual( await pipe( _.right('a'), _.flatMap((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.left('foo') ) U.deepStrictEqual( await _.flatMap(_.right('a'), (a) => (a.length > 2 ? _.right(a.length) : _.left('foo')))(), E.left('foo') ) }) it('chain', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.chain((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right('a'), _.chain((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.left('foo') ) }) it('tap', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.tap((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right('foo') ) U.deepStrictEqual( await _.tap(_.right('foo'), (a) => (a.length > 2 ? _.right(a.length) : _.left('foo')))(), E.right('foo') ) }) it('chainFirst', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.chainFirst((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right('foo') ) }) it('chainFirstW', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.chainFirstW((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right('foo') ) }) it('flatten', async () => { U.deepStrictEqual(await pipe(_.right(_.right('a')), _.flatten)(), E.right('a')) }) it('flattenW', async () => { U.deepStrictEqual( await pipe(_.right<'left1', _.TaskEither<'left2', 'a'>>(_.right('a')), _.flattenW)(), E.right('a') ) }) it('bimap', async () => { const f = (s: string): number => s.length const g = (n: number): boolean => n > 2 U.deepStrictEqual(await pipe(_.right(1), _.bimap(f, g))(), E.right(false)) U.deepStrictEqual(await pipe(_.left('foo'), _.bimap(f, g))(), E.left(3)) }) it('mapLeft', async () => { U.deepStrictEqual(await pipe(_.left(1), _.mapLeft(U.double))(), E.left(2)) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('getApplicativeTaskValidation', async () => { const A = _.getApplicativeTaskValidation(T.ApplicativePar, S.Semigroup) U.deepStrictEqual(await sequenceT(A)(_.left('a'), _.left('b'))(), E.left('ab')) const AV = _.getTaskValidation(S.Semigroup) U.deepStrictEqual(await sequenceT(AV)(_.left('a'), _.left('b'))(), E.left('ab')) }) it('getAltTaskValidation', async () => { const A = _.getAltTaskValidation(S.Semigroup) U.deepStrictEqual(await A.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) const AV = _.getTaskValidation(S.Semigroup) U.deepStrictEqual(await AV.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) }) describe('getTaskValidation', () => { const TV = _.getTaskValidation(S.Semigroup) it('ap', async () => { const fab = _.left('a') const fa = _.left('b') U.deepStrictEqual(await TV.ap(fab, fa)(), E.left('ab')) }) it('alt', async () => { U.deepStrictEqual(await TV.alt(_.right(1), () => _.right(2))(), E.right(1)) U.deepStrictEqual(await TV.alt(_.left('a'), () => _.right(2))(), E.right(2)) U.deepStrictEqual(await TV.alt(_.right(1), () => _.left('b'))(), E.right(1)) U.deepStrictEqual(await TV.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) }) }) describe('getCompactable', () => { const C = _.getCompactable(S.Monoid) it('compact', async () => { U.deepStrictEqual(await C.compact(_.right(some(1)))(), E.right(1)) }) it('separate', async () => { const s1 = C.separate(_.left('a')) U.deepStrictEqual(await left(s1)(), E.left('a')) U.deepStrictEqual(await right(s1)(), E.left('a')) const s2 = C.separate(_.right(E.left('a'))) U.deepStrictEqual(await left(s2)(), E.right('a')) U.deepStrictEqual(await right(s2)(), E.left('')) const s3 = C.separate(_.right(E.right(1))) U.deepStrictEqual(await left(s3)(), E.left('')) U.deepStrictEqual(await right(s3)(), E.right(1)) }) }) describe('getFilterable', () => { const F_ = _.getFilterable(RA.getMonoid()) const { filter, filterMap, partition, partitionMap } = pipeable(F_) it('filter', async () => { U.deepStrictEqual( await pipe( _.right(1), filter((n) => n > 0) )(), await _.right(1)() ) U.deepStrictEqual( await pipe( _.right(-1), filter((n) => n > 0) )(), await _.left([])() ) U.deepStrictEqual( await pipe( _.left(['a']), filter((n) => n > 0) )(), await _.left(['a'])() ) }) it('filterMap', async () => { U.deepStrictEqual( await pipe( _.right('aaa'), filterMap((s) => (s.length > 1 ? some(s.length) : none)) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right('a'), filterMap((s) => (s.length > 1 ? some(s.length) : none)) )(), E.left([]) ) U.deepStrictEqual( await pipe( _.left, string>(['e']), filterMap((s) => (s.length > 1 ? some(s.length) : none)) )(), E.left(['e']) ) }) it('partition', async () => { const s = pipe( _.right('a'), partition((s) => s.length > 2) ) U.deepStrictEqual(await left(s)(), E.right('a')) U.deepStrictEqual(await right(s)(), E.left([])) }) it('partitionMap', async () => { const s = pipe( _.right('a'), partitionMap((s) => (s.length > 2 ? E.right(s.length) : E.left(false))) ) U.deepStrictEqual(await left(s)(), E.right(false)) U.deepStrictEqual(await right(s)(), E.left([])) }) }) describe('getSemigroup', () => { it('concat', async () => { const S = _.getSemigroup(N.SemigroupSum) U.deepStrictEqual(await S.concat(_.left('a'), _.left('b'))(), E.left('a')) U.deepStrictEqual(await S.concat(_.left('a'), _.right(2))(), E.right(2)) U.deepStrictEqual(await S.concat(_.right(1), _.left('b'))(), E.right(1)) U.deepStrictEqual(await S.concat(_.right(1), _.right(2))(), E.right(3)) }) }) describe('getApplyMonoid', () => { const M = _.getApplyMonoid(monoidString) it('concat (right)', async () => { return U.deepStrictEqual(await M.concat(_.right('a'), _.right('b'))(), E.right('ab')) }) it('concat (left)', async () => { return U.deepStrictEqual(await M.concat(_.right('a'), _.left('b'))(), E.left('b')) }) it('empty (right)', async () => { return U.deepStrictEqual(await M.concat(_.right('a'), M.empty)(), E.right('a')) }) it('empty (left)', async () => { return U.deepStrictEqual(await M.concat(M.empty, _.right('a'))(), E.right('a')) }) }) it('applicativeTaskEitherSeq', async () => { await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa()) }) it('applicativeTaskEitherPar', async () => { await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa()) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('taskify', async () => { const api1 = (_path: string, callback: (err: Error | null | undefined, result?: string) => void): void => { callback(null, 'ok') } const api2 = (_path: string, callback: (err: Error | null | undefined, result?: string) => void): void => { callback(undefined, 'ok') } const api3 = (_path: string, callback: (err: Error | null | undefined, result?: string) => void): void => { callback(new Error('ko')) } U.deepStrictEqual(await _.taskify(api1)('foo')(), E.right('ok')) U.deepStrictEqual(await _.taskify(api2)('foo')(), E.right('ok')) U.deepStrictEqual(await _.taskify(api3)('foo')(), E.left(new Error('ko'))) }) it('composed taskify', async () => { const api = (callback: (err: Error | null | undefined, result?: string) => void): void => { callback(null, 'ok') } const taskApi = _.taskify(api)() U.deepStrictEqual(await taskApi(), E.right('ok')) U.deepStrictEqual(await taskApi(), E.right('ok')) }) describe('bracket', () => { let log: Array = [] const acquireFailure = _.left('acquire failure') const acquireSuccess = _.right({ res: 'acquire success' }) const useSuccess = () => _.right('use success') const useFailure = () => _.left('use failure') const releaseSuccess = () => _.rightIO(() => { log.push('release success') }) const releaseFailure = () => _.left('release failure') beforeEach(() => { log = [] }) it('should return the acquire error if acquire fails', async () => { U.deepStrictEqual(await _.bracket(acquireFailure, useSuccess, releaseSuccess)(), E.left('acquire failure')) }) it('body and release must not be called if acquire fails', async () => { await _.bracket(acquireFailure, useSuccess, releaseSuccess)() U.deepStrictEqual(log, []) }) it('should return the use error if use fails and release does not', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useFailure, releaseSuccess)(), E.left('use failure')) }) it('should return the release error if both use and release fail', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useFailure, releaseFailure)(), E.left('release failure')) }) it('release must be called if the body returns', async () => { await _.bracket(acquireSuccess, useSuccess, releaseSuccess)() U.deepStrictEqual(log, ['release success']) }) it('release must be called if the body throws', async () => { await _.bracket(acquireSuccess, useFailure, releaseSuccess)() U.deepStrictEqual(log, ['release success']) }) it('should return the release error if release fails', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useSuccess, releaseFailure)(), E.left('release failure')) }) }) it('bracketW', async () => { const res = await _.bracketW( _.right('string'), (_a: string) => _.right('test'), (_a: string, _e: E.Either) => _.right(constVoid()) )() U.deepStrictEqual(res, E.right('test')) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('filterOrElse', async () => { U.deepStrictEqual( await pipe( _.right(12), _.filterOrElse( (n) => n > 10, () => 'a' ) )(), E.right(12) ) U.deepStrictEqual( await pipe( _.right(7), _.filterOrElse( (n) => n > 10, () => 'a' ) )(), E.left('a') ) }) it('orElse', async () => { U.deepStrictEqual( await pipe( _.left('foo'), _.orElse((l) => _.right(l.length)) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right(1), _.orElse(() => _.right(2)) )(), E.right(1) ) }) it('orElseW', async () => { U.deepStrictEqual( await pipe( _.left('foo'), _.orElseW((l) => _.right(l.length)) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right(1), _.orElseW(() => _.right(2)) )(), E.right(1) ) }) it('tapError', async () => { const f = (e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!')) U.deepStrictEqual(await pipe(_.right(1), _.tapError(f))(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), _.tapError(f))(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), _.tapError(f))(), E.left('aa!')) U.deepStrictEqual(await _.tapError(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await _.tapError(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(await _.tapError(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirst', async () => { const f = _.orElseFirst((e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!'))) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirstW', async () => { const f = _.orElseFirstW((e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!'))) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirstIOK', async () => { const f = _.orElseFirstIOK((e: string) => I.of(e.length)) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a')) }) it('orElseFirstTaskK', async () => { const f = _.orElseFirstTaskK((e: string) => T.of(e.length)) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a')) }) it('orLeft', async () => { const f = _.orLeft((e: string) => T.of(e + '!')) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a!')) }) it('swap', async () => { U.deepStrictEqual(await _.swap(_.right(1))(), E.left(1)) U.deepStrictEqual(await _.swap(_.left('a'))(), E.right('a')) }) it('flatMapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.flatMapEither(f))(), E.right(1)) }) it('chainEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainEitherK(f))(), E.right(1)) }) it('tapEither', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.tapEither(f))(), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.tapEither(g))(), E.left(1)) }) it('chainFirstEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainFirstEitherK(f))(), E.right('a')) const g = (s: string) => E.left(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainFirstEitherK(g))(), E.left(1)) }) it('chainIOEitherK', async () => { const f = (s: string) => IE.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainIOEitherK(f))(), E.right(1)) }) describe('tryCatchK', () => { test('with a resolved promise', async () => { const g = _.tryCatchK((a: number) => Promise.resolve(a), identity) U.deepStrictEqual(await g(1)(), E.right(1)) }) test('with a rejected promise', async () => { const g = _.tryCatchK((a: number) => Promise.reject(a), identity) U.deepStrictEqual(await g(-1)(), E.left(-1)) }) test('with a thrown error', async () => { const g = _.tryCatchK((_: number) => { throw new Error('Some error') }, identity) U.deepStrictEqual(await g(-1)(), E.left(new Error('Some error'))) }) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('rightIO', async () => { const io = () => 1 const fa = _.rightIO(io) U.deepStrictEqual(await fa(), E.right(1)) }) it('leftIO', async () => { U.deepStrictEqual(await _.leftIO(I.of(1))(), E.left(1)) }) describe('tryCatch', () => { test('with a resolving promise', async () => { U.deepStrictEqual(await _.tryCatch(() => Promise.resolve(1), identity)(), E.right(1)) }) test('with a rejected promise', async () => { U.deepStrictEqual(await _.tryCatch(() => Promise.reject(1), identity)(), E.left(1)) }) test('with a thrown error', async () => { U.deepStrictEqual( await _.tryCatch(() => { throw new Error('Some error') }, identity)(), E.left(new Error('Some error')) ) }) }) it('fromNullable', async () => { const testNullable = _.fromNullable('foo') U.deepStrictEqual(await testNullable(1)(), E.right(1)) U.deepStrictEqual(await testNullable(null)(), E.left('foo')) U.deepStrictEqual(await testNullable(undefined)(), E.left('foo')) }) it('fromNullableK', async () => { const f = _.fromNullableK('foo')((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(await f(1)(), E.right(1)) U.deepStrictEqual(await f(0)(), E.left('foo')) U.deepStrictEqual(await f(-1)(), E.left('foo')) }) it('chainNullableK', async () => { const f = _.chainNullableK('foo')((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(await f(_.of(1))(), E.right(1)) U.deepStrictEqual(await f(_.of(0))(), E.left('foo')) U.deepStrictEqual(await f(_.of(-1))(), E.left('foo')) }) it('fromIOEither', async () => { U.deepStrictEqual(await _.fromIOEither(() => E.right(1))(), E.right(1)) U.deepStrictEqual(await _.fromIOEither(() => E.left('foo'))(), E.left('foo')) }) it('fromOption', async () => { U.deepStrictEqual( await pipe( none, _.fromOption(() => 'none') )(), E.left('none') ) U.deepStrictEqual( await pipe( some(1), _.fromOption(() => 'none') )(), E.right(1) ) }) it('fromTaskOption', async () => { U.deepStrictEqual( await pipe( TO.none, _.fromTaskOption(() => 'none') )(), E.left('none') ) U.deepStrictEqual( await pipe( TO.some(1), _.fromTaskOption(() => 'none') )(), E.right(1) ) }) it('fromPredicate', async () => { const gt2 = _.fromPredicate( (n: number) => n >= 2, (n) => `Invalid number ${n}` ) U.deepStrictEqual(await gt2(3)(), E.right(3)) U.deepStrictEqual(await gt2(1)(), E.left('Invalid number 1')) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' U.deepStrictEqual(await _.fromPredicate(isNumber, () => 'not a number')(4)(), E.right(4)) }) it('do notation', async () => { U.deepStrictEqual( await pipe( _.right(1), _.bindTo('a'), _.bind('b', () => _.right('b')), _.let('c', ({ a, b }) => [a, b]) )(), E.right({ a: 1, b: 'b', c: [1, 'b'] }) ) }) // TODO: PR #1584 // it('do notation ensuring proper param passthrough', async () => { // const c = (p: { readonly a: number }) => _.right(p.a) // const d = (p: { readonly b: string }) => _.right(p.b) // U.deepStrictEqual( // await pipe( // _.right(1), // _.bindTo('a'), // _.bind('b', () => _.right('b')), // _.bind('c', c), // _.bind('d', d), // _.bind( // 'e', // _.fromOptionK(() => 'err')((p: { readonly c: number }) => some(p.c)) // ), // _.bind( // 'f', // _.fromOptionK(() => 'err')((p) => some(p.b)) // ) // )(), // E.right({ a: 1, b: 'b', c: 1, d: 'b', e: 1, f: 'b' }) // ) // }) // it('do notation bindW ensuring proper param passthrough', async () => { // const c = (p: { readonly a: number }) => _.right(p.a) // const d = (p: { readonly b: string }) => _.right(p.b) // U.deepStrictEqual( // await pipe( // _.right(1), // _.bindTo('a'), // _.bindW('b', () => _.right('b')), // _.bindW('c', c), // _.bindW('d', d), // _.bindW( // 'e', // _.fromOptionK(() => 1)((p: { readonly c: number }) => some(p.c)) // ), // _.bindW( // 'f', // _.fromOptionK(() => ({ err: 'err' }))((p) => some(p.b)) // ) // )(), // E.right({ a: 1, b: 'b', c: 1, d: 'b', e: 1, f: 'b' }) // ) // }) it('apS', async () => { U.deepStrictEqual( await pipe(_.right(1), _.bindTo('a'), _.apS('b', _.right('b')))(), E.right({ a: 1, b: 'b' }) ) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(), E.right(RA.empty)) U.deepStrictEqual(await pipe(input, f)(), E.right(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(), E.left('e')) }) it('traverseReadonlyArrayWithIndexSeq', async () => { const f = _.traverseReadonlyArrayWithIndexSeq((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(), E.right(RA.empty)) U.deepStrictEqual(await pipe(input, f)(), E.right(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(), E.left('e')) }) it('sequenceReadonlyArray', async () => { const log: Array = [] const right = (n: number): _.TaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndex(SK))(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndex(SK))(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndex(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceReadonlyArraySeq', async () => { const log: Array = [] const right = (n: number): _.TaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) // old it('sequenceArray', async () => { const log: Array = [] const right = (n: number): _.TaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.sequenceArray)(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceArray)(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceArray)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceSeqArray', async () => { const log: Array = [] const right = (n: number): _.TaskEither => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.sequenceSeqArray)(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceSeqArray)(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceSeqArray)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) }) it('match', async () => { const f = _.match( () => 'left', () => 'right' ) U.deepStrictEqual(await f(_.right(1))(), 'right') U.deepStrictEqual(await f(_.left(''))(), 'left') }) it('matchE', async () => { const f = _.matchE( () => T.of('left'), () => T.of('right') ) U.deepStrictEqual(await f(_.right(1))(), 'right') U.deepStrictEqual(await f(_.left(''))(), 'left') }) it('chainTaskOptionK', async () => { const f = _.chainTaskOptionK(() => 'a')((n: number) => (n > 0 ? TO.some(n * 2) : TO.none)) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(2)) U.deepStrictEqual(await pipe(_.right(-1), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('b'), f)(), E.left('b')) }) it('flatMapTaskOption', async () => { const f = _.flatMapTaskOption( (n: number) => (n > 0 ? TO.some(n * 2) : TO.none), () => 'a' ) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(2)) U.deepStrictEqual(await pipe(_.right(-1), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('b'), f)(), E.left('b')) }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(await pipe(_.of(1), _.tapIO(add))(), E.of(1)) U.deepStrictEqual(await pipe(_.left('error'), _.tapIO(add))(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('as', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.as('b'))(), E.right('b')) U.deepStrictEqual(await _.as(_.of('a'), 'b')(), E.right('b')) U.deepStrictEqual(await _.as(_.left('error'), 'b')(), E.left('error')) }) it('asUnit', async () => { U.deepStrictEqual(await pipe(_.of('a'), _.asUnit)(), E.of(undefined)) }) it('tapTask', async () => { const ref: Array = [] const add = (value: number) => T.fromIO(() => ref.push(value)) U.deepStrictEqual(await pipe(_.of(1), _.tapTask(add))(), E.of(1)) U.deepStrictEqual(await pipe(_.left('error'), _.tapTask(add))(), E.left('error')) U.deepStrictEqual(ref, [1]) }) it('flatMapIO', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIO(() => I.of(2)) )(), E.of(2) ) }) it('flatMapTask', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.flatMapTask(f))(), E.of(1)) }) it('flatMapIOEither', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIOEither(() => IE.of(2)) )(), E.of(2) ) }) }) ================================================ FILE: test/TaskOption.ts ================================================ import * as E from '../src/Either' import { pipe, SK } from '../src/function' import * as IO from '../src/IO' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' import * as T from '../src/Task' import * as TE from '../src/TaskEither' import * as _ from '../src/TaskOption' import * as U from './util' describe('TaskOption', () => { // ------------------------------------------------------------------------------------- // type class members // ------------------------------------------------------------------------------------- it('map', async () => { U.deepStrictEqual(await pipe(_.some(1), _.map(U.double))(), O.some(2)) }) it('ap', async () => { U.deepStrictEqual(await pipe(_.some(U.double), _.ap(_.some(2)))(), O.some(4)) U.deepStrictEqual(await pipe(_.some(U.double), _.ap(_.none))(), O.none) U.deepStrictEqual(await pipe(_.none, _.ap(_.some(2)))(), O.none) U.deepStrictEqual(await pipe(_.none, _.ap(_.none))(), O.none) }) it('flatMap', async () => { const f = (n: number) => _.some(n * 2) const g = () => _.none U.deepStrictEqual(await pipe(_.some(1), _.flatMap(f))(), O.some(2)) U.deepStrictEqual(await pipe(_.none, _.flatMap(f))(), O.none) U.deepStrictEqual(await pipe(_.some(1), _.flatMap(g))(), O.none) U.deepStrictEqual(await pipe(_.none, _.flatMap(g))(), O.none) U.deepStrictEqual(await _.flatMap(_.some(1), f)(), O.some(2)) U.deepStrictEqual(await _.flatMap(_.none, f)(), O.none) U.deepStrictEqual(await _.flatMap(_.some(1), g)(), O.none) U.deepStrictEqual(await _.flatMap(_.none, g)(), O.none) }) it('chain', async () => { const f = (n: number) => _.some(n * 2) const g = () => _.none U.deepStrictEqual(await pipe(_.some(1), _.chain(f))(), O.some(2)) U.deepStrictEqual(await pipe(_.none, _.chain(f))(), O.none) U.deepStrictEqual(await pipe(_.some(1), _.chain(g))(), O.none) U.deepStrictEqual(await pipe(_.none, _.chain(g))(), O.none) }) it('alt', async () => { U.deepStrictEqual( await pipe( _.some(1), _.alt(() => _.some(2)) )(), O.some(1) ) U.deepStrictEqual( await pipe( _.some(2), _.alt(() => _.none as _.TaskOption) )(), O.some(2) ) U.deepStrictEqual( await pipe( _.none, _.alt(() => _.some(1)) )(), O.some(1) ) U.deepStrictEqual( await pipe( _.none, _.alt(() => _.none) )(), O.none ) }) it('zero', async () => { U.deepStrictEqual(await _.zero()(), O.none) }) it('fromIO', async () => { U.deepStrictEqual(await _.fromIO(() => 1)(), O.some(1)) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('ApplicativeSeq', async () => { await U.assertSeq(_.ApplySeq, _.FromTask, (fa) => fa()) await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa()) }) it('ApplicativePar', async () => { await U.assertPar(_.ApplyPar, _.FromTask, (fa) => fa()) await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa()) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- describe('tryCatch', () => { test('with a resolving promise', async () => { U.deepStrictEqual(await _.tryCatch(() => Promise.resolve(1))(), O.some(1)) }) test('with a rejected promise', async () => { U.deepStrictEqual(await _.tryCatch(() => Promise.reject(1))(), O.none) }) test('with a thrown error', async () => { U.deepStrictEqual( await _.tryCatch(() => { throw new Error('Some error') })(), O.none ) }) }) it('fromNullable', async () => { U.deepStrictEqual(await _.fromNullable(1)(), O.some(1)) U.deepStrictEqual(await _.fromNullable(null)(), O.none) U.deepStrictEqual(await _.fromNullable(undefined)(), O.none) }) it('fromNullableK', async () => { const f = _.fromNullableK((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(await f(1)(), O.some(1)) U.deepStrictEqual(await f(0)(), O.none) U.deepStrictEqual(await f(-1)(), O.none) }) it('chainNullableK', async () => { const f = _.chainNullableK((n: number) => (n > 0 ? n : n === 0 ? null : undefined)) U.deepStrictEqual(await f(_.of(1))(), O.some(1)) U.deepStrictEqual(await f(_.of(0))(), O.none) U.deepStrictEqual(await f(_.of(-1))(), O.none) }) it('fromPredicate', async () => { const p = (n: number): boolean => n > 2 const f = _.fromPredicate(p) U.deepStrictEqual(await f(1)(), O.none) U.deepStrictEqual(await f(3)(), O.some(3)) }) it('fromTaskEither', async () => { const pl = TE.left('a') const pr = TE.right('a') const fl = _.fromTaskEither(pl) const fr = _.fromTaskEither(pr) U.deepStrictEqual(await fl(), O.none) U.deepStrictEqual(await fr(), O.some('a')) }) // ------------------------------------------------------------------------------------- // destructors // ------------------------------------------------------------------------------------- it('fold', async () => { const f = _.fold( () => T.of('none'), (a) => T.of(`some(${a})`) ) U.deepStrictEqual(await pipe(_.some(1), f)(), 'some(1)') U.deepStrictEqual(await pipe(_.none, f)(), 'none') }) it('getOrElse', async () => { U.deepStrictEqual( await pipe( _.some(1), _.getOrElse(() => T.of(2)) )(), 1 ) U.deepStrictEqual( await pipe( _.none, _.getOrElse(() => T.of(2)) )(), 2 ) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('fromOptionK', async () => { const f = _.fromOptionK((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(await f(1)(), O.some(1)) U.deepStrictEqual(await f(-1)(), O.none) }) it('chainOptionK', async () => { const f = _.chainOptionK((n: number) => (n > 0 ? O.some(n) : O.none)) U.deepStrictEqual(await f(_.some(1))(), O.some(1)) U.deepStrictEqual(await f(_.some(-1))(), O.none) U.deepStrictEqual(await f(_.none)(), O.none) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none)) U.deepStrictEqual(await pipe(RA.empty, f)(), O.some(RA.empty)) U.deepStrictEqual(await pipe(input, f)(), O.some(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(), O.none) }) it('traverseReadonlyArrayWithIndexSeq', async () => { const f = _.traverseReadonlyArrayWithIndexSeq((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none)) U.deepStrictEqual(await pipe(RA.empty, f)(), O.some(RA.empty)) U.deepStrictEqual(await pipe(input, f)(), O.some(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(), O.none) }) it('sequenceReadonlyArray', async () => { const log: Array = [] const some = (n: number): _.TaskOption => _.fromIO(() => { log.push(n) return n }) const none = (s: string): _.TaskOption => pipe( T.fromIO(() => { log.push(s) return s }), T.map(() => O.none) ) U.deepStrictEqual(await pipe([some(1), some(2)], _.traverseReadonlyArrayWithIndex(SK))(), O.some([1, 2])) U.deepStrictEqual(await pipe([some(3), none('a')], _.traverseReadonlyArrayWithIndex(SK))(), O.none) U.deepStrictEqual(await pipe([none('b'), some(4)], _.traverseReadonlyArrayWithIndex(SK))(), O.none) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceReadonlyArraySeq', async () => { const log: Array = [] const some = (n: number): _.TaskOption => _.fromIO(() => { log.push(n) return n }) const none = (s: string): _.TaskOption => pipe( T.fromIO(() => { log.push(s) return s }), T.map(() => O.none) ) U.deepStrictEqual(await pipe([some(1), some(2)], _.traverseReadonlyArrayWithIndexSeq(SK))(), O.some([1, 2])) U.deepStrictEqual(await pipe([some(3), none('a')], _.traverseReadonlyArrayWithIndexSeq(SK))(), O.none) U.deepStrictEqual(await pipe([none('b'), some(4)], _.traverseReadonlyArrayWithIndexSeq(SK))(), O.none) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) // old it('sequenceArray', async () => { const log: Array = [] const some = (n: number): _.TaskOption => _.fromIO(() => { log.push(n) return n }) const none = (s: string): _.TaskOption => pipe( T.fromIO(() => { log.push(s) return s }), T.map(() => O.none) ) U.deepStrictEqual(await pipe([some(1), some(2)], _.sequenceArray)(), O.some([1, 2])) U.deepStrictEqual(await pipe([some(3), none('a')], _.sequenceArray)(), O.none) U.deepStrictEqual(await pipe([none('b'), some(4)], _.sequenceArray)(), O.none) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceSeqArray', async () => { const log: Array = [] const some = (n: number): _.TaskOption => _.fromIO(() => { log.push(n) return n }) const none = (s: string): _.TaskOption => pipe( T.fromIO(() => { log.push(s) return s }), T.map(() => O.none) ) U.deepStrictEqual(await pipe([some(1), some(2)], _.sequenceSeqArray)(), O.some([1, 2])) U.deepStrictEqual(await pipe([some(3), none('a')], _.sequenceSeqArray)(), O.none) U.deepStrictEqual(await pipe([none('b'), some(4)], _.sequenceSeqArray)(), O.none) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) }) describe('tryCatchK', () => { test('with a resolved promise', async () => { const g = _.tryCatchK((a: number) => Promise.resolve(a)) U.deepStrictEqual(await g(1)(), O.some(1)) }) test('with a rejected promise', async () => { const g = _.tryCatchK((a: number) => Promise.reject(a)) U.deepStrictEqual(await g(-1)(), O.none) }) test('with a thrown error', async () => { const g = _.tryCatchK((_: number) => { throw new Error('Some error') }) U.deepStrictEqual(await g(-1)(), O.none) }) }) it('match', async () => { const f = _.match( () => 'none', (a) => `some(${a})` ) U.deepStrictEqual(await pipe(_.some(1), f)(), 'some(1)') U.deepStrictEqual(await pipe(_.none, f)(), 'none') }) it('matchE', async () => { const f = _.matchE( () => T.of('none'), (a) => T.of(`some(${a})`) ) U.deepStrictEqual(await pipe(_.some(1), f)(), 'some(1)') U.deepStrictEqual(await pipe(_.none, f)(), 'none') }) it('fromEitherK', async () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.fromEitherK(f) U.deepStrictEqual(await g('')(), O.some('!')) U.deepStrictEqual(await g('a')(), O.some('a!')) U.deepStrictEqual(await g('aa')(), O.some('aa!')) U.deepStrictEqual(await g('aaa')(), O.none) }) it('chainEitherK', async () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.chainEitherK(f) U.deepStrictEqual(await g(_.of(''))(), O.some('!')) U.deepStrictEqual(await g(_.of('a'))(), O.some('a!')) U.deepStrictEqual(await g(_.of('aa'))(), O.some('aa!')) U.deepStrictEqual(await g(_.of('aaa'))(), O.none) }) it('tapEither', async () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.tapEither(f) U.deepStrictEqual(await g(_.of(''))(), O.some('')) U.deepStrictEqual(await g(_.of('a'))(), O.some('a')) U.deepStrictEqual(await g(_.of('aa'))(), O.some('aa')) U.deepStrictEqual(await g(_.of('aaa'))(), O.none) }) it('chainFirstEitherK', async () => { const f = (s: string) => (s.length <= 2 ? E.right(s + '!') : E.left(s.length)) const g = _.chainFirstEitherK(f) U.deepStrictEqual(await g(_.of(''))(), O.some('')) U.deepStrictEqual(await g(_.of('a'))(), O.some('a')) U.deepStrictEqual(await g(_.of('aa'))(), O.some('aa')) U.deepStrictEqual(await g(_.of('aaa'))(), O.none) }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => () => ref.push(value) U.deepStrictEqual(await pipe(_.of(1), _.tapIO(add))(), O.of(1)) U.deepStrictEqual(await pipe(_.none, _.tapIO(add))(), O.none) U.deepStrictEqual(ref, [1]) }) it('as', async () => { U.deepStrictEqual(await pipe(_.some('a'), _.as('b'))(), O.some('b')) U.deepStrictEqual(await _.as(_.of('a'), 'b')(), O.some('b')) U.deepStrictEqual(await _.as(_.none, 'b')(), O.none) }) it('asUnit', async () => { U.deepStrictEqual(await pipe(_.some('a'), _.asUnit)(), O.some(undefined)) }) it('tapIO', async () => { const ref: Array = [] const add = (value: number) => T.fromIO(() => ref.push(value)) U.deepStrictEqual(await pipe(_.of(1), _.tapTask(add))(), O.of(1)) U.deepStrictEqual(await pipe(_.none, _.tapTask(add))(), O.none) U.deepStrictEqual(ref, [1]) }) it('flatMapIO', async () => { U.deepStrictEqual( await pipe( _.of(1), _.flatMapIO(() => IO.of(2)) )(), O.of(2) ) }) it('flatMapTask', async () => { const f = (s: string) => T.of(s.length) U.deepStrictEqual(await pipe(_.of('a'), _.flatMapTask(f))(), O.of(1)) }) }) ================================================ FILE: test/TaskThese.ts ================================================ import * as E from '../src/Either' import { pipe, SK } from '../src/function' import * as IO from '../src/IO' import * as N from '../src/number' import * as RA from '../src/ReadonlyArray' import * as S from '../src/string' import * as T from '../src/Task' import * as _ from '../src/TaskThese' import * as TH from '../src/These' import * as U from './util' describe('TaskThese', () => { // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- it('map', async () => { U.deepStrictEqual(await pipe(_.right(1), _.map(U.double))(), TH.right(2)) }) it('bimap', async () => { const f = (e: string) => e + e const g = (a: number) => a + 1 U.deepStrictEqual(await pipe(_.right(1), _.bimap(f, g))(), TH.right(2)) U.deepStrictEqual(await pipe(_.left('a'), _.bimap(f, g))(), TH.left('aa')) U.deepStrictEqual(await pipe(_.both('a', 1), _.bimap(f, g))(), TH.both('aa', 2)) }) it('mapLeft', async () => { const f = (e: string) => e + e U.deepStrictEqual(await pipe(_.right(1), _.mapLeft(f))(), TH.right(1)) U.deepStrictEqual(await pipe(_.left('a'), _.mapLeft(f))(), TH.left('aa')) U.deepStrictEqual(await pipe(_.both('a', 1), _.mapLeft(f))(), TH.both('aa', 1)) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- describe('getApplicative', () => { it('Par', async () => { await U.assertSeq(_.getApplicative(T.ApplicativeSeq, S.Semigroup), _.FromTask, (fa) => fa()) }) it('Seq', async () => { await U.assertPar(_.getApplicative(T.ApplicativePar, S.Semigroup), _.FromTask, (fa) => fa()) }) }) it('getSemigroup', async () => { const SSN = _.getSemigroup(S.Semigroup, N.SemigroupSum) U.deepStrictEqual(await SSN.concat(_.right(1), _.right(2))(), TH.right(3)) U.deepStrictEqual(await SSN.concat(_.right(1), _.left('a'))(), TH.both('a', 1)) U.deepStrictEqual(await SSN.concat(_.left('a'), _.left('b'))(), TH.left('ab')) U.deepStrictEqual(await SSN.concat(_.right(1), _.both('a', 2))(), TH.both('a', 3)) U.deepStrictEqual(await SSN.concat(_.left('a'), _.both('b', 2))(), TH.both('ab', 2)) U.deepStrictEqual(await SSN.concat(_.both('a', 1), _.both('b', 2))(), TH.both('ab', 3)) }) describe('getMonad', () => { const M = _.getMonad(S.Monoid) it('map', async () => { const f = (n: number): number => n * 2 U.deepStrictEqual(await M.map(_.right(1), f)(), TH.right(2)) U.deepStrictEqual(await M.map(_.left('a'), f)(), TH.left('a')) U.deepStrictEqual(await M.map(_.both('a', 1), f)(), TH.both('a', 2)) }) it('ap', async () => { const f = (n: number): number => n * 2 U.deepStrictEqual(await M.ap(_.right(f), _.right(1))(), TH.right(2)) }) it('chain', async () => { const f = (n: number) => (n > 2 ? _.both(`c`, n * 3) : n > 1 ? _.right(n * 2) : _.left(`b`)) U.deepStrictEqual(await M.chain(_.right(1), f)(), TH.left('b')) U.deepStrictEqual(await M.chain(_.right(2), f)(), TH.right(4)) U.deepStrictEqual(await M.chain(_.left('a'), f)(), TH.left('a')) U.deepStrictEqual(await M.chain(_.both('a', 1), f)(), TH.left('ab')) U.deepStrictEqual(await M.chain(_.both('a', 2), f)(), TH.both('a', 4)) U.deepStrictEqual(await M.chain(_.both('a', 3), f)(), TH.both('ac', 9)) }) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('right', async () => { const x = await _.right(1)() U.deepStrictEqual(x, TH.right(1)) }) it('left', async () => { const x = await _.left('a')() U.deepStrictEqual(x, TH.left('a')) }) it('both', async () => { const x = await _.both('a', 1)() U.deepStrictEqual(x, TH.both('a', 1)) }) it('rightIO', async () => { const x = await _.rightIO(IO.of(1))() U.deepStrictEqual(x, TH.right(1)) }) it('leftIO', async () => { const x = await _.leftIO(IO.of('a'))() U.deepStrictEqual(x, TH.left('a')) }) it('rightTask', async () => { const x = await _.rightTask(T.of(1))() U.deepStrictEqual(x, TH.right(1)) }) it('leftTask', async () => { const x = await _.leftTask(T.of('a'))() U.deepStrictEqual(x, TH.left('a')) }) // ------------------------------------------------------------------------------------- // destructors // ------------------------------------------------------------------------------------- it('fold', async () => { const f = _.fold( (e) => T.of(`left ${e}`), (a) => T.of(`right ${a}`), (e, a) => T.of(`both ${e} ${a}`) ) U.deepStrictEqual(await pipe(_.right(1), f)(), 'right 1') U.deepStrictEqual(await pipe(_.left('a'), f)(), 'left a') U.deepStrictEqual(await pipe(_.both('a', 1), f)(), 'both a 1') }) it('swap', async () => { U.deepStrictEqual(await _.swap(_.right(1))(), TH.left(1)) U.deepStrictEqual(await _.swap(_.left('a'))(), TH.right('a')) U.deepStrictEqual(await _.swap(_.both('a', 1))(), TH.both(1, 'a')) }) it('toTuple', async () => { const f = _.toTuple('b', 2) U.deepStrictEqual(await f(_.right(1))(), ['b', 1]) U.deepStrictEqual(await f(_.left('a'))(), ['a', 2]) U.deepStrictEqual(await f(_.both('a', 1))(), ['a', 1]) }) it('match', async () => { const match = _.match( (e) => `left ${e}`, (a) => `right ${a}`, (e, a) => `both ${e} ${a}` ) U.deepStrictEqual(await pipe(_.right(1), match)(), 'right 1') U.deepStrictEqual(await pipe(_.left('a'), match)(), 'left a') U.deepStrictEqual(await pipe(_.both('a', 1), match)(), 'both a 1') }) it('matchE', async () => { const matchE = _.matchE( (e) => T.of(`left ${e}`), (a) => T.of(`right ${a}`), (e, a) => T.of(`both ${e} ${a}`) ) U.deepStrictEqual(await pipe(_.right(1), matchE)(), 'right 1') U.deepStrictEqual(await pipe(_.left('a'), matchE)(), 'left a') U.deepStrictEqual(await pipe(_.both('a', 1), matchE)(), 'both a 1') }) it('fromTheseK', async () => { const g = _.fromTheseK((n: number) => (n > 0 ? TH.right(n) : n === 0 ? TH.both('zero', n) : TH.left('negative'))) U.deepStrictEqual(await g(-1)(), TH.left('negative')) U.deepStrictEqual(await g(0)(), TH.both('zero', 0)) U.deepStrictEqual(await g(1)(), TH.right(1)) }) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- it('traverseReadonlyArrayWithIndex', async () => { const f = (i: number, n: number) => (n > 0 ? _.right(n + i) : n === 0 ? _.both('a', 0) : _.left(String(n))) const standard = RA.traverseWithIndex(_.getApplicative(T.ApplicativePar, S.Semigroup))(f) const optimized = _.traverseReadonlyArrayWithIndex(S.Semigroup)(f) const assert = async (input: ReadonlyArray) => { U.deepStrictEqual(await standard(input)(), await optimized(input)()) } await assert([1, 2, 3]) await assert([0, 2, 3]) await assert([1, 0, 3]) await assert([0, 0, 3]) await assert([-1, 2, 3]) await assert([1, -2, 3]) await assert(RA.empty) }) it('traverseReadonlyArrayWithIndexSeq', async () => { const f = (i: number, n: number) => (n > 0 ? _.right(n + i) : n === 0 ? _.both('a', 0) : _.left(String(n))) const standard = RA.traverseWithIndex(_.getApplicative(T.ApplicativeSeq, S.Semigroup))(f) const optimized = _.traverseReadonlyArrayWithIndexSeq(S.Semigroup)(f) const assert = async (input: ReadonlyArray) => { U.deepStrictEqual(await standard(input)(), await optimized(input)()) } await assert([1, 2, 3]) await assert([0, 2, 3]) await assert([1, 0, 3]) await assert([0, 0, 3]) await assert([-1, 2, 3]) await assert([1, -2, 3]) await assert(RA.empty) }) it('sequenceReadonlyArray', async () => { const log: Array = [] const right = (n: number): _.TaskThese => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskThese => _.leftIO(() => { log.push(s) return s }) const f = _.traverseReadonlyArrayWithIndex(S.Semigroup) U.deepStrictEqual(await pipe([right(1), right(2)], f(SK))(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], f(SK))(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], f(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceReadonlyArraySeq', async () => { const log: Array = [] const right = (n: number): _.TaskThese => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskThese => _.leftIO(() => { log.push(s) return s }) const f = _.traverseReadonlyArrayWithIndexSeq(S.Semigroup) U.deepStrictEqual(await pipe([right(1), right(2)], f(SK))(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], f(SK))(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], f(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) }) ================================================ FILE: test/These.ts ================================================ import * as Apply from '../src/Apply' import { identity, pipe } from '../src/function' import * as N from '../src/number' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as S from '../src/string' import * as _ from '../src/These' import * as U from './util' describe('These', () => { describe('pipeables', () => { it('map', () => { const f = _.map(U.double) U.deepStrictEqual(pipe(_.left(2), f), _.left(2)) U.deepStrictEqual(pipe(_.right(2), f), _.right(4)) U.deepStrictEqual(pipe(_.both(1, 2), f), _.both(1, 4)) }) it('bimap', () => { const f = _.bimap(S.size, U.double) U.deepStrictEqual(pipe(_.left('a'), f), _.left(1)) U.deepStrictEqual(pipe(_.right(2), f), _.right(4)) U.deepStrictEqual(pipe(_.both('aaa', 1), f), _.both(3, 2)) }) it('mapLeft', () => { const f = _.mapLeft(S.size) U.deepStrictEqual(pipe(_.left('a'), f), _.left(1)) U.deepStrictEqual(pipe(_.right(2), f), _.right(2)) U.deepStrictEqual(pipe(_.both('aaa', 1), f), _.both(3, 1)) }) it('reduce', () => { U.deepStrictEqual( pipe( _.left('b'), _.reduce('a', (b, a) => b + a) ), 'a' ) U.deepStrictEqual( pipe( _.right('b'), _.reduce('a', (b, a) => b + a) ), 'ab' ) U.deepStrictEqual( pipe( _.both(1, 'b'), _.reduce('a', (b, a) => b + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe(_.right('a'), _.foldMap(S.Monoid)(identity)), 'a') U.deepStrictEqual(pipe(_.left(1), _.foldMap(S.Monoid)(identity)), '') U.deepStrictEqual(pipe(_.both(1, 'a'), _.foldMap(S.Monoid)(identity)), 'a') }) it('reduceRight', () => { const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(_.right('a'), _.reduceRight('', f)), 'a') U.deepStrictEqual(pipe(_.left(1), _.reduceRight('', f)), '') U.deepStrictEqual(pipe(_.both(1, 'a'), _.reduceRight('', f)), 'a') }) it('traverse', () => { const traverse = _.traverse(O.Applicative)((n: number) => (n > 1 ? O.some(n) : O.none)) U.deepStrictEqual(pipe(_.left('a'), traverse), O.some(_.left('a'))) U.deepStrictEqual(pipe(_.right(2), traverse), O.some(_.right(2))) U.deepStrictEqual(pipe(_.right(1), traverse), O.none) U.deepStrictEqual(pipe(_.both('a', 2), traverse), O.some(_.both('a', 2))) U.deepStrictEqual( pipe( _.both('a', 1), _.traverse(O.Applicative)((n) => (n >= 2 ? O.some(n) : O.none)) ), O.none ) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) U.deepStrictEqual(sequence(_.left('a')), O.some(_.left('a'))) U.deepStrictEqual(sequence(_.right(O.some(1))), O.some(_.right(1))) U.deepStrictEqual(sequence(_.right(O.none)), O.none) U.deepStrictEqual(sequence(_.both('a', O.some(1))), O.some(_.both('a', 1))) U.deepStrictEqual(sequence(_.both('a', O.none)), O.none) }) }) it('ap', () => { const M = _.getApply(S.Semigroup) const sequenceT = Apply.sequenceT(M) U.deepStrictEqual(sequenceT(_.right(1), _.right(2)), _.right([1, 2])) U.deepStrictEqual(sequenceT(_.right(1), _.left('b')), _.left('b')) U.deepStrictEqual(sequenceT(_.right(1), _.both('b', 2)), _.both('b', [1, 2])) U.deepStrictEqual(sequenceT(_.left('a'), _.right(2)), _.left('a')) U.deepStrictEqual(sequenceT(_.left('a'), _.left('b')), _.left('ab')) U.deepStrictEqual(sequenceT(_.left('a'), _.both('b', 2)), _.left('ab')) U.deepStrictEqual(sequenceT(_.both('a', 1), _.right(2)), _.both('a', [1, 2])) U.deepStrictEqual(sequenceT(_.both('a', 1), _.left('b')), _.left('ab')) U.deepStrictEqual(sequenceT(_.both('a', 1), _.both('b', 2)), _.both('ab', [1, 2])) }) it('chain', () => { const M = _.getChain(S.Semigroup) const f = (n: number) => (n >= 2 ? (n <= 5 ? _.right(n * 2) : _.both('bar', n)) : _.left('bar')) U.deepStrictEqual(M.chain(_.left('foo'), f), _.left('foo')) U.deepStrictEqual(M.chain(_.right(2), f), _.right(4)) U.deepStrictEqual(M.chain(_.right(1), f), _.left('bar')) U.deepStrictEqual(M.chain(_.right(6), f), _.both('bar', 6)) U.deepStrictEqual(M.chain(_.both('foo', 2), f), _.both('foo', 4)) U.deepStrictEqual(M.chain(_.both('foo', 1), f), _.left('foobar')) U.deepStrictEqual(M.chain(_.both('foo', 6), f), _.both('foobar', 6)) }) it('getApplicative', () => { const A = _.getApplicative(S.Semigroup) U.deepStrictEqual(A.of(1), _.right(1)) }) it('getMonad', () => { const M = _.getMonad(S.Semigroup) U.deepStrictEqual(M.of(1), _.right(1)) }) it('getEq', () => { const { equals } = _.getEq(N.Eq, N.Eq) U.deepStrictEqual(equals(_.left(2), _.left(2)), true) U.deepStrictEqual(equals(_.left(2), _.left(3)), false) U.deepStrictEqual(equals(_.left(3), _.left(2)), false) U.deepStrictEqual(equals(_.left(2), _.right(2)), false) U.deepStrictEqual(equals(_.left(2), _.both(2, 2)), false) U.deepStrictEqual(equals(_.right(2), _.right(2)), true) U.deepStrictEqual(equals(_.right(2), _.right(3)), false) U.deepStrictEqual(equals(_.right(3), _.right(2)), false) U.deepStrictEqual(equals(_.right(2), _.both(2, 2)), false) U.deepStrictEqual(equals(_.both(2, 2), _.both(2, 2)), true) U.deepStrictEqual(equals(_.both(2, 3), _.both(3, 2)), false) }) it('getSemigroup', () => { const { concat } = _.getSemigroup(S.Semigroup, N.SemigroupSum) U.deepStrictEqual(concat(_.left('a'), _.left('b')), _.left('ab')) U.deepStrictEqual(concat(_.left('a'), _.right(2)), _.both('a', 2)) U.deepStrictEqual(concat(_.right(2), _.left('a')), _.both('a', 2)) U.deepStrictEqual(concat(_.left('a'), _.both('b', 2)), _.both('ab', 2)) U.deepStrictEqual(concat(_.both('b', 2), _.left('a')), _.both('ba', 2)) U.deepStrictEqual(concat(_.right(3), _.right(2)), _.right(5)) U.deepStrictEqual(concat(_.right(3), _.both('b', 2)), _.both('b', 5)) U.deepStrictEqual(concat(_.both('b', 2), _.right(3)), _.both('b', 5)) U.deepStrictEqual(concat(_.both('a', 3), _.both('b', 2)), _.both('ab', 5)) }) it('fold', () => { const f = (s: string, n: number) => S.size(s) + U.double(n) const fold = _.fold(S.size, U.double, f) U.deepStrictEqual(fold(_.left('foo')), 3) U.deepStrictEqual(fold(_.right(1)), 2) U.deepStrictEqual(fold(_.both('foo', 1)), 5) }) it('toTuple', () => { U.deepStrictEqual(pipe(_.left('b'), _.toTuple('a', 1)), ['b', 1]) U.deepStrictEqual(pipe(_.right(2), _.toTuple('a', 1)), ['a', 2]) U.deepStrictEqual(pipe(_.both('b', 2), _.toTuple('a', 1)), ['b', 2]) }) it('getLeft', () => { U.deepStrictEqual(_.getLeft(_.left('a')), O.some('a')) U.deepStrictEqual(_.getLeft(_.right(1)), O.none) U.deepStrictEqual(_.getLeft(_.both('a', 1)), O.some('a')) }) it('getRight', () => { U.deepStrictEqual(_.getRight(_.left('a')), O.none) U.deepStrictEqual(_.getRight(_.right(1)), O.some(1)) U.deepStrictEqual(_.getRight(_.both('a', 1)), O.some(1)) }) it('leftOrBoth', () => { U.deepStrictEqual(_.leftOrBoth('a')(O.none), _.left('a')) U.deepStrictEqual(_.leftOrBoth('a')(O.some(1)), _.both('a', 1)) }) it('rightOrBoth', () => { U.deepStrictEqual(_.rightOrBoth(1)(O.none), _.right(1)) U.deepStrictEqual(_.rightOrBoth(1)(O.some('a')), _.both('a', 1)) }) it('getLeftOnly', () => { U.deepStrictEqual(_.getLeftOnly(_.left('a')), O.some('a')) U.deepStrictEqual(_.getLeftOnly(_.right(1)), O.none) U.deepStrictEqual(_.getLeftOnly(_.both('a', 1)), O.none) }) it('getRightOnly', () => { U.deepStrictEqual(_.getRightOnly(_.left('a')), O.none) U.deepStrictEqual(_.getRightOnly(_.right(1)), O.some(1)) U.deepStrictEqual(_.getRightOnly(_.both('a', 1)), O.none) }) it('fromOptions', () => { U.deepStrictEqual(_.fromOptions(O.none, O.none), O.none) U.deepStrictEqual(_.fromOptions(O.some('a'), O.none), O.some(_.left('a'))) U.deepStrictEqual(_.fromOptions(O.none, O.some(1)), O.some(_.right(1))) U.deepStrictEqual(_.fromOptions(O.some('a'), O.some(1)), O.some(_.both('a', 1))) }) it('isLeft', () => { U.deepStrictEqual(_.isLeft(_.left(1)), true) U.deepStrictEqual(_.isLeft(_.right(1)), false) U.deepStrictEqual(_.isLeft(_.both('1', 1)), false) }) it('isRight', () => { U.deepStrictEqual(_.isRight(_.left(1)), false) U.deepStrictEqual(_.isRight(_.right(1)), true) U.deepStrictEqual(_.isRight(_.both('1', 1)), false) }) it('isBoth', () => { U.deepStrictEqual(_.isBoth(_.left(1)), false) U.deepStrictEqual(_.isBoth(_.right(1)), false) U.deepStrictEqual(_.isBoth(_.both('1', 1)), true) }) it('getShow', () => { const Sh = _.getShow(S.Show, S.Show) U.deepStrictEqual(Sh.show(_.left('a')), `left("a")`) U.deepStrictEqual(Sh.show(_.right('a')), `right("a")`) U.deepStrictEqual(Sh.show(_.both('a', 'b')), `both("a", "b")`) }) it('swap', () => { U.deepStrictEqual(_.swap(_.left('a')), _.right('a')) U.deepStrictEqual(_.swap(_.right('a')), _.left('a')) U.deepStrictEqual(_.swap(_.both('a', 1)), _.both(1, 'a')) }) // ------------------------------------------------------------------------------------- // array utils // ------------------------------------------------------------------------------------- it('traverseReadonlyArrayWithIndex', () => { const f = (i: number, n: number) => (n > 0 ? _.right(n + i) : n === 0 ? _.both('a', 0) : _.left(String(n))) const standard = RA.traverseWithIndex(_.getApplicative(S.Semigroup))(f) const optimized = _.traverseReadonlyArrayWithIndex(S.Semigroup)(f) const assert = (input: ReadonlyArray) => { U.deepStrictEqual(standard(input), optimized(input)) } assert([1, 2, 3]) assert([0, 2, 3]) assert([1, 0, 3]) assert([0, 0, 3]) assert([-1, 2, 3]) assert([1, -2, 3]) assert(RA.empty) }) it('exists', () => { const gt2 = _.exists((n: number) => n > 2) U.deepStrictEqual(gt2(_.left('a')), false) U.deepStrictEqual(gt2(_.right(1)), false) U.deepStrictEqual(gt2(_.right(3)), true) U.deepStrictEqual(gt2(_.both('a', 1)), false) U.deepStrictEqual(gt2(_.both('a', 3)), true) }) it('elem', () => { U.deepStrictEqual(_.elem(N.Eq)(2)(_.left('a')), false) U.deepStrictEqual(_.elem(N.Eq)(2)(_.right(2)), true) U.deepStrictEqual(_.elem(N.Eq)(1)(_.right(2)), false) U.deepStrictEqual(_.elem(N.Eq)(2)(_.both('a', 2)), true) U.deepStrictEqual(_.elem(N.Eq)(1)(_.both('a', 2)), false) }) }) ================================================ FILE: test/Traced.ts ================================================ import * as B from '../src/boolean' import { pipe } from '../src/function' import { Monoid, struct } from '../src/Monoid' import * as _ from '../src/Traced' import * as U from './util' // Adapted from https://chshersh.github.io/posts/2019-03-25-comonadic-builders interface Settings { readonly settingsHasLibrary: boolean readonly settingsGitHub: boolean readonly settingsTravis: boolean } const M: Monoid = struct({ settingsHasLibrary: B.MonoidAny, settingsGitHub: B.MonoidAny, settingsTravis: B.MonoidAny }) const C = _.getComonad(M) interface Project { readonly projectName: string readonly projectHasLibrary: boolean readonly projectGitHub: boolean readonly projectTravis: boolean } interface ProjectBuilder extends _.Traced {} const buildProject = (projectName: string): ProjectBuilder => (settings) => ({ projectName, projectHasLibrary: settings.settingsHasLibrary, projectGitHub: settings.settingsGitHub, projectTravis: settings.settingsTravis }) const hasLibraryB = (wa: ProjectBuilder): Project => { const p = { ...M.empty, settingsHasLibrary: true } return wa(p) } const gitHubB = (wa: ProjectBuilder): Project => { const p = { ...M.empty, settingsGitHub: true } return wa(p) } const getProjectName = (project: Project): string => project.projectName describe('Traced', () => { describe('pipeables', () => { it('map', () => { const wa = buildProject('myproject') U.deepStrictEqual(pipe(wa, _.map(getProjectName))(M.empty), 'myproject') }) }) it('getComonad', () => { const wa = buildProject('myproject') U.deepStrictEqual(C.extract(wa), { projectName: 'myproject', projectHasLibrary: false, projectGitHub: false, projectTravis: false }) U.deepStrictEqual(C.extract(C.extend(wa, hasLibraryB)), { projectName: 'myproject', projectHasLibrary: true, projectGitHub: false, projectTravis: false }) }) it('tracks', () => { const travisB = _.tracks(M, (project: Project): Settings => ({ ...M.empty, settingsTravis: project.projectGitHub })) U.deepStrictEqual(C.extract(C.extend(buildProject('travis'), travisB)), { projectName: 'travis', projectHasLibrary: false, projectGitHub: false, projectTravis: false }) U.deepStrictEqual(C.extract(C.extend(C.extend(buildProject('github-travis'), gitHubB), travisB)), { projectName: 'github-travis', projectHasLibrary: false, projectGitHub: true, projectTravis: true }) }) it('listen', () => { U.deepStrictEqual(C.extract(_.listen(buildProject('myproject'))), [ { projectName: 'myproject', projectHasLibrary: false, projectGitHub: false, projectTravis: false }, { settingsHasLibrary: false, settingsGitHub: false, settingsTravis: false } ]) }) it('listens', () => { U.deepStrictEqual( C.extract( pipe( buildProject('myproject'), _.listens((settings) => settings.settingsTravis) ) ), [ { projectName: 'myproject', projectHasLibrary: false, projectGitHub: false, projectTravis: false }, false ] ) }) it('censor', () => { U.deepStrictEqual( C.extract( pipe( buildProject('myproject'), _.censor((settings) => ({ ...settings, settingsHasLibrary: !settings.settingsHasLibrary })) ) ), { projectName: 'myproject', projectHasLibrary: true, projectGitHub: false, projectTravis: false } ) }) }) ================================================ FILE: test/Traversable.ts ================================================ import * as E from '../src/Either' import { identity, pipe } from '../src/function' import * as O from '../src/Option' import * as RA from '../src/ReadonlyArray' import * as _ from '../src/Traversable' import * as U from './util' export const ArrayOptionURI = 'ArrayOption' export type ArrayOptionURI = typeof ArrayOptionURI describe('Traversable', () => { it('getTraversableComposition', () => { const T = _.getTraversableComposition(RA.Traversable, O.Traversable) U.deepStrictEqual( T.map([O.some(1), O.some(2), O.none], (n) => n * 2), [O.some(2), O.some(4), O.none] ) U.deepStrictEqual( T.traverse(O.Applicative)([O.some(1), O.some(2)], (n: number) => (n <= 2 ? O.some(n * 2) : O.none)), O.some([O.some(2), O.some(4)]) ) U.deepStrictEqual( T.traverse(O.Applicative)([O.some(1), O.some(3)], (n: number) => (n <= 2 ? O.some(n * 2) : O.none)), O.none ) U.deepStrictEqual(T.sequence(O.Applicative)([O.some(O.some(1)), O.some(O.some(2))]), O.some([O.some(1), O.some(2)])) U.deepStrictEqual(T.sequence(O.Applicative)([O.some(O.some(1)), O.none]), O.some([O.some(1), O.none])) U.deepStrictEqual(T.sequence(O.Applicative)([O.some(O.some(1)), O.some(O.none)]), O.none) }) it('traverse', () => { const traverse = _.traverse(RA.Traversable, RA.Traversable)(E.Applicative) U.deepStrictEqual(pipe([[E.right(1)]], traverse(identity)), E.right([[1]])) }) it('sequence', () => { const sequence = _.sequence(RA.Traversable, RA.Traversable)(E.Applicative) U.deepStrictEqual(pipe([[E.right(1)]], sequence), E.right([[1]])) }) }) ================================================ FILE: test/Tree.ts ================================================ import * as Eq from '../src/Eq' import { identity, pipe } from '../src/function' import * as N from '../src/number' import * as O from '../src/Option' import * as S from '../src/string' import * as T from '../src/Task' import * as _ from '../src/Tree' import * as U from './util' describe('Tree', () => { describe('pipeables', () => { it('traverse', () => { const fa = _.make('a', [_.make('b'), _.make('c')]) U.deepStrictEqual(pipe(fa, _.traverse(O.Applicative)(O.some)), O.some(fa)) }) it('sequence', () => { U.deepStrictEqual( _.sequence(O.Applicative)(_.make(O.some('a'), [_.make(O.some('b')), _.make(O.some('c'))])), O.some(_.make('a', [_.make('b'), _.make('c')])) ) }) }) it('map', () => { const fa = _.make(1, [_.make(2), _.make(3)]) const expected = _.make(2, [_.make(4), _.make(6)]) U.deepStrictEqual(pipe(fa, _.map(U.double)), expected) }) it('ap', () => { const fab = _.of(U.double) const fa = _.make(1, [_.make(2), _.make(3)]) const expected = _.make(2, [_.make(4), _.make(6)]) U.deepStrictEqual(pipe(fab, _.ap(fa)), expected) }) it('apFirst', () => { U.deepStrictEqual(pipe(_.make('a'), _.apFirst(_.make('b'))), _.make('a')) }) it('apSecond', () => { U.deepStrictEqual(pipe(_.make('a'), _.apSecond(_.make('b'))), _.make('b')) }) it('flatMap', () => { const f = (n: number) => _.of(n * 2) const fa = _.make(1, [_.make(2), _.make(3)]) const expected = _.make(2, [_.make(4), _.make(6)]) U.deepStrictEqual(pipe(fa, _.flatMap(f)), expected) U.deepStrictEqual(_.flatMap(fa, f), expected) }) it('chain', () => { const f = (n: number) => _.of(n * 2) const fa = _.make(1, [_.make(2), _.make(3)]) const expected = _.make(2, [_.make(4), _.make(6)]) U.deepStrictEqual(pipe(fa, _.chain(f)), expected) }) it('chainFirst', () => { const f = (n: number) => _.of(n * 2) const fa = _.make(1, [_.make(2), _.make(3)]) U.deepStrictEqual(pipe(fa, _.chainFirst(f)), fa) }) it('flatten', () => { U.deepStrictEqual(pipe(_.make(_.make('a')), _.flatten), _.make('a')) }) it('duplicate', () => { U.deepStrictEqual(pipe(_.make('a'), _.duplicate), _.make(_.make('a'))) }) it('extract', () => { const fa = _.make(1, [_.make(2), _.make(3)]) U.deepStrictEqual(pipe(fa, _.extract), 1) }) it('extend', () => { const fa = _.make('a', [_.make('foo'), _.make('b')]) const f = (fa: _.Tree) => fa.value.length + fa.forest.length const expected = _.make(3, [_.make(3), _.make(1)]) U.deepStrictEqual(pipe(fa, _.extend(f)), expected) }) it('reduce', () => { const fa = _.make('a', [_.make('b'), _.make('c')]) U.deepStrictEqual( pipe( fa, _.reduce('', (b, a) => b + a) ), 'abc' ) }) it('foldMap', () => { const x = _.make('a', [_.make('b'), _.make('c')]) U.deepStrictEqual(pipe(x, _.foldMap(S.Monoid)(identity)), 'abc') }) it('reduceRight', () => { const x = _.make('a', [_.make('b'), _.make('c')]) const f = (a: string, acc: string) => acc + a U.deepStrictEqual(pipe(x, _.reduceRight('', f)), 'cba') }) it('drawTree', () => { const tree = _.make('a') U.deepStrictEqual(_.drawTree(tree), 'a') const tree1 = _.make('a', [_.make('b'), _.make('c'), _.make('d', [_.make('e'), _.make('f')]), _.make('g')]) U.deepStrictEqual( _.drawTree(tree1), `a ├─ b ├─ c ├─ d │ ├─ e │ └─ f └─ g` ) const tree2 = _.make('a', [_.make('b', [_.make('c')])]) U.deepStrictEqual( _.drawTree(tree2), `a └─ b └─ c` ) const tree3 = _.make('a', [_.make('b', [_.make('c')]), _.make('d', [_.make('e')])]) U.deepStrictEqual( _.drawTree(tree3), `a ├─ b │ └─ c └─ d └─ e` ) const tree4 = _.make('a', [_.make('b', [_.make('c', [_.make('d')]), _.make('e', [_.make('f')])]), _.make('e')]) U.deepStrictEqual( _.drawTree(tree4), `a ├─ b │ ├─ c │ │ └─ d │ └─ e │ └─ f └─ e` ) }) it('getEq', () => { const S = _.getEq(N.Eq) const x = _.make(1, [_.make(2)]) const y = _.make(2, [_.make(2)]) const z = _.make(1, [_.make(1)]) U.deepStrictEqual(S.equals(x, x), true) U.deepStrictEqual(S.equals(x, y), false) U.deepStrictEqual(S.equals(x, z), false) }) it('unfoldTree', () => { U.deepStrictEqual( _.unfoldTree(1, (b) => [b, b < 3 ? [b + 1, b + 2] : []]), _.make(1, [_.make(2, [_.make(3), _.make(4)]), _.make(3)]) ) }) it('unfoldTreeM', async () => { U.deepStrictEqual( _.unfoldTreeM(O.Monad)(1, (b) => O.some([b, b < 3 ? [b + 1, b + 2] : []])), O.some(_.make(1, [_.make(2, [_.make(3), _.make(4)]), _.make(3)])) ) U.deepStrictEqual( _.unfoldTreeM(O.Monad)(1, (b) => (b < 3 ? O.some([b, [b + 1, b + 2]]) : O.none)), O.none ) U.deepStrictEqual( await _.unfoldTreeM(T.Monad)(1, (b) => T.of([b, b < 3 ? [b + 1, b + 2] : []]))(), _.make(1, [_.make(2, [_.make(3), _.make(4)]), _.make(3)]) ) }) it('getShow', () => { const Sh = _.getShow(S.Show) const t1 = _.make('a') U.deepStrictEqual(Sh.show(t1), `make("a")`) const t2 = _.make('a', [_.make('b'), _.make('c')]) U.deepStrictEqual(Sh.show(t2), `make("a", [make("b"), make("c")])`) }) it('fold', () => { const t = _.make(1, [_.make(2), _.make(3)]) U.deepStrictEqual( _.fold((a: number, bs: ReadonlyArray) => bs.reduce((b, acc) => Math.max(b, acc), a))(t), 3 ) }) it('do notation', () => { U.deepStrictEqual( pipe( _.of(1), _.bindTo('a'), _.bind('b', () => _.of('b')), _.let('c', ({ a, b }) => [a, b]) ), _.make({ a: 1, b: 'b', c: [1, 'b'] }) ) }) it('apS', () => { U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b'))), _.make({ a: 1, b: 'b' })) }) it('elem', () => { interface User { readonly id: number } const S: Eq.Eq = pipe( N.Eq, Eq.contramap((user: User) => user.id) ) const users = _.make({ id: 1 }, [_.make({ id: 1 }, [_.make({ id: 3 }), _.make({ id: 4 })]), _.make({ id: 2 })]) U.deepStrictEqual(_.elem(S)({ id: 1 }, users), true) U.deepStrictEqual(_.elem(S)({ id: 4 }, users), true) U.deepStrictEqual(_.elem(S)({ id: 5 }, users), false) }) it('exists', () => { interface User { readonly id: number } const users = _.make({ id: 1 }, [_.make({ id: 1 }, [_.make({ id: 3 }), _.make({ id: 4 })]), _.make({ id: 2 })]) U.deepStrictEqual(_.exists((user: User) => user.id === 1)(users), true) U.deepStrictEqual(_.exists((user: User) => user.id === 4)(users), true) U.deepStrictEqual(_.exists((user: User) => user.id === 5)(users), false) }) }) ================================================ FILE: test/Tuple.ts ================================================ import * as assert from 'assert' import { getMonoid } from '../src/Array' import { left, right } from '../src/Either' import { identity, pipe } from '../src/function' import * as O from '../src/Option' import * as S from '../src/string' import * as _ from '../src/Tuple' import * as U from './util' describe('Tuple', () => { describe('pipeables', () => { it('compose', () => { U.deepStrictEqual(pipe([true, 2] as [boolean, number], _.compose([1, 'a'])), [true, 'a']) }) it('mapFst', () => { U.deepStrictEqual(pipe([1, 'a'] as [number, string], _.mapFst(U.double)), [2, 'a']) }) it('extract', () => { U.deepStrictEqual(pipe([1, 'a'] as [number, string], _.extract), 1) }) it('extend', () => { const f = (fa: [number, string]): number => _.snd(fa).length + _.fst(fa) U.deepStrictEqual(pipe([1, 'bb'], _.extend(f)), [3, 'bb']) }) it('bimap', () => { U.deepStrictEqual(pipe([1, 'a'], _.bimap(S.size, U.double)), [2, 1]) }) it('mapSnd', () => { U.deepStrictEqual(pipe([1, 'a'] as [number, string], _.mapSnd(S.size)), [1, 1]) }) it('duplicate', () => { U.deepStrictEqual(pipe([1, 'a'] as [number, string], _.duplicate), [[1, 'a'], 'a']) }) it('reduce', () => { U.deepStrictEqual( pipe( ['b', 1] as [string, number], _.reduce('a', (acc, a) => acc + a) ), 'ab' ) }) it('foldMap', () => { U.deepStrictEqual(pipe(['a', 1] as [string, number], _.foldMap(S.Monoid)(identity)), 'a') }) it('reduceRight', () => { U.deepStrictEqual( pipe( ['b', 1] as [string, number], _.reduceRight('a', (acc, a) => acc + a) ), 'ba' ) }) it('traverse', () => { const traverse = _.traverse(O.Applicative)((n: number) => (n > 1 ? O.some(n) : O.none)) assert.deepStrictEqual(traverse([2, 'a']), O.some([2, 'a'])) U.deepStrictEqual(traverse([1, 'a']), O.none) }) it('sequence', () => { const sequence = _.sequence(O.Applicative) assert.deepStrictEqual(sequence([O.some(1), 'a']), O.some([1, 'a'])) U.deepStrictEqual(sequence([O.none, 'a']), O.none) }) }) it('swap', () => { U.deepStrictEqual(_.swap([1, 'a']), ['a', 1]) }) it('getApply', () => { const apply = _.getApply(S.Monoid) U.deepStrictEqual(apply.ap([U.double, 'a'], [1, 'b']), [2, 'ab']) }) it('getApplicative', () => { const applicative = _.getApplicative(S.Monoid) U.deepStrictEqual(applicative.of(1), [1, '']) }) it('getMonad', () => { const monad = _.getMonad(S.Monoid) U.deepStrictEqual( monad.chain([1, 'a'], (a) => [a * 2, 'b']), [2, 'ab'] ) }) it('chainRec', () => { const { chainRec } = _.getChainRec(getMonoid()) function seqReq(upper: number): [number, ReadonlyArray] { return chainRec(1, (init) => [init >= upper ? right(init) : left(init + 1), [init]]) } const xs = _.snd(seqReq(10000)) U.deepStrictEqual(xs.length, 10000) U.deepStrictEqual(xs[0], 1) U.deepStrictEqual(xs[xs.length - 1], 10000) }) }) ================================================ FILE: test/ValidationT.ts ================================================ import * as E from '../src/Either' import * as IO from '../src/IO' import { semigroupString } from '../src/Semigroup' import * as _ from '../src/ValidationT' import * as U from './util' describe('ValidationT', () => { describe('getValidationM', () => { const VT = _.getValidationM(semigroupString, IO.Monad) it('chain', () => { const f = (n: number) => (n > 0 ? IO.of(E.right(n * 2)) : IO.of(E.left('b'))) U.deepStrictEqual(VT.chain(IO.of(E.right(1)), f)(), E.right(2)) U.deepStrictEqual(VT.chain(IO.of(E.right(-1)), f)(), E.left('b')) U.deepStrictEqual(VT.chain(IO.of(E.left('a')), f)(), E.left('a')) }) it('alt', () => { U.deepStrictEqual(VT.alt(IO.of(E.right(1)), () => IO.of(E.right(2)))(), E.right(1)) U.deepStrictEqual(VT.alt(IO.of(E.right(1)), () => IO.of(E.left('b')))(), E.right(1)) U.deepStrictEqual(VT.alt(IO.of(E.left('a')), () => IO.of(E.right(2)))(), E.right(2)) U.deepStrictEqual(VT.alt(IO.of(E.left('a')), () => IO.of(E.left('b')))(), E.left('ab')) }) }) }) ================================================ FILE: test/Witherable.ts ================================================ import { pipe } from '../src/function' import * as RT from '../src/ReaderTask' import * as RA from '../src/ReadonlyArray' import * as RR from '../src/ReadonlyRecord' import * as S from '../src/string' import * as T from '../src/Task' import * as _ from '../src/Witherable' import * as U from './util' describe('Witherable', () => { describe('filterE', () => { const filterERA = _.filterE(RA.Witherable) const filterERR = _.filterE(RR.getWitherable(S.Ord)) it('Applicative1', async () => { const f = (n: number) => T.of(n % 2 === 0) U.deepStrictEqual(await pipe([1, 2], filterERA(T.ApplicativePar)(f))(), [2]) U.deepStrictEqual(await pipe({ a: 1, b: 2 }, filterERR(T.ApplicativePar)(f))(), { b: 2 }) }) it('Applicative2', async () => { const f = (n: number) => RT.of(n % 2 === 0) U.deepStrictEqual(await pipe([1, 2], filterERA(RT.ApplicativePar)(f))({})(), [2]) U.deepStrictEqual(await pipe({ a: 1, b: 2 }, filterERR(RT.ApplicativePar)(f))({})(), { b: 2 }) }) }) }) ================================================ FILE: test/Writer.ts ================================================ import { pipe, tuple } from '../src/function' import * as S from '../src/string' import * as _ from '../src/Writer' import * as U from './util' describe('Writer', () => { describe('pipeables', () => { it('map', () => { const x: _.Writer = () => [1, 'a'] U.deepStrictEqual(pipe(x, _.map(U.double))(), [2, 'a']) }) }) it('evalWriter', () => { U.deepStrictEqual( _.evalWriter(() => [1, 'a']), 1 ) }) it('execWriter', () => { U.deepStrictEqual( _.execWriter(() => [1, 'a']), 'a' ) }) it('evaluate', () => { U.deepStrictEqual(pipe((() => [1, 'a']) as _.Writer, _.evaluate), 1) }) it('execute', () => { U.deepStrictEqual(pipe((() => [1, 'a']) as _.Writer, _.execute), 'a') }) it('tell', () => { U.deepStrictEqual(_.tell(1)(), [undefined, 1]) }) it('listen', () => { U.deepStrictEqual(_.listen(() => [1, 'a'])(), [[1, 'a'], 'a']) }) it('pass', () => { U.deepStrictEqual(_.pass(() => [tuple(1, (w: string) => w + 'b'), 'a'])(), [1, 'ab']) }) it('listens', () => { const fa: _.Writer = () => [1, 'a'] U.deepStrictEqual( pipe( fa, _.listens((w) => w.length) )(), [[1, 1], 'a'] ) }) it('censor', () => { const fa: _.Writer, number> = () => [1, ['a', 'b']] U.deepStrictEqual( pipe( fa, _.censor((w) => w.filter((a) => a !== 'a')) )(), [1, ['b']] ) }) describe('getMonad', () => { const M = _.getMonad(S.Monoid) it('of', () => { U.deepStrictEqual(M.of(1)(), [1, '']) }) it('ap', () => { const fab: _.Writer number> = () => [(n: number) => n * 2, 'a'] const fa: _.Writer = () => [1, 'b'] U.deepStrictEqual(M.ap(fab, fa)(), [2, 'ab']) }) it('chain', () => { const fa: _.Writer = () => [1, 'a'] const f = (n: number): _.Writer => () => [n * 2, 'b'] U.deepStrictEqual(M.chain(fa, f)(), [2, 'ab']) }) }) }) ================================================ FILE: test/boolean.ts ================================================ import * as _ from '../src/boolean' import * as U from './util' describe('boolean', () => { // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('Eq', () => { U.deepStrictEqual(_.Eq.equals(true, true), true) U.deepStrictEqual(_.Eq.equals(false, false), true) U.deepStrictEqual(_.Eq.equals(false, true), false) }) it('Ord', () => { U.deepStrictEqual(_.Ord.compare(false, true), -1) U.deepStrictEqual(_.Ord.compare(true, false), 1) U.deepStrictEqual(_.Ord.compare(true, true), 0) }) it('Show', () => { U.deepStrictEqual(_.Show.show(true), 'true') U.deepStrictEqual(_.Show.show(false), 'false') }) it('BooleanAlgebra', () => { const BA = _.BooleanAlgebra U.deepStrictEqual(BA.implies(true, true), true) U.deepStrictEqual(BA.implies(true, false), false) U.deepStrictEqual(BA.implies(false, true), true) U.deepStrictEqual(BA.implies(false, false), true) U.deepStrictEqual(BA.join(true, true), true) U.deepStrictEqual(BA.join(true, false), true) U.deepStrictEqual(BA.join(false, true), true) U.deepStrictEqual(BA.join(false, false), false) U.deepStrictEqual(BA.meet(true, true), true) U.deepStrictEqual(BA.meet(true, false), false) U.deepStrictEqual(BA.not(true), false) U.deepStrictEqual(BA.not(false), true) U.deepStrictEqual(BA.one, true) U.deepStrictEqual(BA.zero, false) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('fold', () => { U.deepStrictEqual( _.fold( () => 'false', () => 'true' )(true), 'true' ) U.deepStrictEqual( _.fold( () => 'false', () => 'true' )(false), 'false' ) }) }) ================================================ FILE: test/function.ts ================================================ import * as assert from 'assert' import * as B from '../src/boolean' import * as _ from '../src/function' import { concatAll } from '../src/Monoid' import * as N from '../src/number' import * as RA from '../src/ReadonlyArray' import * as U from './util' const f = (n: number) => n + 1 const g = (n: number) => n * 2 describe('function', () => { test('flip', () => { const f1 = (a: number) => (b: string) => a - b.length const f2 = (a: number, b: string) => a - b.length U.deepStrictEqual(_.flip(f1)('aaa')(2), -1) // eslint-disable-next-line deprecation/deprecation U.deepStrictEqual(_.flip(f2)('aaa', 2), -1) }) it('not', () => { const n = _.not(Boolean) U.deepStrictEqual(n(false), true) U.deepStrictEqual(n(1), false) U.deepStrictEqual(n(''), true) }) it('unsafeCoerce', () => { U.deepStrictEqual(_.unsafeCoerce, _.identity) }) it('constTrue', () => { U.deepStrictEqual(_.constTrue(), true) }) it('constFalse', () => { U.deepStrictEqual(_.constFalse(), false) }) it('constNull', () => { U.deepStrictEqual(_.constNull(), null) }) it('constUndefined', () => { U.deepStrictEqual(_.constUndefined(), undefined) }) it('constVoid', () => { U.deepStrictEqual(_.constVoid(), undefined) }) it('increment', () => { U.deepStrictEqual(_.increment(2), 3) }) it('decrement', () => { U.deepStrictEqual(_.decrement(2), 1) }) it('absurd', () => { assert.throws(() => _.absurd(null as any as never)) }) it('flow', () => { U.deepStrictEqual(_.flow(f)(2), 3) U.deepStrictEqual(_.flow(f, g)(2), 6) U.deepStrictEqual(_.flow(f, g, f)(2), 7) U.deepStrictEqual(_.flow(f, g, f, g)(2), 14) U.deepStrictEqual(_.flow(f, g, f, g, f)(2), 15) U.deepStrictEqual(_.flow(f, g, f, g, f, g)(2), 30) U.deepStrictEqual(_.flow(f, g, f, g, f, g, f)(2), 31) U.deepStrictEqual(_.flow(f, g, f, g, f, g, f, g)(2), 62) U.deepStrictEqual(_.flow(f, g, f, g, f, g, f, g, f)(2), 63) // this is just to satisfy noImplicitReturns and 100% coverage U.deepStrictEqual((_.flow as any)(...[f, g, f, g, f, g, f, g, f, g]), undefined) }) it('tupled', () => { const f1 = (a: number): number => a * 2 const f2 = (a: number, b: number): number => a + b const u1 = _.tupled(f1) const u2 = _.tupled(f2) U.deepStrictEqual(u1([1]), 2) U.deepStrictEqual(u2([1, 2]), 3) }) it('untupled', () => { const f1 = (a: readonly [number]): number => a[0] * 2 const f2 = (a: readonly [number, number]): number => a[0] + a[1] const u1 = _.untupled(f1) const u2 = _.untupled(f2) U.deepStrictEqual(u1(1), 2) U.deepStrictEqual(u2(1, 2), 3) }) it('pipe', () => { const f = (n: number) => n + 1 const g = (n: number) => n * 2 U.deepStrictEqual(_.pipe(2), 2) U.deepStrictEqual(_.pipe(2, f), 3) U.deepStrictEqual(_.pipe(2, f, g), 6) U.deepStrictEqual(_.pipe(2, f, g, f), 7) U.deepStrictEqual(_.pipe(2, f, g, f, g), 14) U.deepStrictEqual(_.pipe(2, f, g, f, g, f), 15) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g), 30) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f), 31) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g), 62) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f), 63) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g), 126) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f), 127) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g), 254) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f), 255) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g), 510) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f), 511) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g), 1022) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f), 1023) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g), 2046) U.deepStrictEqual(_.pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f), 2047) U.deepStrictEqual((_.pipe as any)(...[2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g]), 4094) }) it('getBooleanAlgebra', () => { const BA = _.getBooleanAlgebra(B.BooleanAlgebra)() const f = (n: number) => n >= 0 const g = (n: number) => n < 2 U.deepStrictEqual(BA.implies(f, g)(1), true) U.deepStrictEqual(BA.implies(f, g)(-1), true) U.deepStrictEqual(BA.join(f, g)(1), true) U.deepStrictEqual(BA.join(f, g)(-1), true) U.deepStrictEqual(BA.meet(f, g)(1), true) U.deepStrictEqual(BA.meet(f, g)(-1), false) U.deepStrictEqual(BA.not(f)(1), false) U.deepStrictEqual(BA.not(f)(-1), true) U.deepStrictEqual(BA.one(1), true) U.deepStrictEqual(BA.one(-1), true) U.deepStrictEqual(BA.zero(1), false) U.deepStrictEqual(BA.zero(-1), false) }) it('getMonoid', () => { const getPredicateMonoidAll = _.getMonoid(B.MonoidAll) const getPredicateMonoidAny = _.getMonoid(B.MonoidAny) const isLessThan10 = (n: number) => n <= 10 const isEven = (n: number) => n % 2 === 0 U.deepStrictEqual( _.pipe([1, 2, 3, 40], RA.filter(concatAll(getPredicateMonoidAll())([isLessThan10, isEven]))), [2] ) U.deepStrictEqual( _.pipe([1, 2, 3, 40, 41], RA.filter(concatAll(getPredicateMonoidAny())([isLessThan10, isEven]))), [1, 2, 3, 40] ) }) it('getSemiring', () => { const S = _.getSemiring(N.Field) const f1 = (s: string): number => s.length const f2 = (s: string): number => s.indexOf('a') U.deepStrictEqual(S.add(f1, f2)('foo'), 2) U.deepStrictEqual(S.add(f1, f2)('fooa'), 7) U.deepStrictEqual(S.zero(''), 0) U.deepStrictEqual(S.one(''), 1) U.deepStrictEqual(S.mul(f1, f2)('foo'), -3) U.deepStrictEqual(S.mul(f1, f2)('fooa'), 12) }) it('getRing', () => { const R = _.getRing(N.Field) const f1 = (s: string): number => s.length const f2 = (s: string): number => s.indexOf('a') U.deepStrictEqual(R.sub(f1, f2)('foo'), 4) U.deepStrictEqual(R.sub(f1, f2)('fooa'), 1) }) it('getEndomorphismMonoid', () => { const M = _.getEndomorphismMonoid() const f = M.concat(_.increment, U.double) U.deepStrictEqual(f(3), 8) }) it('apply', () => { U.deepStrictEqual(_.pipe(U.double, _.apply(1)), 2) }) }) ================================================ FILE: test/index.ts ================================================ import * as assert from 'assert' import * as glob from 'glob' import * as path from 'path' import * as _ from '../src' const getExportName = (name: string): string => { if (name === 'HKT' || name === 'IO') { return name.toLowerCase() } if (name === 'IOEither') { return 'ioEither' } if (name === 'IOOption') { return 'ioOption' } if (name === 'IORef') { return 'ioRef' } return name.substring(0, 1).toLowerCase() + name.substring(1) } function getModuleNames(): ReadonlyArray { return glob .sync('./src/**/*.ts') .map((file) => path.parse(file).name) .filter((name) => name !== 'internal') } describe('index', () => { it('check exported modules', () => { const moduleNames = getModuleNames() moduleNames.forEach((name) => { if (name !== 'index') { const exportName = getExportName(name) assert.deepStrictEqual( // tslint:disable-next-line: strict-type-predicates (_ as Record)[exportName] !== undefined, true, `The "${name}" module is not exported in src/index.ts as ${exportName}` ) } }) }) }) ================================================ FILE: test/number.ts ================================================ import * as _ from '../src/number' import * as U from './util' describe('string', () => { it('Ord', () => { U.deepStrictEqual(_.Ord.compare(1, 2), -1) U.deepStrictEqual(_.Ord.compare(2, 1), 1) U.deepStrictEqual(_.Ord.compare(2, 2), 0) }) it('Field', () => { U.deepStrictEqual(_.Field.degree(0), 1) U.deepStrictEqual(_.Field.degree(1), 1) U.deepStrictEqual(_.Field.degree(2), 1) }) it('Show', () => { U.deepStrictEqual(_.Show.show(1), '1') }) it('SemigroupProduct', () => { U.deepStrictEqual(_.SemigroupProduct.concat(2, 3), 6) }) it('MagmaSub', () => { U.deepStrictEqual(_.MagmaSub.concat(2, 3), -1) }) }) ================================================ FILE: test/pipeable.ts ================================================ import * as assert from 'assert' import * as C from '../src/Const' import * as E from '../src/Either' import { pipe } from '../src/function' import { fold } from '../src/Monoid' import * as N from '../src/number' import * as O from '../src/Option' import { pipeable } from '../src/pipeable' import * as R from '../src/Reader' import * as RA from '../src/ReadonlyArray' import { separated } from '../src/Separated' import * as U from './util' describe('pipeable', () => { it('{}', () => { const r = pipeable<'{}', {}>({ URI: '{}' }) U.deepStrictEqual(r, {}) }) it('Functor', () => { const { map } = pipeable(RA.Functor) U.deepStrictEqual(map((n: number) => n * 2)([1, 2, 3]), [2, 4, 6]) }) it('Contravariant', () => { const { contramap } = pipeable(C.Contravariant) U.deepStrictEqual(contramap((s: string) => s.length * 2)(C.make(1)), 1) }) it('FunctorWithIndex', () => { const { mapWithIndex } = pipeable(RA.FunctorWithIndex) U.deepStrictEqual(mapWithIndex((i, n: number) => n * 2 + i)([1, 2, 3]), [2, 5, 8]) }) it('Apply', () => { const { ap, apFirst, apSecond } = pipeable(RA.Applicative) U.deepStrictEqual(ap([1, 2, 3])([(n) => n * 2]), [2, 4, 6]) U.deepStrictEqual(apFirst([2])([1]), [1]) U.deepStrictEqual(apSecond([2])([1]), [2]) }) it('Chain', () => { const { chain, chainFirst, flatten } = pipeable(RA.Monad) U.deepStrictEqual(chain((n: number) => [n * 2])([1, 2, 3]), [2, 4, 6]) U.deepStrictEqual(chainFirst((n: number) => [n * 2])([1, 2, 3]), [1, 2, 3]) U.deepStrictEqual(flatten([[1], [2], [3]]), [1, 2, 3]) }) it('Bifunctor', () => { const { bimap, mapLeft } = pipeable(E.Bifunctor) U.deepStrictEqual( bimap( (s: string) => s.length, (n: number) => n * 2 )(E.right(1)), E.right(2) ) U.deepStrictEqual( bimap( (s: string) => s.length, (n: number) => n * 2 )(E.left('aa')), E.left(2) ) U.deepStrictEqual(mapLeft((s: string) => s.length)(E.right(1)), E.right(1)) U.deepStrictEqual(mapLeft((s: string) => s.length)(E.left('aa')), E.left(2)) }) it('Extend', () => { const { extend, duplicate } = pipeable(RA.Extend) U.deepStrictEqual(extend((as: ReadonlyArray) => fold(N.MonoidSum)(as))([1, 2, 3]), [6, 5, 3]) U.deepStrictEqual(duplicate([1, 2, 3]), [[1, 2, 3], [2, 3], [3]]) }) it('Foldable', () => { const { reduce, foldMap, reduceRight } = pipeable(RA.Foldable) U.deepStrictEqual(reduce(0, (acc, n: number) => acc + n)([1, 2, 3]), 6) U.deepStrictEqual(foldMap(N.MonoidSum)((n: number) => n)([1, 2, 3]), 6) U.deepStrictEqual(reduceRight(0, (n: number, acc) => -acc + n)([1, 2, 3]), 2) }) it('FoldableWithIndex', () => { const { reduceWithIndex, foldMapWithIndex, reduceRightWithIndex } = pipeable(RA.FoldableWithIndex) U.deepStrictEqual(reduceWithIndex(0, (i, acc, n: number) => acc + n + i)([1, 2, 3]), 9) U.deepStrictEqual(foldMapWithIndex(N.MonoidSum)((i, n: number) => n + i)([1, 2, 3]), 9) U.deepStrictEqual(reduceRightWithIndex(0, (i, n: number, acc) => -acc + n + i)([1, 2, 3]), 3) }) it('Alt', () => { const { alt } = pipeable(RA.Alt) U.deepStrictEqual(alt(() => [4, 5, 6])([1, 2, 3]), [1, 2, 3, 4, 5, 6]) }) it('Filterable', () => { const { filter, filterMap, partition, partitionMap } = pipeable(RA.Filterable) U.deepStrictEqual(pipe([O.some(1), O.none, O.some(2)], filter(O.isSome)), [O.some(1), O.some(2)] as ReadonlyArray< O.Some >) U.deepStrictEqual(filterMap((a: O.Option) => a)([O.some(1), O.none, O.some(2)]), [1, 2]) assert.deepStrictEqual( pipe([O.some(1), O.none, O.some(2)], partition(O.isSome)), separated([O.none], [O.some(1), O.some(2)]) ) U.deepStrictEqual( partitionMap((n: number) => (n > 2 ? E.right(n) : E.left(String(n))))([1, 2, 3]), separated(['1', '2'], [3]) ) }) it('FilterableWithIndex', () => { const { filterWithIndex, filterMapWithIndex, partitionWithIndex, partitionMapWithIndex } = pipeable( RA.FilterableWithIndex ) U.deepStrictEqual( filterWithIndex((i, a: O.Option) => i > 1 && O.isSome(a))([O.some(1), O.none, O.some(2)]), [O.some(2)] ) U.deepStrictEqual( filterMapWithIndex((i, a: O.Option) => pipe( a, O.map((n) => n + i) ) )([O.some(1), O.none, O.some(2)]), [1, 4] ) U.deepStrictEqual( partitionWithIndex((i, a: O.Option) => i > 1 && O.isSome(a))([O.some(1), O.none, O.some(2)]), separated([O.some(1), O.none], [O.some(2)]) ) U.deepStrictEqual( partitionMapWithIndex((i, n: number) => (i < 2 && n > 1 ? E.right(n) : E.left(String(n))))([1, 2, 3]), separated(['1', '3'], [2]) ) }) it('Profunctor', () => { const { promap } = pipeable(R.Profunctor) const f = promap( (s: string) => s + 'a', (n: number) => n > 2 )((s: string) => s.length) U.deepStrictEqual(f('a'), false) U.deepStrictEqual(f('aa'), true) }) it('Semigroupoid', () => { const { compose } = pipeable(R.Category) U.deepStrictEqual(compose((s: string) => s.length)((n) => n * 2)('aa'), 4) }) it('MonadThrow', () => { const { fromEither, fromOption, fromPredicate, filterOrElse } = pipeable(E.MonadThrow) U.deepStrictEqual(fromEither(E.right(1)), E.right(1)) U.deepStrictEqual(fromEither(E.left('a')), E.left('a')) U.deepStrictEqual(fromOption(() => 'none')(O.none), E.left('none')) U.deepStrictEqual(fromOption(() => 'none')(O.some(1)), E.right(1)) const gt2 = fromPredicate( (n: number) => n >= 2, (n) => `Invalid number ${n}` ) U.deepStrictEqual(gt2(3), E.right(3)) U.deepStrictEqual(gt2(1), E.left('Invalid number 1')) const gt10 = (n: number): boolean => n > 10 U.deepStrictEqual( pipe( E.right(12), filterOrElse(gt10, () => -1) ), E.right(12) ) U.deepStrictEqual( pipe( E.right(7), filterOrElse(gt10, () => -1) ), E.left(-1) ) U.deepStrictEqual( pipe( E.left(12), filterOrElse(gt10, () => -1) ), E.left(12) ) U.deepStrictEqual( pipe( E.right(7), filterOrElse(gt10, (n) => `invalid ${n}`) ), E.left('invalid 7') ) }) }) ================================================ FILE: test/string.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/string' import * as U from './util' describe('string', () => { // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('Show', () => { U.deepStrictEqual(_.Show.show('a'), '"a"') }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('empty', () => { U.deepStrictEqual(_.empty, '') }) it('isEmpty', () => { U.deepStrictEqual(_.isEmpty(_.empty), true) U.deepStrictEqual(_.isEmpty(''), true) U.deepStrictEqual(_.isEmpty('a'), false) }) it('isString', () => { U.deepStrictEqual(_.isString(_.empty), true) U.deepStrictEqual(_.isString('a'), true) U.deepStrictEqual(_.isString(1), false) }) it('size', () => { U.deepStrictEqual(_.size(_.empty), 0) U.deepStrictEqual(_.size(''), 0) U.deepStrictEqual(_.size('a'), 1) }) it('toUpperCase', () => { U.deepStrictEqual(_.toUpperCase('a'), 'A') }) it('toLowerCase', () => { U.deepStrictEqual(_.toLowerCase('A'), 'a') }) it('replace', () => { U.deepStrictEqual(pipe('abc', _.replace('b', 'd')), 'adc') }) it('split', () => { U.deepStrictEqual(pipe('abc', _.split('')), ['a', 'b', 'c']) U.deepStrictEqual(pipe('', _.split('')), ['']) }) it('trim', () => { U.deepStrictEqual(pipe(' a ', _.trim), 'a') }) it('trimLeft', () => { U.deepStrictEqual(pipe(' a ', _.trimLeft), 'a ') }) it('trimRight', () => { U.deepStrictEqual(pipe(' a ', _.trimRight), ' a') }) it('includes', () => { U.deepStrictEqual(pipe('abc', _.includes('b')), true) U.deepStrictEqual(pipe('abc', _.includes('b', 2)), false) }) it('startsWith', () => { U.deepStrictEqual(pipe('abc', _.startsWith('a')), true) }) it('endsWith', () => { U.deepStrictEqual(pipe('abc', _.endsWith('c')), true) }) it('slice', () => { U.deepStrictEqual(pipe('abcd', _.slice(1, 3)), 'bc') }) }) ================================================ FILE: test/struct.ts ================================================ import { pipe } from '../src/function' import * as _ from '../src/struct' import * as U from './util' describe('struct', () => { it('getAssignSemigroup', () => { type T = { readonly foo?: number readonly bar: string } const foo: T = { foo: 123, bar: '456' } const bar: T = { bar: '123' } const S = _.getAssignSemigroup() U.deepStrictEqual(S.concat(foo, bar), Object.assign({}, foo, bar)) }) it('evolve', () => { U.deepStrictEqual( pipe( { a: 'a', b: 1, c: true }, _.evolve({ a: (s) => s.length, b: (b) => b > 0, c: (c) => !c }) ), { a: 1, b: true, c: false } ) // should ignore non own properties const x: Record<'b', number> = Object.create({ a: 1 }) x.b = 1 U.deepStrictEqual(pipe(x, _.evolve({ b: (b) => b > 0 })), { b: true }) }) }) ================================================ FILE: test/util.ts ================================================ import * as assert from 'assert' import { Apply, Apply1, Apply2, Apply2C, Apply3, Apply4, sequenceT } from '../src/Apply' import { FromTask, FromTask1, FromTask2, FromTask3, FromTask4 } from '../src/FromTask' import { HKT, Kind, Kind2, Kind3, Kind4, URIS, URIS2, URIS3, URIS4 } from '../src/HKT' import * as T from '../src/Task' export const deepStrictEqual = (actual: A, expected: A) => { assert.deepStrictEqual(actual, expected) } export const strictEqual = (actual: A, expected: A) => { assert.strictEqual(actual, expected) } export const double = (n: number): number => n * 2 export interface AssertParSeq { ( F: Apply4, MT: FromTask4, run: (fa: Kind4) => Promise ): Promise ( F: Apply3, MT: FromTask3, run: (fa: Kind3) => Promise ): Promise ( F: Apply2, MT: FromTask2, run: (fa: Kind2) => Promise ): Promise ( F: Apply2C, MT: FromTask2, run: (fa: Kind2) => Promise ): Promise (F: Apply1, MT: FromTask1, run: (fa: Kind) => Promise): Promise (F: Apply, MT: FromTask, run: (fa: HKT) => Promise): Promise } export const assertParSeq = (expected: ReadonlyArray): AssertParSeq => async (F: Apply, MT: FromTask, run: (fa: HKT) => Promise) => { const log: Array = [] const a = MT.fromTask(T.delay(100)(T.fromIO(() => log.push('a')))) const b = MT.fromTask(T.fromIO(() => log.push('b'))) const ab = sequenceT(F)(a, b) await run(ab) deepStrictEqual(log, expected) } export const assertPar = assertParSeq(['b', 'a']) export const assertSeq = assertParSeq(['a', 'b']) ================================================ FILE: tsconfig.build-es6.json ================================================ { "extends": "./tsconfig.build.json", "compilerOptions": { "outDir": "./dist/es6", "module": "es6" } } ================================================ FILE: tsconfig.build.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "noEmit": false }, "include": ["./src"] } ================================================ FILE: tsconfig.eslint.json ================================================ { "compilerOptions": { "noEmit": true, "allowJs": true, "baseUrl": "." }, "include": [ "./src/**/*.ts", "./test/**/*.ts", "./dtslint/**/*.ts", "./examples/**/*.ts", "./benchmark/**/*.ts", "./vitest.config.ts", "./scripts/**/*.ts" ] } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "noEmit": true, "outDir": "./dist/lib", "target": "es5", "module": "commonjs", "moduleResolution": "node", "esModuleInterop": true, "lib": [], "sourceMap": false, "declaration": true, "strict": true, "noImplicitReturns": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "forceConsistentCasingInFileNames": true, "stripInternal": true, "skipLibCheck": true, "types": ["vitest/globals"], "plugins": [ { "name": "@effect/language-service" } ] }, "include": ["./src", "./test", "./scripts", "./perf", "./dtslint"], "exclude": ["./node_modules"] } ================================================ FILE: vite.config.ts ================================================ /// import { defineConfig } from 'vite' export default defineConfig({ test: { include: ['./test/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], exclude: ['./test/**/util.ts'], globals: true, coverage: { provider: 'istanbul' } } })