> On Aug 6, 2017, at 6:16 PM, Jordan Johnson <j...@fellowhuman.com> wrote:
> 
> Hi all,
> 
> I’m writing some music-related code for which I find myself using a lot of 
> lookup tables, following the pattern of making an alist or hash table and 
> then writing a function that consults the table. I wound up writing a macro 
> for this pattern; one example of its use is:
> 
> ;; key->fifths : PitchName -> Int[-7..7]
> ;; tells how many perfect fifths above C the given pitch is (and
> ;; therefore how many sharps or flats its key signature has)
> (define-lookup-function key->fifths
>  [C 0] [G 1] [D 2] [A 3] [E 4] [B 5]
>  [F# 6] [F♯ 6]
>  [C# 7] [C♯ 7]
>  [F -1]
>  [Bb -2] [Eb -3] [Ab -4] [Db -5] [Gb -6] [Cb -7]
>  [B♭ -2] [E♭ -3] [A♭ -4] [D♭ -5] [G♭ -6] [C♭ -7])
> ;; Ex:
> (key->fifths 'Gb) ;; -> -6
> 
> This seems like a simple and common enough pattern that there must be such a 
> facility in some Racket library out there already, but I haven’t found one. 
> Am I reinventing a wheel here?
> 
> Thanks,
> Jordan

What I've done for situations like these is define notes like C and D not as 
symbols, but as data structures that contain the numbers you need. So for 
instance I would define:

(struct pitch-class [chromatic-number])

(define C (pitch-class 0))
(define C#/D♭ (pitch-class 1))
(define D (pitch-class 2))
(define D#/E♭ (pitch-class 3))
(define E (pitch-class 4))
(define F (pitch-class 5))
etc.

When the notes are defined like this, the number of fifths can be a 
mathematical function instead of a lookup, if you can find the function that 
maps chromatic numbers to fifths.
  

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to