繁体   English   中英

为什么恒等函数会破坏 Dart 中函数组合的类型推断?

[英]Why does the identity function break type inference of function composition in Dart?

我有一个函数,它包含 3 个函数,同时保留类型推断。 请注意,我的组合函数是左关联的,因此函数是从左到右应用的。

D Function(A) compose3<A, B, C, D>(
        B Function(A) fa, C Function(B) fb, D Function(C) fc) =>
    (x) => fc(fb(fa(x)));

int incr(int x) => x + 1;

T id<T>(T x) => x;

以下代码按预期工作。 res的类型被正确推断为int

void main() {
  var res = compose3(incr, incr, incr)(7);
  print('$res, ${res.runtimeType}'); // 10, int
}

但是中间插入id函数后,代码编译不出来。

var res = compose3(incr, id, incr)(7); // error

有两个错误:

Couldn't infer type parameter 'C'.

Tried to infer 'dynamic' for 'C' which doesn't work:
  Parameter 'fc' declared as     'D Function(C)'
                 but argument is 'int Function(int)'.
The type 'dynamic' was inferred from:
  Parameter 'fb' declared as     'C Function(B)'
                 but argument is 'dynamic Function(dynamic)'.

Consider passing explicit type argument(s) to the generic.

The argument type 'int Function(int)' can't be assigned to the parameter type 'int Function(dynamic)'.

我曾尝试明确指定返回类型,但没有帮助。

int res = compose3(incr, id, incr)(7); // error

以下使错误消失,但它违背了id函数的目的。

T id<T extends int>(T x) => x;

此外,显式应用这些功能是有效的。

void main() {
  var res = incr(id(incr(7)));
  print('$res, ${res.runtimeType}'); // 9, int
}

这已经在 Dartpad 中进行了测试,具有 null 安全性,Dart SDK 2.14.3。

为什么id函数会破坏函数组合中的类型推断,以及如何使其按预期工作?

这是使用扩展方法的解决方案。

extension ComposeExtension on Function {
  C Function(A) pipe<A, B, C>(C Function(B) f) => (x) => f(this(x));
}

int incr(int x) => x + 1;

T id<T>(T x) => x;

void main() {
  var res = incr
    .pipe(id)
    .pipe(incr)(7);
  
  print('$res, ${res.runtimeType}'); // 9, int
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM