Home > Enterprise >  How to make mutual recursion in APL?
How to make mutual recursion in APL?

Time:10-30

I'm trying the following mutual recursion example in Dyalog APL Win10:

      even ← { (odd  ⍵-1) ∨ ⍵=0 }
      odd  ← { (even ⍵-1) ∧ ⍵>0 }
      even 7
WS FULL

It looks like the and doesn't stop evaluation at reaching a defined state. The WS FULL shows that the recursion actually works but doesn't terminate properly.

How to make mutual recursion in APL?

PS. I'm very new to APL and doesn't know the proper syntax of functions. Anyway, I prefer a more "functional" style, if it is possible.

CodePudding user response:

Since and are normal functions, and do not short-circuit, you have to use "guards" instead:

      even ← {⍵=0:1 ⋄ odd ⍵-1}
      odd  ← {⍵>0:even ⍵-1 ⋄ 0}
      even 7
0

Alternatively, you can define your own short-circuiting operators. You can find ready-made definitions on APLcart:

      OR   ← {⍺⍺ ⍵:1 ⋄ ⍵⍵ ⍵}
      AND  ← {⍺⍺ ⍵:⍵⍵ ⍵ ⋄ 0}
      even ← {=∘0 OR  (odd  -∘1) ⍵}
      odd  ← {>∘0 AND (even -∘1) ⍵}
      even 7
0
  • Related