F# Ways to help type inference?

前端 未结 1 1450
盖世英雄少女心
盖世英雄少女心 2020-12-20 16:48

In Expert F# 2.0 by Don Syme, Adam Granicz, and Antonio Cisternino, pg. 44

Type inference: Using the |> operator lets type information flow from inp

相关标签:
1条回答
  • 2020-12-20 17:21

    A few points:

    1) Prefer module functions to properties and methods.

    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) Prefer methods without overloading. For example, QuickLinq Helpers define non-overloaded members to avoid a bunch of type annotation in LINQ extension methods.

    3) Make use of any available information to give some hints to the type checker.

    let makeStreamReader x = new System.IO.StreamReader(x) // fails
    let makeStreamReader x = new System.IO.StreamReader(path=x) // works
    

    The last example is taken from an excellent write-up about F# type inference.

    To conclude, you don't often need to help F# type checker. If there is a type error, the summary from the link above gives a good fixing guideline:

    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.
    0 讨论(0)
提交回复
热议问题