读取包含数字的文件并在打印出一行之前进行平方

时间:2013-07-24 22:33:25

标签: golfscript

我正在学习golfscript,我想在包含数字的文件中读取并在打印出一行之前进行平方。例如,我有一个像以下

的文件
1
2
3
4

然后我需要打印

1 4 9 16

我该怎么做?

1 个答案:

答案 0 :(得分:2)

以下代码为您提供了如何完成任务的想法。

;                             # 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

您可以找到每个运营商的详细信息here