【问题标题】:F# value restriction problem in reversing list反转列表中的F#值限制问题
【发布时间】:2021-02-23 04:23:39
【问题描述】:

由于值限制问题,以下 F# 代码无法编译:

let x = List.rev []

但这编译:

let x = List.rev [] in 3::x

据我了解,编译器推断 x 必须是 int list 类型,因此无法编译。

以下内容无法编译:

let x = List.rev [] in (3::x, true::x)

但这确实:

let x = ([]) in (3::x, true::x)

为什么?

【问题讨论】:

  • 您可以在不同的文章中阅读有关值限制的信息,例如herehere
  • 类型推断可以在任何方向上传播。对于List.rev : 'a list -> 'a list,没有可以同时满足intbool'a 类型。

标签: f#


【解决方案1】:

据我了解*,在 F# 中声明值有两种方法:

  • 值具有具体类型(例如List<int>)。您必须明确指定此具体类型,或者编译器必须能够推断它。
  • 值具有通用类型(例如List<'t>)。您必须明确指定此泛型类型,或者编译器必须能够推断它并且值必须是简单的不可变值

考虑到这一点,以下是您所看到内容的解释:

// not allowed because x is generic, but not simple
let x = List.rev []

// allowed because the compiler can infer x's concrete type (List<int>)
let x = List.rev [] in 3::x

// not allowed because x is generic, but not simple
let x = List.rev [] in (3::x, true::x)

// allowed because x is both generic and simple (compiler can tell it's the empty list)
let x = ([]) in (3::x, true::x)

* 值限制可能很棘手,因此我在解释中可能忽略了一些细微差别。

【讨论】:

    猜你喜欢
    • 2012-03-13
    • 2020-10-03
    • 2010-09-29
    • 2013-01-26
    • 2011-05-03
    • 2019-07-19
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多