开发者

Way to make sure our functions use abbreviated types intead of primitives in F# other than to have to always write it ourselves?

Let's say I have defined some type abbreviation

type Individual = Double array
开发者_开发知识库

and that I am using it throughout my F# project:

let generateIndividual = [|1.0; 2.0|]

IntelliSense tells me generateIndividual has an associated return type of float[]. As I would prefer it to show up Individual as return type, I change its signature to

let generateIndividual : Individual = [|1.0; 2.0|]

When using internal code it really doesn't matter that much what Intellisense shows up. But when doing APIs to be used for the external world it seems prettier to have my functions show up the aliases rather than the primitive types.

Is there by chance any way to avoid having to type them up other than by the method shown above? By Swensen's suggestion I took a look at Signature files, and while at first they appeared to be just what I was looking for, they seem incapable of doing it.


Type aliases like your Individual are only visible in F# if you use explicit annotations to mark values (or function arguments and results) with the type. At compile-time, aliases are replaced with the actual type (e.g. Double array). This means that F# treats both as the same type and there is no way to guarantee that you'll only see the aliased name. You can add type annotations everywhere, but if someone else uses the type, they'll also have to do that.

If you want to make sure, you need to use a wrapper. A discriminated union with a single case is quite nice way to do this, because they are easy to construct and decompose:

type Individual = Individual of Double array

// Creating single-case union
let generateIndividual = Individual [|1.0; 2.0|]  

// Decomposing single-case union
let sumIndividual (Individual data) = Array.sum data
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜