# [racket-users] Re: table lookup shorthands?

On Monday, August 7, 2017 at 12:16:12 AM UTC+2, Jordan Johnson 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

Jordan, just to add one more thing just in case.

If you just need an alternative to the lookup table only for this function, you
could also rely on some math. In particular, since the number of semitones of a
perfect fifth (7) (the same holds for the number of semitones of a perfect
fourth if you want to use that fact) and 12 are co-primes I think you could use
what follows to compute the number you are looking for, basically a way to
express in a formula how many jumps of 7 steps in a clock of 12 positions you
need to do to go from point 0 (the C pitch-class) to your destination.

(modulo (* 7 p) 12)

where p stands for the pitch class passed to the function;

and then adapt and extend this as needed to get the kind of output you
mentioned.

--
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