John Lam 1997 — 2026

Experiments with lambda functions

Lambda functions in Python, which are somewhat related to anonymous methods in C# can be really useful in certain situations.

In this example, I’m using lambda functions to define jump tables based on dictionaries. Using a single line of code, I can substitute arbitrary markup blocks in a “little” language that I defined for writing music. There are two markup characters: ! and #. ! lets me declare the tempo of the music, and # lets me declare the pitch of the note.

import re
import win32com.client

notes = dict([['c',65],['d',73],['e',82],['f',87],['g',98],['aa',110],['bbf',117],['cc',131]])
tempo = dict([['f',130],['s',55]])

re_markup = re.compile(r'([\#|\!])(\w+)', re.IGNORECASE)

markup = dict([['#', (lambda mo : '\\pit=%s\\' % notes[mo.group(2)])],
               ['!', (lambda mo : '\\spd=%s\\' % tempo[mo.group(2)])]])

def parseSong(song):
    return '\\chr=\"monotone\"\\' + re_markup.sub(lambda mo : markup[mo.group(1)](mo), song)

song = ['!f#c Hap- #c p #d birth-#c day !s#f to #e you.',
        '!f#c Hap- #c p #d birth-#c day !s#g to #f you.',
        '!f#c Hap- #c p #cc birth- #aa day !s#f to  #e Maa- #d foo.',
        '!f#bbf Hap- #bbf p #aa birth- #f day !s#g to #f you.']

agent = win32com.client.Dispatch("Agent.Control.2")
agent.Connected = -1
agent.Characters.Load("Peedy", "Peedy.acs")

peedy = agent.Characters("Peedy")
peedy.Height = 600
peedy.Width = 600
peedy.LanguageID = 0x409
peedy.Show()

for line in song:
    peedy.Speak(parseSong(line))

peedy.Hide()

I’m amazed that I can create in such a compact form a “little language” for writing a birthday song for my boy Matthew who will turn one on September 22. Note that this little sample program also uses COM to talk to Microsoft Agent via Mark Hammond’s most excellent win32com libraries (and IDE!)

Wow. Programming is becoming a lot of fun again.