1

When writing FFI code in haskell, I often have Int and CInt variables mixed together. I tried to define a new type Intlike to help with defining constants that can be represented as values of either type, as follows:

type Intlike = forall a . (Num a, Integral a) => a
floatSize :: Intlike = fromIntegral $ sizeOf (1 :: CFloat)

Then GHCi complains so:

Fractal.hs:276:24-35: No instance for (Num Intlike) arising from \
                                         a use of ‘fromIntegral’ …
    In the expression: fromIntegral
    In the expression: fromIntegral $ sizeOf (1 :: CFloat)
    In a pattern binding:
      floatSize :: Intlike = fromIntegral $ sizeOf (1 :: CFloat)
Compilation failed.

(This is with the Rank2Types language extension.)

The following, however, works:

floatSize :: (Num a, Integral a) => a
floatSize = fromIntegral $ sizeOf (1 :: CFloat)

Is there a good solution that doesn't have me write fromIntegral all the time? What is the difference between Intlike and the one that works? They look similar.

1 Answer 1

2

I can't tell you why, but if you write

floatSize :: Intlike
floatSize = fromIntegral $ sizeOf (1 :: CFloat)

then it works just fine. One possibility is that the type annotation on the pattern variable is doing something other than what you expected (I've never really understood what those do). Note that your Num context is redundant, because Integral is a subclass of Num. As for fromIntegral, you will need that just about any time you need to switch between integral types. Another option is to use "generic" functions that give you what you need. For example, you could define

import Foreign.Storable (sizeOf, Storable)

genericSizeOf :: (Storable a, Integral b) => a -> b
genericSizeOf = fromIntegral . sizeOf

Side note: when using functions like sizeOf that take an argument solely for its type, I personally prefer to use undefined rather than an arbitrary value. So I'd write something like sizeOf (undefined::CInt) rather than sizeof (1::CInt). This makes it clear that it doesn't matter what value I'm passing in, and reduces the mental clutter of "What is this 1? What would happen if I changed it to 2?"


In the comments below, Boyd Stephen Smith, Jr., mentions another approach that is apparently to be preferred, although I have not yet read up on it.

8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.