Guidelines to design a C# library well usable from F#

后端 未结 2 2159
日久生厌
日久生厌 2021-02-08 00:22

I just want to point out that this is question is not the reverse of

Best approach for designing F# libraries for use from both F# and C#

Here I\'m not asking ho

2条回答
  •  清酒与你
    2021-02-08 00:57

    Imagine one day you would like to rewrite your C# library in F# for better usability. Here are the paths you are likely to take:

    enter image description here

    I focus on the path "Imperative C# --> Functional C# --> Functional F# --> Idiomatic F#". The more functional your C# library is, the more usable your library is in F#. Functional style helps increase composability and is closer to idiomatic F# code. Along these lines, you can:

    • Embrace immutability by default principle. If you don't know whether you need to update a field/property later, just mark it readonly first.
    • Follow expression-based and declarative programming style. LINQ operations are good examples.
    • Use immutable collections or mutable collections in an immutable way. With the introduction of C# immutable collections, it should be easier than ever before.

    The picture above is taken from F# for fun and profit's Porting from C# to F# series. They are very helpful; knowing how C# concepts are expressed in F# will improve usability of your library.

    It's hard to avoid C#'s object-oriented features. Remember that F# type inference doesn't work very well with these features. Along the line of keeping object hierarchy simple, you should reduce number of member overloads. A big number of member overloads will easily confuse F# type checker. Moreover, it doesn't hurt to distribute a thin F# wrapper with your C# library. Certain things you need to do are turning some methods into module functions and creatingActive Patterns to decompose object hierarchy.

提交回复
热议问题