Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 542
devoured elysium Avatar asked Sep 12 '11 02:09

devoured elysium


1 Answers

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
like image 126
Tomas Petricek Avatar answered Sep 28 '22 03:09

Tomas Petricek