[Haskell-cafe] Extending the idea of a general Num to other types?

Peter Verswyvelen bf3 at telenet.be
Sun Sep 2 06:13:12 EDT 2007


Chaddaï Fouché wrote:
> You can indeed already do that, except it won't be a single instance
> since list have a bucketful of interesting properties. A good starting
> is looking at what list is an instance of and trying to identify the
> set of instance which interest us in this case, Foldable and Functor
> are probably a good start, embodying most of the interesting way to
> access a data structure as a list (head and tail don't really make
> sense for most of the alternatives, except other "sequence" library
> which currently provide this functionality in an ad-hoc way, see
> Sequence and ByteString for example of that).
> An alternative is Traversable.
Thanks!

But before digging into this, maybe I should rephrase myself by giving a 
more specific (although useless) example of what I mean.

When I write:

data Foo = Foo Int Int deriving (Show,Eq)

instance Num Foo where
    fromInteger x = Foo x' x' where x' = fromInteger x
    _ + _ = error "Not relevant for example"
    _ * _  = error "Not relevant for example"
    abs _ = error "Not relevant for example"
    signum _ = error "Not relevant for example"

x = 42::Foo

I don't have to apply the Foo data constructor to lift the number 42 
because I guess the compiler has builtin support for calling fromInteger 
(or fromRational). I even don't have to add the type annotation most of 
the time when the compiler can infer the type needed, which is very 
cool, sometimes a bit annoying.

However, now I try the same for lists

data Bar = Bar [Int] [Int]

-- A List type class does not exist, so this cannot work
instance List Bar where
   fromList  x = Bar x x

-- This does not work
y = [1..10]::Bar

So the only way to do this, is to create a constructor function like

bar x = Bar x x

which means the usage of lists in Haskell is not as general as numbers, 
in the sense one cannot take advantage of the builtin syntactic sugar of 
lists like

[x,y,z] := x : (y : (z : []))

So if I would like to use this compact notation for e.g. creating a Set 
datatype, I would have to create special constructor functions (fromList 
or mkSet or whatever)

Is this correct? If so, I'm sure a good reason must exist for this :)

Thanks,
Peter







More information about the Haskell-Cafe mailing list