Question

I'm looking for a shorter way (if there is one) to constraint a function. E.g.

let inline sincos (a:'T) =
    let y = sin a
    let x = cos a
    y, x

For using this function, 'T will need to support both Sin and Cos static members. I can constraint it to work on float32 with:

let sincosf = sincos : float32 -> float32 -> float32

or using some wildcard:

let sincosf = sincos : float32 -> _

My question is, would it be possible to add a type parameter to sincos so I just have to write:

let sincosf = sincos<float32>

Thanks in advance.

Was it helpful?

Solution

Indeed, let sincosf = sincos<float32> will give you a warning, but will work as is.

As I noted in the comments, it should be possible to explicitly provide a type parameter on the definition of sincos which would remove the warning. However, this also requires all of the inferred constraints on that parameter to be specified, which can be a bit ugly. In this case, the F# compiler unexpectedly rejects the definition anyway:

let inline sincos< ^t when ^t : (static member Sin : ^t -> ^t)
                       and ^t : (static member Cos : ^t -> ^t)> (a: ^t) =
  let y = sin a
  let x = cos a
  y, x

I believe that this is a compiler bug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top