Alex Rivera | Logout

multiplication of different types in Haskell

Asked 2011-03-15T20:25:33.570
11

I'm new to haskell, and from time to time I bump into a problem I'll try to describe here in a few words. Imagine, I want to declare different types for different measures so Haskell type system would find errors in my formulas:

newtype Dist = Km Float
newtype Time = H Float
newtype Velocity = KmH Float

(/) :: Dist → Time → Velocity
(Km d) / (H t) = KmH (d / v)

(*) :: Velocity → Time → Dist
(KmH v) * (H t) = Km (v * t)

so, any time when I try to use wrong units of measures in my formulas the compiler would bite.

The problem is that I can't implement ad-hoc polimorphism like this. With this code I bring ambiguity - the complier can distinguish my operator * and the one defined in Prelude. Declaration of an instance of Num class also is not possible since I need different types in parameters.

I'm wondering how people solve the problem usually.

Thanks in advance!

Edit
Report

1 Answer

7

You can hide the usual (*) if you want, by

import Prelude hiding((*))

Or hide all of Num

import Prelude hiding(Num(..))

Then you can define your own multiplication, probably along the lines

class Mul a b c | a b -> c, b c -> a, c a -> b where
    (*) :: a -> b -> c
answered 2011-03-15T20:41:49.263

Your Answer