带有选项和链的 fp-ts 管道不起作用
fp-ts pipeline with Option and chain not working
我有这个示例代码:
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);
我遇到了这个编译时错误
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?
我的代码有什么问题?
我期望 f1
和 f2
到 运行 和其他功能不是因为 none
在 f3
返回并且最后输出是Some "X f1 f2"
fp-ts pipe
函数需要初始值 "X"
作为第一个参数,以促进 TypeScript 从左到右的泛型推理。
因此,与其他以柯里化方式传递初始值的 fp 库相比,您可以按如下方式创建管道:
const result = pipe(
"X", // here is initial argument
f1,
chain(f2),
chain(f3),
chain(f4)
); // type: Option<string>, actual value is None
return 值将是 None
- 一旦一个选项是 None
,它将保持 None
,当你 chain
超过它时(实施here):
chain((n: number) => some(n*2))(none) // stays None
编辑:
flow
(等同于其他库的 pipe
)是另一种选择,在示例中以您想要的方式运行:
import { flow } from "fp-ts/lib/function";
const result3 = flow(
f1,
chain(f2),
chain(f3),
chain(f4)
)("X")
可能会出现类型问题。例如,第一个函数 (f1
) 的函数参数类型需要用显式类型注释。还请考虑,pipe
被维护者视为组合的新 "blessed way"。
我有这个示例代码:
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);
我遇到了这个编译时错误
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?
我的代码有什么问题?
我期望 f1
和 f2
到 运行 和其他功能不是因为 none
在 f3
返回并且最后输出是Some "X f1 f2"
fp-ts pipe
函数需要初始值 "X"
作为第一个参数,以促进 TypeScript 从左到右的泛型推理。
因此,与其他以柯里化方式传递初始值的 fp 库相比,您可以按如下方式创建管道:
const result = pipe(
"X", // here is initial argument
f1,
chain(f2),
chain(f3),
chain(f4)
); // type: Option<string>, actual value is None
return 值将是 None
- 一旦一个选项是 None
,它将保持 None
,当你 chain
超过它时(实施here):
chain((n: number) => some(n*2))(none) // stays None
编辑:
flow
(等同于其他库的 pipe
)是另一种选择,在示例中以您想要的方式运行:
import { flow } from "fp-ts/lib/function";
const result3 = flow(
f1,
chain(f2),
chain(f3),
chain(f4)
)("X")
可能会出现类型问题。例如,第一个函数 (f1
) 的函数参数类型需要用显式类型注释。还请考虑,pipe
被维护者视为组合的新 "blessed way"。