你会怎么称呼一个以 T<A>[] 作为输入并输出 T<A[]> 的函数?
What would you call a function that takes T<A>[] as input and outputs T<A[]>?
一些例子
const f = <L, R>(xs: Either<L, R>[]): Either<L, R[]> => { throw new Error('Not Implemented') };
const f = <T>(xs: Promise<T>[]): Promise<T[]> => { throw new Error('Not Implemented') };
const f = <T>(xs: Box<T>[]): Box<T[]> => { throw new Error('Not Implemented') };
这些都执行某种减少。然而,这里的半群只是一个列表。
从可读性的角度来看,这些函数有什么好名字。
这里显然有一定程度的主观性,SO不鼓励这样做。但是,我觉得也可以说一个名字好坏 objective criteria/rationale.
也许只有 collect
或 gather
行?
TypeScript 不是 Haskell,但我通常会去那里查看我正在创建的事物类型是否已经有一个众所周知的名称。
假设Either<L, T>
、Promise<T>
、Box<T>
都是applicative functors over T
, then the function signatures <L,T>(x: Array<Either<L, T>>) => Either<L, Array<T>>
, <T>(x: Array<Promise<T>>) => Promise<Array<T>>
, and <T>(x: Array<Box<T>>) => Box<Array<T>>
would probably be called sequence
。
类型函数F<T>
应用函子优于T
的规则草图:您需要一些这样的函数:
declare function pure<T>(x: T): F<T>;
declare function lift2<A, B, T>(cb: (a: A, b: B) => T): (fa: F<A>, fb: F<B>) => F<T>;
然后sequence
可以这样实现:
function sequence<T>(x: Array<F<T>>): F<Array<T>> {
return x.reduce(lift2<T[], T, T[]>((xs, x) => xs.concat(x)), pure([]))
}
对于 Promise<T>
这相当简单:
function pure<T>(x: T): Promise<T> {
return Promise.resolve(x);
}
function lift2<A, B, T>(cb: (a: A, b: B) => T): (fa: Promise<A>, fb: Promise<B>) => Promise<T> {
return (fa: Promise<A>, fb: Promise<B>) => fa.then(a => fb.then(b => cb(a, b)))
}
你大概也可以为 Either<L, T>
和 Box<T>
想出一个。
好的,希望对您有所帮助;祝你好运!
一些例子
const f = <L, R>(xs: Either<L, R>[]): Either<L, R[]> => { throw new Error('Not Implemented') };
const f = <T>(xs: Promise<T>[]): Promise<T[]> => { throw new Error('Not Implemented') };
const f = <T>(xs: Box<T>[]): Box<T[]> => { throw new Error('Not Implemented') };
这些都执行某种减少。然而,这里的半群只是一个列表。
从可读性的角度来看,这些函数有什么好名字。
这里显然有一定程度的主观性,SO不鼓励这样做。但是,我觉得也可以说一个名字好坏 objective criteria/rationale.
也许只有 collect
或 gather
行?
TypeScript 不是 Haskell,但我通常会去那里查看我正在创建的事物类型是否已经有一个众所周知的名称。
假设Either<L, T>
、Promise<T>
、Box<T>
都是applicative functors over T
, then the function signatures <L,T>(x: Array<Either<L, T>>) => Either<L, Array<T>>
, <T>(x: Array<Promise<T>>) => Promise<Array<T>>
, and <T>(x: Array<Box<T>>) => Box<Array<T>>
would probably be called sequence
。
类型函数F<T>
应用函子优于T
的规则草图:您需要一些这样的函数:
declare function pure<T>(x: T): F<T>;
declare function lift2<A, B, T>(cb: (a: A, b: B) => T): (fa: F<A>, fb: F<B>) => F<T>;
然后sequence
可以这样实现:
function sequence<T>(x: Array<F<T>>): F<Array<T>> {
return x.reduce(lift2<T[], T, T[]>((xs, x) => xs.concat(x)), pure([]))
}
对于 Promise<T>
这相当简单:
function pure<T>(x: T): Promise<T> {
return Promise.resolve(x);
}
function lift2<A, B, T>(cb: (a: A, b: B) => T): (fa: Promise<A>, fb: Promise<B>) => Promise<T> {
return (fa: Promise<A>, fb: Promise<B>) => fa.then(a => fb.then(b => cb(a, b)))
}
你大概也可以为 Either<L, T>
和 Box<T>
想出一个。
好的,希望对您有所帮助;祝你好运!