2

I am learning golfscript, and I want to read in a file containing numbers and do squaring before print out on one line. For example, I have a file like the following

1
2
3
4

Then I need to print out

1 4 9 16

How can I do this?

Beatle
  • 43
  • 2

1 Answers1

2

The following code gives you an idea, how to accomplish the task.

;                             # Discard the input (golfscript takes 
                              # input from STDIN)

"#{File.read('input.txt')}"   # Read contents of file into a string
                              # (see your previous question 
                              # http://stackoverflow.com/q/17826704)

[~]                           # Evaluate the input into an array

{2?}%                         # Apply the operators `2?` to each element
                              # ( "x 2 ?" simply calculates x^2 )

" "*                          # Join the array elements with spaces

                              # By default the remaining items on the stack
                              # are printed when the program ends

You find details to each of the operators here.

Howard
  • 38,639
  • 9
  • 64
  • 83