4
\$\begingroup\$

Community agrees that functions should be reusable while if a function take whole stdin (like while(gets()) in C or fs.readFileSync(0) in nodejs) then it can no longer be used. In this case is it still required to recover environment?

A third answer, function don't take whole stdin, can be considered

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

This shouldn't be a special case

Consuming the entirety of standard input isn't something that necessarily makes a function unusable in the future, because it's possible for files to grow.

If standard input is a regular file, a loop like while(gets(…)) (note: this code is inherently insecure, so although it's allowed for golfing if you know how large the input could be, it should never be used for regular programming) will read to the end of the file – the current end of the file. Then it will stop. The next time you run the function, it will start reading the file where it left off, but that isn't necessarily going to be the end of the file any more, because someone might have edited the file in between the two calls and made it longer.

The same phenomenon can also happen if standard input is a terminal; the user can type whatever the "end of file" character sequence is (Ctrl-D on Unix/Linux/Mac or Ctrl-Z on Windows), and the input routines will return an end-of-file condition at that point. However, if you keep reading from the terminal after that, it'll keep looking for user input, with another end-of-file sequence required to make the input routines return end-of-file again.

When writing full programs that consume input, it's reasonable for a program to assume that an end-of-file condition on standard input, once encountered, will continue to be encountered, i.e. its input isn't changing while it's reading it. The reason you can do that is that we're conceptually providing the input to the program by connecting standard input to an unchanging file. However, when writing a function submission, we're conceptually connecting the standard input of each call to the function to its own unchanging section of a file, and that doesn't imply that multiple calls will be given the same data (or that the first call will be the only call with data and the others will have empty input); each call is being given different input, which can in practice be implemented by growing standard input in between the calls (by appending to the file or typing on the terminal that represents it).

As such, I don't see any reason why functions that read standard input should be treated any differently than functions that don't, even if they read it all the way to (what is, to them) the end – our normal rules for functions should be fine here.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .