When to use Data.Coerce?

Viewed 101

In the inline-c package, there's an example calling the C library GNU Scientific Library gsl from Haskell.

solveOde fun x0 f0 xend =
  coerce $ solveOdeC (coerce fun) (coerce x0) (coerce f0) (coerce xend)

I'm trying to wrap more of gsl in Haskell and I try to understand every line of the example code. So why it uses Data.Coerce here?

1 Answers

The type of solveOdeC is almost the same as the type for solveOde. The former type involves CDouble at several points, including inside Vectors and Either. The latter instead uses Double.

The code relies on CDouble and Double having the same representation. Because of that, using coerce one can define a function by simply calling the other one with no runtime overhead. Without that, one would need to create a new Vector which would be bitwise identical to the first one only to satisfy the type checker, spending O(N) for this overhead.

To be honest, I find the definition in the library unnecessarily verbose. One could have written, instead,

solveOde = coerce solveOdeC
Related