[Haskell-beginners] Type classes and synonyms
Philip Scott
haskell-beginners at foo.me.uk
Sat Nov 21 10:20:30 EST 2009
Hello all,
Quick one for you. I have a list of (<timestamp>,<value>) pairs, and I have
defined lots of nice functions for doing various tricks with them. I'd like to
define a custom data type which is an instance of 'Num' so I can conveniently
do arithmetic on them. (I have written some tools for merging two time series
etc...)
e.g.
t (x,y) = x
v (x,y) = y
mergeSkip _ [] = []
mergeSkip [] _ = []
mergeSkip (x:xs) (y:ys)
| t x == t y = ( t x, (v x, v y) ) : (mergeSkip xs ys)
| t x > t y = mergeSkip xs (y:ys)
| t x < t y = mergeSkip (x:xs) ys
binaryValueFunc f [] = []
binaryValueFunc f ((t,(a,b)):xs) = (t, f a b):binaryValueFunc f xs
add xs = binaryValueFunc (+) xs
addSkip xs ys = add $ mergeSkip xs ys
So addSkip will nicely take two of my time series, merge them by throwing out
any pairs which don't have a time stamp that exists in both and then add the
values to return a new series. All is well. But how do I make it so that I can
use the + operator to add two of them?
Well of course, I tried making a custom data type:
data Ts a b = Ts [(a,b)]
intance Ts Num where
<blaa blaa blaa>
But then I have to rewrite all of my functions to pattern match on Ts instead
of just the list. Worse, when I am writing recursive functions I have to
construct a Ts again for the recursive call. I guess I could make my own
'list-like' datastructure
data Ts a b = Empty
| Cons ((a,b), Ts)
But that seems rather clumsy.
So I tried to make 'Ts' a type synonym for [(a,b)] which worked, but then
I couldn't declare it an instance of 'Num'.
So I guess the question is, is there any way of making a type synonym for a
type which I can define as an instance of another class? So I can use my
values of the type synonym for functions which expect the 'vanilla' type, but
define 'extra' stuff my type synonym can do?
Any help or advice greatly appreciated.
- Philip
More information about the Beginners
mailing list