4 ms·
In Haskell I guess it would look like this: I'm still new to Haskell hopefully someone can improve it? data M = M1 | M2 | M3 deriving(Show, Eq, Ord) f
by meric 14y ago
In Haskell I guess it would look like this:
I'm still new to Haskell hopefully someone can improve it?
data M = M1 | M2 | M3 deriving(Show, Eq, Ord)
fromM M1 = 1
fromM M2 = 2
fromM M3 = 3
instance Num M where
abs = abs
a + b = fromInteger (mod ((fromM a) + (fromM b)) 3)
a * b = fromInteger (mod ((fromM a) * (fromM b)) 3)
a - b = fromInteger (mod (abs $ (fromM a) - (fromM b)) 3)
fromInteger 0 = M3
fromInteger 1 = M1
fromInteger 2 = M2
fromInteger 3 = M3
Is this what you're looking for? :)
- klodolph 14y agoA more generic version allows you to parameterize based on the bound: newtype BoundedInt b = BoundedInt Int class Bound b where boundRange :: t b -> (Int, Int) fromBounded :: BoundedInt b -> Int fromBounded (BoundedInt x) = x toBounded :: Bound b => Int -> BoundedInt b toBounded x = let result = BoundedInt x (minb, maxb) = boundRange result in if minb <= result && result <= maxb then result else error $ "Out of range: " ++ show x instance Bound b => Num (BoundedInt b) where abs = toBounded . abs . fromBounded negate = toBounded . negate . fromBounded signum = toBounded . signum . fromBounded x + y = toBounded (fromBounded x + fromBounded y) x - y = toBounded (fromBounded x - fromBounded y) x * y = toBounded (fromBounded x * fromBounded y) fromInteger = toBounded . fromInteger This assumes you want exceptions for overflow. Nowadays, you can put numbers in the type system, obviating the need for a "Bound" class, but I'm not familiar with it yet. The implementation above will also silently overflow given large enough bounds.
- wonderzombie 14y agoI'd ask, I suppose, why he wants ints from 1 to 3 in the first place. Why are these semantically important, and what's the intended meaning? If you just need a set of numbers which only has those three, a helper function with a modulus seems easier. Or an infinite list of [1,2,3]. But it's not clear to me what the use case is, so...