[英]fp-ts pipeline with Option and chain not working
I have this sample code:我有这个示例代码:
import {none, some, chain} from 'fp-ts/lib/Option';
import {pipe} from 'fp-ts/lib/pipeable';
const f1 = (input: string) => {
return some(input + " f1")
};
const f2 = (input: string) => {
return some(input + "f2")
};
const f3 = (input: string) => {
return none;
};
const f4 = (input: string) => {
return some(input + "f4");
};
const result = pipe(
f1,
chain(f2),
chain(f3),
chain(f4),
)("X");
console.log("result", result);
And I am getting this compile time error我收到这个编译时错误
Argument of type '(input: string) => Option<string>' is not assignable to parameter of type 'Option<string>'.
Type '(input: string) => Option<string>' is missing the following properties from type 'Some<string>': _tag, value
18 f1,
~~
src/index.ts:18:5
18 f1,
~~
Did you mean to call this expression?
What is wrong with my code?我的代码有什么问题?
I expect f1
and f2
to run and other function not because of none
returning in f3
and at the end the output to be Some "X f1 f2"
我希望
f1
和f2
运行和其他功能不是因为f3
中none
返回,最后输出是Some "X f1 f2"
The fp-ts pipe
function expects the initial value "X"
as first argument to facilitate TypeScript left to right generic inference. fp-ts
pipe
函数期望初始值"X"
作为第一个参数,以促进 TypeScript 从左到右的泛型推理。
So in contrast to other fp-libraries, where the initial value is passed in a curried manner, you create the pipe as follows:因此,与其他以柯里化方式传递初始值的 fp 库相比,您可以按如下方式创建管道:
const result = pipe(
"X", // here is initial argument
f1,
chain(f2),
chain(f3),
chain(f4)
); // type: Option<string>, actual value is None
The return value will be None
- once an option is None
, it will stay None
, when you chain
over it (implementation here ):返回值将是
None
-一旦选择是None
,它会留None
,当你chain
在它(实现此):
chain((n: number) => some(n*2))(none) // stays None
Edit:编辑:
flow
(equivalent of other libraries' pipe
) is an alternative, that behaves in the way you want it in the example: flow
(相当于其他库的pipe
)是另一种选择,在示例中以您希望的方式运行:
import { flow } from "fp-ts/lib/function";
const result3 = flow(
f1,
chain(f2),
chain(f3),
chain(f4)
)("X")
There may arise type problems.可能会出现类型问题。 For example, it is necessary to have the function parameter types of the first function (
f1
) annotated with explicit types.例如,需要使用显式类型注释第一个函数 (
f1
) 的函数参数类型。 Also consider, that pipe
is seen as the new "blessed way" for compositions by the maintainers.还要考虑一下,该
pipe
被维护者视为新的“祝福方式” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.