gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:05:49 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com