How would you implement Instant and Interval

Hello all If I define an Instant as a point in Time and an Interval as the difference between two Instants, and I also want to use (+) and (-), how can I do this. My initial thought making them instances of the Num class, but that does not work. (-) is okay on Intervals, but on Instant it returns a different type (Interval). Is it possible at all to define a typeclass with (-) :: Instant -> Instant -> Interval without using language extensions?

Would this package help: http://hackage.haskell.org/package/time-interval ?

On 2015-10-27 at 13:53, martin
Hello all
If I define an Instant as a point in Time and an Interval as the difference between two Instants, and I also want to use (+) and (-), how can I do this.
My initial thought making them instances of the Num class, but that does not work. (-) is okay on Intervals, but on Instant it returns a different type (Interval).
Is it possible at all to define a typeclass with (-) :: Instant -> Instant -> Interval without using language extensions?
I think you are asking for the same type class function to have the types `Instant -> Instant -> Interval` and `Interval -> Interval -> Interval` for two different instances. I don't believe this is possible without language extensions. Below is an example of doing it with TypeFamilies. If I actually wanted this, I'd probably use the Affine class from linear[1] or vector-space[2] instead of the Sub class I define here. At any event, I don't think I'd want to give up on using - in it's normal meaning of Num, in order to use it for Time and Interval. newtype Time = Time Double deriving Show newtype Interval = Interval Double deriving Show class Sub a where type Diff a (.-.) :: a -> a -> Diff a instance Sub Time where type Diff Time = Interval (Time a) .-. (Time b) = Interval (a - b) instance Sub Interval where type Diff Interval = Interval (Interval a) .-. (Interval b) = Interval (a - b) Footnotes: [1] http://hackage.haskell.org/package/linear-1.20.2/docs/Linear-Affine.html [2] http://hackage.haskell.org/package/vector-space-0.10.2/docs/Data-AffineSpace...
participants (3)
-
Daniel Bergey
-
Imants Cekusins
-
martin