Question

Following on from my question here : How do I attach optional attributes to values?

I'm trying to define a Haskell representation of music.

I'd like to do something this :

data Chord = Chord Int Modality [Annotate] deriving (Eq, Show, Read)

which, as I understand defines a new type which is a Chord.

And then I want to be able to add Chords amongst other events to a Score such that

data Event = Note Int | Chord Int Modality [Annotate] | Rest

However, the compiler says I'm trying to define Chord twice.

So, is there a way to use an earlier defined data type inside a new data type definition? What I'm doing looks, to me, more or less like the classic Tree definition :

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)  

which works OK. So why is it ok to use "Tree" in this example, but not "Chord" in mine?

Was it helpful?

Solution

The problem is not about defining a type twice, but about defining the constructor Chord twice. You probably want

type Note = Int

data Event = NoteEvent Note | ChordEvent Chord | Rest

Alternatively, you can leave Event as is, but there you've basically inlined the entire definition of the Chord data type, so you don't need that anymore then.

OTHER TIPS

data Chord = Chord Int Modality [Annotate] deriving (Eq, Show, Read)

Note Chord is used twice here. The two occurrences are used for two different things.

data Chord =                       -- This one defines a new data type
     Chord Int Modality [Annotate] -- This one defines a new data constructor

It's OK to give the two things the same name because they exist in different namespaces.

data Event = Note Int | Chord Int Modality [Annotate] | Rest

Now you are trying to define another data constructor named Chord, which is a no-no. Data constructors must be unique across all data types in the module. If you want to use the Chord type here, use it like this:

data Event = NoteEvent Int    | -- A new data constructor, then optionally type(s)
             ChordEvent Chord | -- A new data constructor, then optionally type(s)
             OtherEvent         -- A new data constructor, then optionally type(s)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top