F# 帮助类型推断的方法?

标签 f# type-inference

Expert F# 2.0 Don Syme、Adam Granicz 和 Antonio Cisternino,第44

Type inference: Using the |> operator lets type information flow from input objects to the functions manipulating those objects. F# uses information collected from type inference to resolve some language constructs such as property accesses and method overloading. This relies on information being propagated left to right thorough the text of a program. In particular, type information to the right of a position isn't taken into account when resolving property access and overload.



很明显,使用 |> 可以帮助类型推断。

与往常一样,声明类型也很有帮助。

是否有任何其他方法/策略可用于帮助 F# 类型推断?

编辑

正如 RamonSnir 正确指出的那样,应该让类型推断做尽可能多的工作。因此,仅仅因为你可以添加类型声明并不是一个人应该做的。不要把这个问题或答案当作应该做的事情。我问这个问题是为了帮助更好地理解类型推断的细微差别,以及在类型推断需要帮助的情况下有什么帮助。因此,如果类型推断可以在没有帮助的情况下解析所有类型,那么不要给它任何帮助,但是当它这样做时,知道一些帮助它的方法会很好。

最佳答案

几点:

1)更喜欢模块功能而不是属性和方法。

List.map (fun x -> x.Length) ["hello"; "world"] // fails
List.map String.length ["hello"; "world"] // works

let mapFirst xss = Array.map (fun xs -> xs.[0]) xss // fails
let mapFirst xss = Array.map (fun xs -> Array.get xs 0) xss // works

2)更喜欢没有重载的方法。例如,QuickLinq Helpers定义非重载成员以避免 LINQ 扩展方法中的一堆类型注释。

3) 利用任何可用信息给类型检查器一些提示。
let makeStreamReader x = new System.IO.StreamReader(x) // fails
let makeStreamReader x = new System.IO.StreamReader(path=x) // works

最后一个例子取自一篇关于 F# type inference 的优秀文章。 .

总而言之,您通常不需要帮助 F# 类型检查器。如果存在类型错误,上面链接的摘要提供了一个很好的修复指南:

So to summarize, the things that you can do if the compiler is complaining about missing types, or not enough information, are:

  • Define things before they are used (this includes making sure the files are compiled in the right order)
  • Put the things that have "known types" earlier than things that have "unknown types". In particular, you might be able reorder pipes and similar chained functions so that the typed objects come first.
  • Annotate as needed. One common trick is to add annotations until everything works, and then take them away one by one until you have the minimum needed. Do try to avoid annotating if possible. Not only is it not aesthetically pleasing, but it makes the code more brittle. It is a lot easier to change types if there are no explicit dependencies on them.

关于F# 帮助类型推断的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13821811/

相关文章:

java - 当 API 说接口(interface)的方法返回某些内容时,它是什么意思?

scala - 如何基于函数的type参数的类型参数编写具有多态返回类型的函数?

c# - 是否有可能以强类型方式调用泛型方法,同时保持在编译时推断类型的能力?

f# - 将 F# 3.0 中的 Amazon WSDL Web 服务与类型提供程序结合使用

f# - 如何在寓言中使用window.chrome API

macros - 如何强制 Haxe 宏返回类型为 Array/Iterable?

c# - 方法推断不适用于方法组

.net - 使用与使用 : preferred style?

lambda - 列表列表、lambda 和过滤结果

list - 预定义列表 F# 的总和