If composers were hackers

  2023-04-01

Introduction

Music is my first true loveComputer games are my zeroeth true love.. The first time I got my hands on an old untuned guitar, I didn’t want to put it down. I found a summer job to buy my first instrument and pay for a teacher, and since then, music has been a constant source of joy in my life. Picking a degree in computer science at a university over a musical college education was a hard choice for me.

I can’t help but look at the world through my musical obsession. There are many deep similarities between music and computing but we won’t explore them in this article. Instead, I will focus on a silly and subjective question: If my favorite composers decided to write some code, which language would they pick?

Johan Sebastian Bach

Johan Sebastian Bach is the most talented and prolific musician in history.

Bach would love the APL programming language:

  • Like a well-written APL program, Bach’s music is dense. He achieves immense expressive power with a few well-chosen constructs.
  • In his lifetime, Bach was famous not for his compositions, but for his improvisation skills. APL is an excellent fit for live coding because of its interactivity and terseness.
  • Motifs and keys bear deep symbolic and emotional meaning in Bach’s music. A twisted motif might mean a crucifixion and a sequence of twelve beats might depict a clock striking midnight. APL assigns ingeniously-chosen symbols to all its primitives.
  • Bach’s productivity was phenomenal. For example, he was cranking at least one cantata (about 20 minutes of music) per week for church services on Sundays for over three years, writing over three hundred cantatas. And it wasn’t even his primary duty. Tell me about your tight deadlines. The only programmer who can come close to this level of productivity must be an over-caffeinated APL wizard.
  • The Voyager Golden Record contains three compositions by Bach. If we wanted to prove to aliens that we know how to compute, APL would be the best choice for writing programs on golden surfaces.
Representative Bach’s music: Wachet auf, ruft uns die Stimme, a deeply moving and masterfully harmonized choral.
An APL function computing 2n Gray codes for the given number n. This code comes from A History of APL in 50 functions by Roger K.W. Hui. Try it yourself!
{(0∘, ⍪ 1∘,∘⊖)⍣⍵⍉⍪⍬}

Resources

If you want to learn more about J.S. Bach:

If you want to learn more about APL:

Wolfgang Amadeus Mozart

Mozart’s musical genius was so bright and incomprehensible that mysteries and myths still surround his life.

Mozart would prefer the Scheme programming language.

  • Mozart’s music reflects the values of the age of enlightenment and appeals to everyone. It’s clean and beautifully constructed. Scheme is so simple that a few pages can introduce most of the language. Before the recent switch to Python, MIT professors used Scheme for introductory Computer Science classes.
  • Mozart wrote music in all genres of his time (though he loved theater and opera the most). Scheme is a programmable programming language; it is flexible enough to be helpful in any domain. See Racket and "The Little X" books in the Resources section.
Representative Mozart’s music: Piano Sonata 5 in G-major, featuring a joyful melody and with a simple but elegant arrangement.
Symbolic differentiation in Scheme (example 2.3.2 in SICP).
(define (deriv exp var)
  (cond ((number? exp) 0)
        ((variable? exp)
         (if (same-variable? exp var) 1 0))
        ((sum? exp)
         (make-sum (deriv (addend exp) var)
                   (deriv (augend exp) var)))
        ((product? exp)
         (make-sum
           (make-product (multiplier exp)
                         (deriv (multiplicand exp) var))
           (make-product (deriv (multiplier exp) var)
                         (multiplicand exp))))
        (else
         (error "unknown expression type -- DERIV" exp))))

Resources

If you want to learn more about Mozart:

If you want to learn more about Scheme:

Ludwig van Beethoven

Beethoven is the most influential composer in history. He single-handedly changed the direction of western music and the role of an artist in society.

One of the few languages worthy of Beethoven would be Haskell:

  • Beethoven often constructed his music from the interaction and development of small motifs and rhythms, many of which initially seem trivial. The art of writing good Haskell code is composing programs from small functions, many of which do not do much when considered in isolation (id and fix, for example).
  • Beethoven was constantly evolving his style, pushing the boundary of musical art. He reinvented himself three times during his career, turning his suffering into fuel for a breakthrough. Similarly, the Haskell ecosystem constantly evolves, turning pain points into new beautiful ways to write and think about software. For example, issues with lazy input/output led to the invention of iteratees, and problems with nested record updates led to optics (such as lenses) and bidirectional programming.
  • Beethoven turned my musical world upside down: I caught a piano bug after hearing one of his sonatas. Haskell enormously influenced my professional life, forever changing my thoughts about computing.
Representative Beethoven’s music: Sonata op. 13 in C minor, also known as the Pathétique Sonata. Note the operatic dramatism, the masterful use of piano’s sonority, and Beethoven’s way of building music landscapes from tiny memorable motifs and rhythms.
An idiomatic implementation of the Knuth-Morris-Pratt algorithm in Haskell. The code comes from the Knuth-Morris-Pratt in Haskell article by Twan van Laarhoven.
data KMP a = KMP { done :: Bool, next :: (a -> KMP a) }

makeTable :: Eq a => [a] -> KMP a
makeTable xs = table
   where table = makeTable' xs (const table)

makeTable' []     failure = KMP True failure
makeTable' (x:xs) failure = KMP False test
   where  test  c = if c == x then success else failure c
          success = makeTable' xs (next (failure x))

isSublistOf :: Eq a => [a] -> [a] -> Bool
isSublistOf as bs = match (makeTable as) bs
   where  match table []     = done table
          match table (b:bs) = done table || match (next table b) bs

Resources

If you want to learn more about Beethoven:

If you want to learn more about Haskell:

Alexander Nikolayevich Scriabin

Scriabin is a relatively obscure (at least outside of Russia) Russian composer. I find his music deeply expressive, emotional, and metaphysical. Also, he had the most stylish mustache ever.

Scriabin would love Scala:

  • Scriabin dreamed of fusing arts into a synthetic art form he called Mysterium. Similarly, Scala aims to be extensible enough to embrace all programming styles and paradigms (functional, object-oriented, actor-based, etc.).
  • Scriabin’s music feels profound and unfathomable, like the night sky. Looking at Scala code makes me feel the same awe: I admire its structure and elegance, but its inherent complexity makes my head spin.
Representative Scriabin’s music: Prelude in C#-minor from op. 11, one of my favorite short piano pieces.
The Scala way of saying that optional values are just an instance of a monoid in the category of endofunctors. This snippet comes from the scalaz library documentation.
implicit val option: Traverse[Option] with MonadPlus[Option] =
  new Traverse[Option] with MonadPlus[Option] {
    def point[A](a: => A) = Some(a)
    def bind[A, B](fa: Option[A])(f: A => Option[B]): Option[B] = fa flatMap f
    override def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa map f
    def traverseImpl[F[_], A, B](fa: Option[A])(f: A => F[B])(implicit F: Applicative[F]) =
      fa map (a => F.map(f(a))(Some(_): Option[B])) getOrElse F.point(None)
    def empty[A]: Option[A] = None
    def plus[A](a: Option[A], b: => Option[A]) = a orElse b
    def foldR[A, B](fa: Option[A], z: B)(f: (A) => (=> B) => B): B = fa match {
      case Some(a) => f(a)(z)
      case None => z
    }
}

Resources

If you want to learn more about Scriabin:

If you want to learn more about Scala:

Closing words

There are many more great composers and excellent programming languages. Matching these is an exercise for the reader.

I encourage you to think more often about things and people you like and match them with others. For example, My Favorite Theorem podcast hosts ask their guests to match their favorite theorems with items and activities in their lives, such as pizza and rock climbing.

Enjoy your favorite things!