我有一个带有以下参数的扫描运算符:
.scan(function (acc:Message[], x: (msg: Message[]) => Message[]){ return x(acc); }, initialMessages)我的问题是什么return x(acc)实际返回? 累加器function在这种特殊情况下如何工作? 我对TypeScript和lambda表达式相当陌生,因此非常感谢任何帮助。
I have a scan operator with the following arguments:
.scan(function (acc:Message[], x: (msg: Message[]) => Message[]){ return x(acc); }, initialMessages)my question is what return x(acc) returns actually? how does the accumulator function work in this particular case? I am quite new to TypeScript and lambda expressions, so any help is much appreciated.
最满意答案
在这种情况下, x(acc)的类型将是Message[] 。 你可以通过第二个参数x的签名来告诉它,它返回Message[] 。
通常scan()接受一个带累加器和值的函数(acc, val) => ... 并发出返回的值。 在这种情况下,进入扫描操作符的发射值val是一个闭包。 这有点不寻常,但非常好。 输出的一个例子
[ 1, 2, 3 ] [ 3, 4, 5 ] [ 4, 5, 6 ]...将会:
import { Observable } from 'rxjs/Rx'; type Message = number; function scanFn(acc: Message[], x: (msg: Message[]) => Message[]): Message[] { return x(acc); } function mapFn(val: Message): (msg: Message[]) => Message[] { return x => x.map((y, i) => val + i); } Observable.from([1, 3, 4]) .map(mapFn) .scan(scanFn, [1, 2, 3]) .subscribe(console.log);In this case the type of x(acc) would be Message[]. You can tell this from the signature of the 2nd argument x, which returns Message[].
Usually scan() accepts a function (acc, val) => ... with accumulator and value. and emits the returned value. In this case the emitted value val entering the scan operator is a closure. it's a bit unusual, but perfectly fine. An example which outputs
[ 1, 2, 3 ] [ 3, 4, 5 ] [ 4, 5, 6 ]...would be:
import { Observable } from 'rxjs/Rx'; type Message = number; function scanFn(acc: Message[], x: (msg: Message[]) => Message[]): Message[] { return x(acc); } function mapFn(val: Message): (msg: Message[]) => Message[] { return x => x.map((y, i) => val + i); } Observable.from([1, 3, 4]) .map(mapFn) .scan(scanFn, [1, 2, 3]) .subscribe(console.log);更多推荐
发布评论