Skip to content

Instantly share code, notes, and snippets.

@matthewcrews
Created February 3, 2022 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewcrews/bea24372de6af4f040ec68a0640289ef to your computer and use it in GitHub Desktop.
Save matthewcrews/bea24372de6af4f040ec68a0640289ef to your computer and use it in GitHub Desktop.
[<Measure>] type Chicken
[<Measure>] type Cow
type Arr<[<Measure>] 'Measure>(v: array<'T>) =
member _.Item
with get (i: int<'Measure>) =
v.[int i]
let chickenSizeArray =
[|1.0 .. 10.0|]
|> Arr<Chicken>
let cowSizeArray =
[|1.0 .. 10.0|]
|> Arr<Cow>
let chickenIndex = 1<Chicken>
// This works
let chickenSize = chickenSizeArray[chickenIndex]
// This won't compile
let cowSize = cowSizeArray[chickenIndex]
@goswinr
Copy link

goswinr commented Feb 6, 2022

I have a warning on line 13: FS0064: This construct causes code to be less generic than indicated by the type annotations. The type variable 'T has been constrained to be type 'float'.
Like this it works:

[<Measure>] type ChickenIdx
[<Measure>] type CowIdx

type Arr<'T, [<Measure>] 'Measure>(v: array<'T>) =

    member _.Item
        with get (i: int<'Measure>) =
            v.[int i]


let chickenSizeArray =
    [|1.0 .. 10.0|]
    |> Arr<float, ChickenIdx>

let cowSizeArray =
    [|1.0 .. 10.0|]
    |> Arr<float, CowIdx>


let chickenIndex = 1<ChickenIdx>

// This works
let chickenSize = chickenSizeArray[chickenIndex]

// This won't compile
let cowSize = cowSizeArray[chickenIndex]

@matthewcrews
Copy link
Author

Yeah, I've updated my code since then. Good catch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment