Lambda
 Volume Number: 9 Issue Number: 9 Column Tag: Lisp Listener

Mutual Recursion

By André van Meulebrouck, Chatsworth, California

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

“Mathematics is thought moving in the sphere of complete abstraction from any particular instance of what it is talking about.” - Alfred North Whitehead

Welcome once again to Mutual of Omo Oz Y Old Kingdom (with apologies to the similar named TV series of yesteryears).

In this installment, Lambda, the forbidden (in conventional languages) function, does the lambada-the forbidden (in l-calculus) dance. Film at 11.

In [vanMeule Jun 91] the question was raised as to whether everything needed to create a metacircular interpreter (using combinators) has been given to the reader.

One of the last (if not the last) remaining items not yet presented is mutual recursion, which allows an interpreter’s eval and apply functions to do their curious tango (the “lambda lambada”?!?).

In this article, the derivation of a Y2 function will be shown. Y2 herein will be the sister combinator of Y, to be used for handling mutual recursion (of two functions) in the applicative order. The derivation of Y2 will be done in a similar manner as was done for deriving Y from pass-fact in [vanMeule May 92].

This exercise will hopefully give novel insights into Computer Science and the art of programming. (This is the stuff of Überprogrammers!) This exercise should also give the reader a much deeper understanding of Scheme while developing programming muscles in ways that conventional programming won’t.

Backdrop and motivation

[vanMeule Jun 91] described the minimalist game. The minimalist game is an attempt to program in Scheme using only those features of Scheme that have more or less direct counterparts in l-calculus. The aim of the minimalist game is (among other things):

1) To understand l-calculus and what it has to say about Computer Science.

2) To develop expressive skills. Part of the theory behind the minimalist game is that one’s expressive ability is not so much posited in how many programming constructs one knows, but in how cleverly one wields them. Hence, by deliberately limiting oneself to a restricted set of constructs, one is forced to exercise one’s expressive muscles in ways they would not normally get exercised when one has a large repertoire of constructs to choose from. The maxim here is: “learn few constructs, but learn them well”.

In l-calculus (and hence the minimalist game) there is no recursion. It turns out that recursion is a rather impure contortion in many ways! However, recursion can be simulated by making use of the higher order nature of l-calculus. A higher order function is a function which is either passed as an argument (to another function) or returned as a value. As thrifty as l-calculus is, it does have higher order functions, which is no small thing as very few conventional languages have such a capability, and those that do have it have only a very weak version of it. (This is one of the programming lessons to be learned from playing the minimalist game: The enormous power of higher order functions and the losses conventional languages suffer from not having them.)

Different kinds of recursion

As soon as a language has global functions or procedures and parameter passing provided via a stack discipline, you’ve got recursion! In fact, there is essentially no difference between a procedure calling itself or calling a different function-the same stack machinery that handles the one case will automatically handle the other. (There’s no need for the stack machinery to know nor care whether the user is calling other procedures or the same procedure.)

However, as soon as a language has local procedures, it makes a very big difference if a procedure calls itself! The problem is that when a local procedure sees a call to itself from within itself, by the rules of lexical scoping, it must look for its own definition outside of its own scope! This is because the symbol naming the recursive function is a free variable with respect to the context it occurs in.

```; 1
>>> (let ((local-fact
(lambda (n)
(if (zero? n)
1
(* n (local-fact (1- n)))))))
(local-fact 5))
```
```ERROR:  Undefined global variable
local-fact

Entering debugger.  Enter ? for help.
debug:>
```

This is where letrec comes in.

```; 2

>>> (letrec ((local-fact
(lambda (n)
(if (zero? n)
1
(* n (local-fact (1- n)))))))
(local-fact 5))
120
```

To understand what letrec is doing let’s translate it to its semantic equivalent. letrec can be simulated using let and set! [CR 91].

```; 3
>>> (let ((local-fact ‘undefined))
(begin
(set! local-fact
(lambda (n)
(if (zero? n)
1
(* n (local-fact (1- n))))))
(local-fact 5)))
120
```

Mutual recursion is slightly different from “regular” recursion: instead of a function calling itself, it calls a different function that then calls the original function. For instance, “foo” and “fido” would be mutually recursive if foo called fido, and fido called foo. The letrec trick will work fine for mutual recursion.

```; 4

>>> (let ((my-even? ‘undefined)
(my-odd? ‘undefined))
(begin
(set! my-even?
(lambda (n)
(if (zero? n)
#t
(my-odd? (1- n)))))
(set! my-odd?
(lambda (n)
(if (zero? n)
#f
(my-even? (1- n)))))
(my-even? 80)))
#t
```

The reason this works is because both functions that had to have mutual knowledge of each other were defined as symbols in a lexical context outside of the context in which the definitions were evaluated.

However, all the above letrec examples rely on being able to modify state. l-calculus doesn’t allow state to be modified. (An aside: since parallel machines have similar problems and restrictions in dealing with state, there is ample motivation for finding non-state oriented solutions to such problems in l-calculus.)

The recursion in local-fact can be ridded by using the Y combinator. However, in the my-even? and my-odd? example the Y trick doesn’t work because in trying to eliminate recursion using Y, the mutual nature of the functions causes us to get into a chicken-before-the-egg dilemma.

It’s clear we need a special kind of Y for this situation. Let’s call it Y2.

The pass-fact trick

[vanMeule May 92] derived the Y combinator in the style of [Gabriel 88] by starting with pass-fact (a version of the factorial function which avoids recursion by passing its own definition as an argument) and massaging it into two parts: a recursionless recursion mechanism and an abstracted version of the factorial function.

Let’s try the same trick for Y2, using my-even? and my-odd? as our starting point.

First, we want to massage my-even? and my-odd? into something that looks like pass-fact. Here’s what our “template” looks like:

```; 5

>>> (define pass-fact
(lambda (f n)
(if (zero? n)
1
(* n (f f (1- n))))))
```
```pass-fact
>>> (pass-fact pass-fact 5)
120
```

Here’s a version of my-even? and my-odd? modeled after the pass-fact “template”.

```; 6
>>> (define even-odd
(cons
(lambda (function-list)
(lambda (n)
(if (zero? n)
#t
(((cdr function-list) function-list)
(1- n)))))
(lambda (function-list)
(lambda (n)
(if (zero? n)
#f
(((car function-list) function-list)
(1- n)))))))
even-odd
>>> (define pass-even?
((car even-odd) even-odd))
pass-even?
>>> (define pass-odd?
((cdr even-odd) even-odd))
pass-odd?
>>> (pass-even? 8)
#t
```

This could derive one crazy!

Now that we know we can use higher order functions to get rid of the mutual recursion in my-even? and my-odd? the next step is to massage out the recursionless mutual recursion mechanism from the definitional parts that came from my-even? and my-odd?. The following is the code of such a derivation, including test cases and comments.

```; 7
(define my-even?
(lambda (n)
(if (zero? n)
#t
(my-odd? (1- n)))))
;
(define my-odd?
(lambda (n)
(if (zero? n)
#f
(my-even? (1- n)))))
;
(my-even? 5)
;
; Get out of global environment-use local environment.
;
(define mutual-even?
(letrec
((my-even? (lambda (n)
(if (zero? n)
#t
(my-odd? (1- n)))))
(my-odd? (lambda (n)
(if (zero? n)
#f
(my-even? (1- n))))))
my-even?))
;
(mutual-even? 5)
;
; Get rid of destructive letrec.  Use let instead.
; Make a list of the mutually recursive functions.
;
(define mutual-even?
(lambda (n)
(let
((function-list
(cons (lambda (functions n) ; even?
(if (zero? n)
#t
((cdr functions) functions
(1- n))))
(lambda (functions n) ; odd?
(if (zero? n)
#f
((car functions) functions
(1- n)))))))
((car function-list) function-list n))))
;
(mutual-even? 5)
;
; Curry, and get rid of initial (lambda (n) ...) .
;
(define mutual-even?
(let
((function-list
(cons (lambda (functions) ; even?
(lambda (n)
(if (zero? n)
#t
(((cdr functions) functions)
(1- n)))))
(lambda (functions) ; odd?
(lambda (n)
(if (zero? n)
#f
(((car functions) functions)
(1- n))))))))
((car function-list) function-list)))
;
(mutual-even? 5)
;
; Abstract ((cdr functions) functions) out of if, etc..
;
(define mutual-even?
(let
((function-list
(cons (lambda (functions)
(lambda (n)
((lambda (f)
(if (zero? n)
#t
(f (1- n))))
((cdr functions) functions))))
(lambda (functions)
(lambda (n)
((lambda (f)
(if (zero? n)
#f
(f (1- n))))
((car functions) functions)))))))
((car function-list) function-list)))
;
(mutual-even? 5)
;
; Massage functions into abstracted versions of
; originals.
;
(define mutual-even?
(let
((function-list
(cons (lambda (functions)
(lambda (n)
(((lambda (f)
(lambda (n)
(if (zero? n)
#t
(f (1- n)))))
((cdr functions) functions))
n)))
(lambda (functions)
(lambda (n)
(((lambda (f)
(lambda (n)
(if (zero? n)
#f
(f (1- n)))))
((car functions) functions))
n))))))
((car function-list) function-list)))
;
(mutual-even? 5)
;
; Separate abstracted functions out from recursive
; mechanism.
;
(define mutual-even?
(let
((abstracted-functions
(cons (lambda (f)
(lambda (n)
(if (zero? n)
#t
(f (1- n)))))
(lambda (f)
(lambda (n)
(if (zero? n)
#f
(f (1- n))))))))
(let
((function-list
(cons (lambda (functions)
(lambda (n)
(((car abstracted-functions)
((cdr functions) functions))
n)))
(lambda (functions)
(lambda (n)
(((cdr abstracted-functions)
((car functions) functions))
n))))))
((car function-list) function-list))))
;
(mutual-even? 5)
;
; Abstract out variable abstracted-functions in 2nd let.
;
(define mutual-even?
(let
((abstracted-functions
(cons (lambda (f)
(lambda (n)
(if (zero? n)
#t
(f (1- n)))))
(lambda (f)
(lambda (n)
(if (zero? n)
#f
(f (1- n))))))))
((lambda (abstracted-functions)
(let
((function-list
(cons (lambda (functions)
(lambda (n)
(((car abstracted-functions)
((cdr functions) functions))
n)))
(lambda (functions)
(lambda (n)
(((cdr abstracted-functions)
((car functions) functions))
n))))))
((car function-list) function-list)))
abstracted-functions)))
;
(mutual-even? 5)
;
; Separate recursion mechanism into separate function.
;
(define y2
(lambda (abstracted-functions)
(let
((function-list
(cons (lambda (functions)
(lambda (n)
(((car abstracted-functions)
((cdr functions) functions))
n)))
(lambda (functions)
(lambda (n)
(((cdr abstracted-functions)
((car functions) functions))
n))))))
((car function-list) function-list))))
;
(define mutual-even?
(y2
(cons (lambda (f)
(lambda (n)
(if (zero? n)
#t
(f (1- n)))))
(lambda (f)
(lambda (n)
(if (zero? n)
#f
(f (1- n))))))))
;
(mutual-even? 5)
;
; y2 has selector built into it-generalize it!
;
(define y2-choose
(lambda (abstracted-functions)
(lambda (selector)
(let
((function-list
(cons (lambda (functions)
(lambda (n)
(((car abstracted-functions)
((cdr functions) functions))
n)))
(lambda (functions)
(lambda (n)
(((cdr abstracted-functions)
((car functions) functions))
n))))))
((selector function-list) function-list)))))
;
; Now we can achieve the desired result-defining
; both mutual-even? and mutual-odd? without recursion.
;
(define mutual-even-odd?
(y2-choose
(cons (lambda (f)
(lambda (n)
(if (zero? n)
#t
(f (1- n)))))
(lambda (f)
(lambda (n)
(if (zero? n)
#f
(f (1- n))))))))
;
(define mutual-even?
(mutual-even-odd? car))
;
(define mutual-odd?
(mutual-even-odd? cdr))
;
(mutual-even? 5)
(mutual-odd? 5)
(mutual-even? 4)
(mutual-odd? 4)
```

Deriving Mutual Satisfaction

Notice that mutual-even? and mutual-odd? could have been defined using y2 instead of y2-choose, however, the definitional bodies of my-even? and my-odd? would have been repeated in defining mutual-even? and mutual-odd?.

• Herein Y2 was derived from mutual-even?. Try deriving it instead from pass-even?.

• Question for the Überprogrammer: if evaluation were normal order rather than applicative order, could we use the same version of Y for mutually recursive functions that we used for “regular” recursive functions (thus making a Y2 function unnecessary)?

• Another question: Let’s say we have 3 or more functions which are mutually recursive. What do we need to handle this situation when evaluation is applicative order? What about in normal order? (Note: evaluation in l-calculus is normal order.)

Creating a “minimalist” (i.e., combinator based) metacircular interpreter might now be possible if we can tackle the problem of manipulating state!

Thanks to:

The local great horned owls that watch over everything from on high; regularly letting fellow “night owls” know that all is well by bellowing their calming, reassuring “Who-w-h-o-o” sounds.

Bugs/infelicities due to: burning too much midnite oil!

Bibliography and References

[CR 91] William Clinger and Jonathan Rees (editors). “Revised4 Report on the Algorithmic Language Scheme”, LISP Pointers, SIGPLAN Special Interest Publication on LISP, Volume IV, Number 3, July-September, 1991. ACM Press.

[Gabriel 88] Richard P. Gabriel. “The Why of Y”, LISP Pointers, Vol. II, Number 2, October-November-December, 1988.

[vanMeule May 91] André van Meulebrouck. “A Calculus for the Algebraic-like Manipulation of Computer Code” (Lambda Calculus), MacTutor, Anaheim, CA, May 1991.

[vanMeule Jun 91] André van Meulebrouck. “Going Back to Church” (Church numerals.), MacTutor, Anaheim, CA, June 1991.

[vanMeule May 92] André van Meulebrouck. “Deriving Miss Daze Y”, (Deriving Y), MacTutor, Los Angeles, CA, April/May 1992.

Community Search:
MacTech Search:

Garmin Express 7.0.0.0 - Manage your Gar...
Garmin Express is your essential tool for managing your Garmin devices. Update maps, golf courses and device software. You can even register your device. Update maps Update software Register your... Read more
VMware Fusion 11.5.5 - Run Windows apps...
VMware Fusion and Fusion Pro - virtualization software for running Windows, Linux, and other systems on a Mac without rebooting. The latest version includes full support for Windows 10, macOS Mojave... Read more
Civilization VI 1.3.0 - Next iteration o...
Civilization® VI is the award-winning experience. Expand your empire across the map, advance your culture, and compete against history’s greatest leaders to build a civilization that will stand the... Read more
Google Earth 7.3.3.7721 - View and contr...
Google Earth gives you a wealth of imagery and geographic information. Explore destinations like Maui and Paris, or browse content from Wikipedia, National Geographic, and more. Google Earth combines... Read more
Corel Painter 20.1.0.285 - Digital art s...
OmniFocus 3.8 - GTD task manager with iO...
OmniFocus is an organizer app. It uses projects to organize tasks naturally, and then add tags to organize across projects. Easily enter tasks when you’re on the go, and process them when you have... Read more
Hazel 4.4.5 - Create rules for organizin...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a familiar... Read more
Macs Fan Control 1.5.7 - Monitor and con...
Macs Fan Control allows you to monitor and control almost any aspect of your computer's fans, with support for controlling fan speed, temperature sensors pane, menu-bar icon, and autostart with... Read more

Latest Forum Discussions

Dungonian is a card-based dungeon crawle...
Dungonian is a card-based dungeon crawler from developer SandFish Games that only recently launched as a free-to-play title. It offers an extensive roster of playable heroes to collect and enemies to take down, and it's available right now for iOS... | Read more »
Steam Link Spotlight - Signs of the Sojo...
Steam Link Spotlight is a feature where we look at PC games that play exceptionally well using the Steam Link app. Our last entry was XCOM: Chimera Squad. Read about how it plays using Steam Link's new mouse and keyboard support over here. | Read more »
Steampunk Tower 2, DreamGate's sequ...
Steampunk Tower 2 is a DreamGate's follow up to their previous tower defence game. It's available now for both iOS and Android as a free-to-play title and will see players defending their lone base by kitting it out with a variety of turrets. [... | Read more »
Clash Royale: The Road to Legendary Aren...
Supercell recently celebrated its 10th anniversary and their best title, Clash Royale, is as good as it's ever been. Even for lapsed players, returning to the game is as easy as can be. If you want to join us in picking the game back up, we've put... | Read more »
Pokemon Go Fest 2020 will be a virtual e...
Niantic has announced that Pokemon Go Fest will still take place this year although understandably it won't be a physical event. Instead, it will become a virtual celebration and is set to be held on 25th and 26th July. [Read more] | Read more »
Marvel Future Fight's major May upd...
Marvel Future Fight's latest update has now landed, and it sounds like a big one. The focus this time around is on Marvel's Guardians of the Galaxy, and it introduces all-new characters, quests, and uniforms for players to collect. [Read more] | Read more »
SINoALICE, Yoko Taro and Pokelabo's...
Yoko Taro and developer Pokelabo's SINoALICE has now opened for pre-registration over on the App Store. It's already amassed 1.5 million Android pre-registrations, and it's currently slated to launch on July 1st. [Read more] | Read more »
Masketeers: Idle Has Fallen is the latest endeavour from Appxplore, the folks behind Crab War, Thor: War of Tapnarok and Light A Way. It's an idle RPG that's currently available for Android in Early Access and will head to iOS at a later date. [... | Read more »
Evil Hunter Tycoon celebrates 2 million...
Evil Hunter Tycoon has proved to be quite the hit since launching back in March, with its most recent milestone being 2 million downloads. To celebrate the achievement, developer Super Planet has released a new updated called Darkness' Front Yard... | Read more »
Peak's Edge is an intriguing roguel...
Peak's Edge is an upcoming roguelike puzzle game from developer Kenny Sun that's heading for both iOS and Android on June 4th as a free-to-play title. It will see players rolling a pyramid shape through a variety of different levels. [Read more] | Read more »

Price Scanner via MacPrices.net

Sale! \$200 off on select 2020 13″ MacBook Pro...
Amazon has select 2020 13″ MacBook Pro configurations on sale today for \$200 off Apple’s MSRP. Shipping is free. Be sure to purchase the MacBook Pro from Amazon, rather than a third-party seller, and... Read more
June 1 only: \$100 off Apple’s iPhones at Boos...
Boost Mobile is offering Apple iPhone 11, 11 Pro, and iPhone 11 Pro Max models for \$100 off MSRP with service. Their discount reduces the cost of an iPhone 11/64GB to \$599, iPhone 11 Pro to \$899 for... Read more
Sams Club Sales Event: \$100 off every Apple W...
Sams Club is discounting all Apple Watch Series 5 models by \$100 off Apple’s MSRP through June 3, 2020. Choose free shipping or free local store pickup (if available). Sale prices for online orders... Read more
New 16″ MacBook Pros now on sale for up to \$2...
Apple reseller DataVision is now offering new 16″ Apple MacBook Pros for up to \$255 off MSRP, each including free shipping. Prices start at \$2194. DataVision charges sales tax for NY, NJ, PA, and CA... Read more
Apple now offering Certified Refurbished iPho...
Apple is now offering Certified Refurbished iPhone Xr models in the refurbished section of their online store starting at \$499. Each iPhone comes with Apple’s standard one-year warranty, ships free,... Read more
Sale! Get a 10.2″ 32GB WiFi iPad for only \$27...
Walmart has new 10.2″ 32GB WiFi iPads on sale for \$50 off Apple’s MSRP, only \$279. These are the same iPads sold by Apple in their retail and online stores. Be sure to select Walmart as the seller... Read more
Apple resellers offer new 2020 Mac minis for...
Apple resellers are offering new 2020 Mac minis for up to \$50 off Apple’s MSRP with prices available starting at \$759. Shipping is free: (1) B&H Photo: – 2020 4-Core Mac mini: \$759 \$40 off MSRP... Read more
Sprint is offering the Apple iPhone 11 free t...
Did you miss out on Sprint’s recent free iPhone SE promotion? No worries. Sprint has the 64GB iPhone 11 available for \$0 per month for new lines when you trade-in a qualifying phone in any condition... Read more
Apple has clearance 2019 13″ 1.4GHz MacBook P...
Apple has Certified Refurbished 2019 13″ 1.4GHz 4-Core Touch Bar MacBook Pros available today starting at \$979 and up to \$440 off original MSRP. Apple’s one-year warranty is included, shipping is... Read more
Apple restocks 2019 MacBook Airs starting at...
Apple has clearance, Certified Refurbished, 2019 13″ MacBook Airs available again starting at \$779. Each MacBook features a new outer case, comes with a standard Apple one-year warranty, and is... Read more

Jobs Board

*Apple* Mac Desktop Support - Global Dimensi...
…Operate and support an Active Directory (AD) server-client environment for all Apple devices operating on the BUMED network + Leverage necessary industry enterprise Read more
Surgical Technologist III, *Apple* Hill Sur...
Surgical Technologist III, Apple Hill Surgical Center - Full Time Tracking Code D5.29.2020 Job Description Surgical Technologist III Apple Hill Surgical Center Read more
Security Officer - *Apple* Store - NANA (Un...
**Security Officer \- Apple Store** **Description** About NMS Built on a culture of safety and integrity, NMSdelivers award\-winning, integrated support services to Read more
Transition Into Practice Program (TIP) - Sept...
…Academy-Transition into Practice (TIP) Residency program at St Mary Medical Center in Apple Valley, CA. **We are seekingRegistered Nurses who are:** + New graduate Read more
Essbase Developer - *Apple* - Theorem, LLC...
Job Summary Apple is seeking an experienced, detail-minded Essbase developer to join our worldwide business development and strategy team. If you are someone who Read more