Thinking functionally (1): removing variables
If you're not programming functionally, then you're programming
dysfunctionally.
Long time ago, in the first ages of universe, coders and variables were living peacefully; but one day, they turned evil and then began a long war between them and men. Unfortunately men could not do much against so many variables. Only a few men are still alive today, but fortunately you can do something for them. You have heard about the ancient art of computer programming and you even spoke one day to a very old functional programmer. Your mission is to kill as many variables as you can.
This should be the first challenge in a longer series called "Thinking functionally".
Goal: write a short and interesting piece of code in some language where variables are usually needed (we all know that you can write some code in J or in some stack-based language with no variable, but please, choose some other language for this challenge), and use fewer variables than what would have been expected. You must explain what you did.
Example 1: Here is a first example in python, acceptable and interesting. The computer will guess which number you are thinking at with an optimal strategy, with only one variable.
a = 256
while True:
print("I am going to guess the number you are thinking at.")
print("Is it",a,"?")
print(":: 0 for less, 1 for more, Ctrl-C for OK")
a = (
[
lambda x: x - ( (1 + (x ^(x-1))) >> 2 ),
lambda x: x + ( (1 + (x ^(x-1))) >> 2 )
]
)[input("? ")](a)
Explanation:Explanation: usually this game requires at least two variables, a and b, which allow the program to remember the smallest and largest possible number, then a third number is computed (a+b)/2 and a or b is updated according to the answer of the player. Here the code uses only one variable, and checks for successive bits in order to set them or not.
Example 2: Here is another example, acceptable but not as much interesting. How can I swap two variables?
a = 42
b = 17
a = a + b
b = a - b
a = a - b
Explanation:Explanation: everyone knows that three variables are needed for swapping two variables, and we laugh when students try something like a=b followed with b=a, but you actually can swap variables without any temporary variable.
Score: this is a popularity contest; the winner will be for the answer with the most upvotes. Vote for an answer if you find it clever and tricky.