I am attempting to write a function using UArrays that are very general. I would like the type signature:
myFunction :: a -> b -> ((UArray Int a), (UArray Int b))
However, a and b are too general. I would like them to be one of the possible instances of IArray UArray a. Is there some deriving type that will allow me to specify this? For example, if Num were a valid instance I could do:
myFunction :: (Num a, Num b) => a -> b -> ((UArray Int a), (UArray Int b))
Does it make sense what I am trying to do?
Thanks in advance!
We need to repeat constraints from array methods you are going to use, such as
arrayetc. Since your indexes are fixed and we know they’re instance ofIx, we only need to addIArrayconstraints:For this, you need the FlexibleContexts (see section 7.6.3.2. Relaxed rules for instance contexts) language extension.
You could also think about generalizing your function to arbitrary arrays (not just
UArraysor perhaps even to arbitrary indexes:
(For these 2 variants, you don’t need the extension.)
Since probably you’re using
UArrays for speed, I’d suggest addingINLINEpragma so that your function gets optimized for the particular data types at the place you use it. That can make a significant speed improvement.