CompuServe Thread

#Recursion in Modula 2

8 messages in this thread
#76530From: John DraperJul 16, 1987 6:15 PM
#76565From: Richard BielakJul 16, 1987 8:50 PM
Larry, here is a cute and useful example of recursion: .. . PROCEDURE WriteOctal (n : INTEGER); . BEGIN . IF n <= 7 THEN . WriteInt (n,1) . ELSE . WriteOctal (n DIV 8); . WriteInt (n MOD 8, 1) . END . END WriteOctal; . This should be as easy as Factorial, but not as obviously converted to iteration. …..Richie "To iterate is human, to recurse divine!"
#76606From: John DraperJul 17, 1987 2:16 AM
Richie, nice one! And definitely useful for those poor souls who've lost their thumbs and need octal. Regards, Larry.
#76623From: Vic WagnerJul 17, 1987 3:23 AM
Richard, Doesn't work with negative numbers.
#76747From: Richard BielakJul 18, 1987 2:22 PM
True, but negative numbers can be taken care of before calling WriteOctal…..Richie
#76715From: Vic WagnerJul 18, 1987 3:34 AM
Richard, Other than that, it's a great example.
#76802From: Steve FaiwiszewskiJul 18, 1987 10:44 PM
Negative numbers on a computer are nothing but an illusion: Everything is really a cardinal!! Besides why would you want to print the Octal representation of a negative number?? (And who the hell needs Octal anyway, Richie?? Long Live Hex! :-))
#76800From: Steve FaiwiszewskiJul 18, 1987 10:41 PM
Granted, using the Factorial example to demonstrate recursion is very silly. And I think that Wirth agrees that for Factorials, iteration is preferred. A better example would be something like the Towers of Hanoi or the Knight's Tour problems. See if you can code these using iteration. Then do it using recursion. All of a sudden you'll see the beauty of recursion. As they say: 'To Iterate is Human; To Recurse – Divine'