I would like to define a generic function that gets the next value in a range. I have the following function definition:
nextValInRange :: (Enum a) => a -> a
nextValInRange = succ
The problem with the above definition is that for Fractional values, I would like to change the value succ function increments with. Instead of incrementing by 1.0, I would like succ to increment by 0.2. For example:
(succ 10.0) = 10.2, not 11.0
The problem is I still want the nextValInRange function to be for any value that is in Enum type class.
I could write:
nextValInRange :: (Enum a, Num a) => a -> a -> a
nextValInRange stepVal rangeVal = rangeVal + stepVal
but I do not want to add a Num type class restriction.
Is there some haskell voodoo that I can use to achieve this?
The other solution I can think of is to have 2 separate nextValInRange functions, 1 for Nums and another for normal Enums.
TIA
Essentially, no. You could get it to work with an additional typeclass and some scary LANGUAGE pragmas, but that would probably be more work than just defining instances for your own typeclass in the first place.
I would recommend using
enumFromToas Chris suggests, since that is solving basically the same problem that you are solving.However, you could just turn
nextValInRangeto a function provided by the caller. Suppose it is used in some code like this:Simply change the implicit Enum dictionary passing into an explicit function pass
Then you can pass in the
(+ 0.1)function for floats, andsuccfor whatever type you feel that is appropriate.