Skip to content
loading...

re: Daily Challenge #138 - Do I get a Bonus? VIEW POST

FULL DISCUSSION
 

Since this exercise was too simplistic I decided to do it in GolfScript

{\.'0'+\if}:bonus;

You can call it like this (with 0 being false and 1 being true):

1000 0 bonus
1000

1000 1 bonus
10000

Explanation:

  • {} defines a block of code
  • :bonus assigns this block to a variable named bonus
  • ; pops the block off the stack since it's assigned to a variable anyway

The "function body":

  • \ swaps the top 2 stack arguments, so e.g. 1000 1 becomes 1 1000
  • . duplicates the top of the stack, so 1 1000 becomes 1 1000 1000
  • '0' pushes '0' on the stack, so 1 1000 1000 becomes 1 1000 1000 '0'
  • + concatenates the top two stack argument, automatically coercing to string if necessary. The stack is now 1 1000 10000
  • \ swap the top 2 stack arguments again, so 1 10000 1000
  • if pops 3 elements of the stack, if true (1) outputs the second (10000) otherwise the third (1000)
  • No explicit output is needed since a GolfScript program automatically prints the remaining stack when it finishes

In a more traditional stack-based language like Forth one could define the word bonus simply as :

: bonus if 10 * . else . then  ;

1000 true bonus
10000 
 
 

That’s a pretty apt summary of GolfScript. I like it for solving small problems like this, fun mental exercise.

code of conduct - report abuse