[Haskell-beginners] Question about functors (or maybe not...)

Felipe Almeida Lessa felipe.lessa at gmail.com
Sat Mar 19 03:53:05 CET 2011


On Sat, Mar 19, 2011 at 2:00 AM, Patrick LeBoutillier
<patrick.leboutillier at gmail.com> wrote:
> Hi,
>
> I'm writing a music library and have the following types and functions:
>
> data Note = C | D | E | F | G | A | B | Sharp Note | Flat Note
> raise C = Sharp C
>
> data Quality = Major | Minor
>
> data Chord = Chord Quality Note  -- Note is the root
> data Scale = Scale Quality Note  -- Note is the tonic
>
> What I would like to do is to be able to lift the raise function and
> apply it to
> Chords and Scales. Something like this:
>
> fmap raise (Chord Major C) = Chord Major (Sharp C)
>
> But these are not functors as it doesn't seem to make sense for them to
> be polymorphic. A chord can't really made of anything except Notes.

You can write your own plain old functions:

mapChord :: (Note -> Note) -> Chord -> Chord
mapChord f (Chord q n) = Chord q (f n)

mapScale :: (Note -> Note) -> Scale -> Scale
mapScale f (Scale q n) = Scale q (f n)

You can also create your own type class, if that's convenient for you

class NoteMap a where
  noteMap :: (Note -> Note) -> a -> a

instance NoteMap Chord where noteMap = mapChord
instance NoteMap Scale where noteMap = mapScale

HTH, =)

-- 
Felipe.



More information about the Beginners mailing list