[Haskell-beginners] Type classes and synonyms

John Dorsey haskell at colquitt.org
Sat Nov 21 16:23:26 EST 2009


Philip,

> I merge my lists into a list of pairs before I do anything with them so 
> unevenness isn't a problem; I was just trying t convince haskell that I could 
> use nice operators like '+' on my derived type.

There's another way to use nice operators like '+', in cases where the type
you're using it with just doesn't make sense as an instance of Class Num.

(I think there's an argument that your [(date,value)] type isn't a number
and shouldn't be a Num, but I'm not going to go there.)

Every module can have its own definition for each name, such as the operator
(+).  So in your module (eg. module Main, or module DateValueSeries), you
can go ahead and define your own (+).  The major caveat is making sure you
don't conflict with the default (+), which lives in module Prelude, which is
normally automatically brought into scope.

So you could do this:

-- file DateValueSeries.hs

module DateValueSeries where

import Prelude hiding ((+))

(+) :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]
(+) = addSkip

addSkip = ...


-- file main.hs

import Prelude hiding ((+))
import DateValueSeries

dvlist1 = [(0,100)]
dvlist2 = ...
dvlist3 = dvlist1 + dvlist2

The code is incomplete and untested, of course.

The basic idea is that you can use (+) for something that isn't exactly
addition (although you're choosing that name because it's clearly related to
addition).  Unlike the examples using Class Num your (+) has nothing to do
with the normal (+); it just has the same name.

John



More information about the Beginners mailing list