Repository: pelotom/hkts Branch: master Commit: 786840c7d6fe Files: 13 Total size: 22.4 KB Directory structure: gitextract_mg5a2za2/ ├── .gitignore ├── .prettierignore ├── .prettierrc.yml ├── .travis.yml ├── .vscode/ │ └── settings.json ├── LICENSE ├── README.md ├── jest.config.js ├── package.json ├── src/ │ ├── index.spec.ts │ ├── index.ts │ └── static-land.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ coverage lib node_modules ================================================ FILE: .prettierignore ================================================ coverage lib package.json README.md tsconfig.json ================================================ FILE: .prettierrc.yml ================================================ arrowParens: avoid bracketSpacing: true printWidth: 100 semi: true tabWidth: 2 trailingComma: all singleQuote: true ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - node cache: yarn script: - yarn test - yarn format after_success: cat ./coverage/lcov.info | ./node_modules/.bin/coveralls ================================================ FILE: .vscode/settings.json ================================================ { "typescript.tsdk": "node_modules/typescript/lib", "editor.codeActionsOnSave": { "source.organizeImports": true }, "editor.formatOnSave": true } ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2018 Tom Crockett 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 ================================================ # HKTS - Higher-Kinded TypeScript [![Build Status](https://travis-ci.com/pelotom/hkts.svg?branch=master)](https://travis-ci.com/pelotom/hkts) ## Overview TypeScript [doesn't directly support higher-kinded types yet](https://github.com/Microsoft/TypeScript/issues/1213), but various attempts have been made to simulate them (see [related work](https://github.com/pelotom/hkts/blob/master/README.md#related-work) at the bottom). This project presents a new, greatly simplified approach to encoding HKTs using the power of conditional types. The idea is that, although we can't truly abstract over a type constructor `type T = ...`, we _can_ abstract over the result `T<_>` of applying it to a special placeholder type `_`. Then, if we can somehow substitute all instances of `_` within a type, we effectively have the ability to "apply" `T` at arbitrary types. That is, we can abstract over `T`! And it turns out we can define a substitution operator `$` which does just that. Here's how we would use `$` to define the [static-land's `Functor` type class](https://github.com/rpominov/static-land/blob/master/docs/spec.md#functor): ```ts interface Functor { map: (f: (x: A) => B, t: $) => $; } ``` Then, supposing we have a `Maybe` type constructor ```ts type Maybe = { tag: 'none' } | { tag: 'some'; value: A }; const none: Maybe = { tag: 'none' }; const some = (value: A): Maybe => ({ tag: 'some', value }); ``` we can define a `Functor` instance for it like so, using the placeholder type `_`: ```ts const MaybeFunctor: Functor> = { map: (f, maybe) => maybe.tag === 'none' ? none : some(f(maybe.value)), }; // It works! expect(MaybeFunctor.map(n => n + 1, some(42))).toEqual(some(43)); ``` ## Type classes and instance factories This package defines [a set of interfaces](https://github.com/pelotom/hkts/blob/master/src/static-land.ts) corresponding to the the type classes of the [static-land spec](https://github.com/rpominov/static-land), as well as factory functions for producing instances thereof. For example, there is a `Monad` interface as well as a `Monad` function. The function takes as arguments only the minimum data (`of` and `chain`) needed to produce an implementation of the full `Monad` interface (which includes other derived methods like `map`, `ap` and `join`). So again using the `Maybe` type above, we can construct a `Monad` instance like so: ```ts const MaybeMonad = Monad>({ of: some, chain: (f, maybe) => maybe.tag === 'none' ? none : f(maybe.value), }); // Use the `map` method, which we didn't have to define: expect(MaybeMonad.map(n => n + 1, some(42))).toBe(some(43)); ``` ## Abstracting over kinds of higher arity You may have noticed in the above example that `$` takes an array of substitution types as its second parameter. There are also placeholders `_0` (an alias for `_`), `_1`, `_2`, ..., `_`. `$` simultaneously replaces `_0` with `S[0]`, `_1` with `S[1]`, and so on, throughout `T`. This allows us to define, for example, `Bifunctor`, which abstracts over a type constructor of kind `(*, *) -> *`: ```ts interface Bifunctor { bimap: (f: (x: A) => B, g: (x: C) => D, t: $) => $; // ... } ``` Then given an `Either` type constructor ```ts type Either = { tag: 'left'; left: A } | { tag: 'right'; right: B }; const left = (left: A): Either => ({ tag: 'left', left }); const right = (right: B): Either => ({ tag: 'right', right }); ``` a `Bifunctor` instance for it looks like ```ts type EitherBifunctor: Bifunctor> = { bimap: (f, g, either) => (either.tag === 'left' ? left(f(either.left)) : right(g(either.right))), }; ``` ## Fixing type parameters Suppose we want to ignore one or more of the parameters of a type constructor for the purpose of making it an instance of a type class. For example we can make a `Monad` out of `Either` by ignoring its first parameter and using the second parameter as the "hole" of the monad. The way to do this is to make a polymorphic instance creation function which can produce a `Monad` instance _for any given left type `L`_: ```ts const RightMonad = () => Monad>({ of: right, chain: (f, either) => either.tag === 'left' ? either : f(either.right), }); ``` ## Known limitations The type application operator `$` is able to transform most types correctly, including functions, however there are a few edge cases: - Polymorphic functions will get nerfed. For example: ```ts type Id = (x: A) => A type NerfedId = $; // type NerfedId = (x_0: {}) => {} ``` Not what you wanted! Unfortunately TypeScript's conditional types don't currently allow analyzing and reconstructing the type parameters of a function ([this feature](https://github.com/Microsoft/TypeScript/issues/5453) might solve that). - Tuples `[A, B, ...]` are transformed correctly up to size 10 (though we can add arbitrarily many more as needed), after which they will be transformed into an array `(A | B | ...)[]`. Correspondingly, functions of arity <= 10 are supported. - In some cases the `join` method of `Monad` [must be supplied a type parameter](https://github.com/pelotom/hkts/blob/5ba4734bef74e9c2b8a10a75cb1de9ce230bde37/src/index.spec.ts#L23)... I've filed [an issue about this](https://github.com/Microsoft/TypeScript/issues/26807). The good news is it's still safe; you can't provide a _wrong_ type argument without getting an error. ## Related work Other notable attempts to solve this problem: - https://medium.com/@gcanti/higher-kinded-types-in-typescript-static-and-fantasy-land-d41c361d0dbe - https://github.com/SimonMeskens/TypeProps ================================================ FILE: jest.config.js ================================================ module.exports = { clearMocks: true, coverageDirectory: 'coverage', globals: { 'ts-jest': { tsConfigFile: 'tsconfig.json', }, }, moduleFileExtensions: ['ts', 'tsx', 'js'], testEnvironment: 'node', testMatch: ['/src/**/*.spec.ts'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, }; ================================================ FILE: package.json ================================================ { "name": "hkts", "version": "0.3.1", "description": "A simple encoding of higher-kinded types in TypeScript", "keywords:": [ "typescript", "higher", "kinded", "types" ], "main": "./lib/index.js", "types": "./lib/index.d.ts", "author": "Thomas Crockett", "license": "MIT", "devDependencies": { "@types/jest": "^23.3.1", "jest": "^23.5.0", "prettier": "^1.14.2", "ts-jest": "^23.1.4", "typescript": "^3.0.1" }, "scripts": { "build": "tsc", "format": "prettier $([ \"$CI\" == true ] && echo --list-different || echo --write) './**/*.{ts,tsx,js,json,css}'", "test": "jest $([ \"$CI\" == true ] && echo --no-cache --verbose --coverage)" } } ================================================ FILE: src/index.spec.ts ================================================ import { Bifunctor, Monad, _, _0, _1 } from '.'; it('array', () => { const { map, join } = Monad<_[]>({ of: x => [x], chain: (f, xs) => xs.map(f).reduce((xs, ys) => xs.concat(ys), []), }); const result = map(n => n + 1, join([[42]])); expect(result).toEqual([43]); }); it('maybe', () => { type Maybe = { tag: 'none' } | { tag: 'some'; value: A }; const none: Maybe = { tag: 'none' }; const some = (value: A): Maybe => ({ tag: 'some', value }); const { map, join } = Monad>({ of: some, chain: (f, maybe) => (maybe.tag === 'none' ? none : f(maybe.value)), }); const result = map(n => n + 1, join(some(some(42)))); expect(result).toEqual(some(43)); }); it('list', () => { type List = { tag: 'nil' } | { tag: 'cons'; head: A; tail: List }; const nil: List = { tag: 'nil' }; const cons = (head: A, tail: List = nil): List => ({ tag: 'cons', head, tail }); const concat = (xs: List, ys: List): List => xs.tag === 'nil' ? ys : cons(xs.head, concat(xs.tail, ys)); const chainList = (f: (x: A) => List, xs: List): List => xs.tag === 'nil' ? nil : concat(f(xs.head), chainList(f, xs.tail)); const { map, join } = Monad>({ of: x => cons(x, nil), chain: chainList, }); const result = map(n => n + 1, join(cons(cons(42)))); expect(result).toEqual(cons(43)); }); describe('either', () => { type Either = { tag: 'left'; left: A } | { tag: 'right'; right: B }; const left = (left: A): Either => ({ tag: 'left', left }); const right = (right: B): Either => ({ tag: 'right', right }); it('bifunctor', () => { const { bimap, first, second } = Bifunctor>({ bimap: (f, g, either) => either.tag === 'left' ? left(f(either.left)) : right(g(either.right)), }); const l = (x: number): boolean => !(x % 2); const r = (y: boolean): string => String(y); const input1: Either = left(2); const result1 = bimap(l, r, input1); expect(result1).toEqual(left(true)); const input2: Either = right(true); const result2 = bimap(l, r, input2); expect(result2).toEqual(right('true')); expect(first(result2).map(x => !x, result2)).toEqual(right('true')); expect(second(result2).map(x => x.length, result2)).toEqual(right(4)); }); it('monad', () => { const RightMonad = () => Monad>({ of: right, chain: (f, either) => (either.tag === 'left' ? either : f(either.right)), }); const either = right(42); const result = RightMonad().map(n => n + 1, either); expect(result).toEqual(right(43)); }); }); ================================================ FILE: src/index.ts ================================================ declare const index: unique symbol; /** * Placeholder representing an indexed type variable. */ export interface _ { [index]: N; } export type _0 = _<0>; export type _1 = _<1>; export type _2 = _<2>; export type _3 = _<3>; export type _4 = _<4>; export type _5 = _<5>; export type _6 = _<6>; export type _7 = _<7>; export type _8 = _<8>; export type _9 = _<9>; declare const fixed: unique symbol; /** * Marks a type to be ignored by the application operator `$`. This is used to protect * bound type parameters. */ export interface Fixed { [fixed]: T; } /** * Type application (simultaneously substitutes all placeholders within the target type) */ // prettier-ignore export type $ = ( T extends Fixed ? { [indirect]: U } : T extends _ ? { [indirect]: S[N] } : T extends undefined | null | boolean | string | number ? { [indirect]: T } : T extends (infer A)[] & { length: infer L } ? { [indirect]: L extends keyof TupleTable ? TupleTable[L] : $[] } : T extends (...x: infer I) => infer O ? { [indirect]: (...x: $) => $ } : T extends object ? { [indirect]: { [K in keyof T]: $ } } : { [indirect]: T } )[typeof indirect]; /** * Used as a level of indirection to avoid circularity errors. */ declare const indirect: unique symbol; /** * Allows looking up the type for a tuple based on its `length`, instead of trying * each possibility one by one in a single long conditional. */ // prettier-ignore type TupleTable = { 0: []; 1: T extends [ infer A0 ] ? [ $ ] : never 2: T extends [ infer A0, infer A1 ] ? [ $, $ ] : never 3: T extends [ infer A0, infer A1, infer A2 ] ? [ $, $, $ ] : never 4: T extends [ infer A0, infer A1, infer A2, infer A3 ] ? [ $, $, $, $ ] : never 5: T extends [ infer A0, infer A1, infer A2, infer A3, infer A4 ] ? [ $, $, $, $, $ ] : never 6: T extends [ infer A0, infer A1, infer A2, infer A3, infer A4, infer A5 ] ? [ $, $, $, $, $, $ ] : never 7: T extends [ infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6 ] ? [ $, $, $, $, $, $, $ ] : never 8: T extends [ infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7 ] ? [ $, $, $, $, $, $, $, $ ] : never 9: T extends [ infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, infer A8 ] ? [ $, $, $, $, $, $, $, $, $ ] : never 10: T extends [ infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, infer A8, infer A9 ] ? [ $, $, $, $, $, $, $, $, $, $ ] : never } export * from './static-land'; ================================================ FILE: src/static-land.ts ================================================ import { $, _ } from '.'; export interface Setoid { equals: (x: T, y: T) => boolean; } export interface Ord extends Setoid { lte: (x: T, y: T) => boolean; } export interface Semigroup { concat: (x: T, y: T) => T; } export interface Monoid extends Semigroup { empty: () => T; } export interface Group extends Monoid { invert: (x: T) => T; } export interface Semigroupoid { compose: (tij: $, tjk: $) => $; } export interface Category extends Semigroupoid { id: () => $; } export interface Filterable { filter: (pred: (x: A) => boolean, ta: $) => $; } export interface Functor { map: (f: (x: A) => B, t: $) => $; } export const Functor = (spec: Functor) => spec; export interface Bifunctor { bimap: (f: (x: A) => B, g: (x: C) => D, t: $) => $; first: (t: $) => Functor<$>; second: (t: $) => Functor<$>; } export const Bifunctor = ({ bimap }: Pick, 'bimap'>): Bifunctor => ({ bimap, first: (t: $) => ({ map: (f, u) => bimap(f, x => x, u), }), second: (t: $) => ({ map: (f, u) => bimap(x => x, f, u), }), }); export interface Contravariant { contramap: (f: (x: A) => B, t: $) => $; } export interface Profunctor { promap: (f: (x: A) => B, g: (x: C) => D, t: $) => $; } export interface Apply extends Functor { ap: (tf: $ B]>, ta: $) => $; } export interface Applicative extends Apply { of: (x: A) => $; } export const Applicative = (spec: Pick, 'ap' | 'of'>): Applicative => ({ ...spec, map: (f, u) => spec.ap(spec.of(f), u), }); export interface Alt extends Functor { alt: (x: $, y: $) => $; } export interface Plus extends Alt { zero: () => $; } export interface Alternative extends Applicative, Plus {} export interface Chain extends Apply { chain: (f: (x: A) => $, t: $) => $; } export const Chain = (spec: Pick, 'chain'> & Pick, 'map'>): Chain => ({ ...spec, ap: (uf, ux) => spec.chain(f => spec.map(f, ux), uf), }); export interface Monad extends Applicative, Chain { join: (tt: $]>) => $; } export const Monad = ({ of, chain, }: Pick, 'of'> & Pick, 'chain'>): Monad => ({ of, ...Chain({ chain, map: (f, t) => chain(x => of(f(x)), t) }), join: tt => chain(t => t, tt), }); export interface Foldable { reduce: (f: (x: A, y: B) => A, x: A, u: $) => A; } export interface Extend extends Functor { extend: (f: (t: $) => B, t: $) => $; } export interface Comonad extends Extend { extract: (t: $) => a; } export interface Traversable extends Functor, Foldable { traverse: (a: Applicative, f: (x: A) => $, t: $) => $]>; } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { /* Basic Options */ "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "lib", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ } }