Readln

When reading an input text file (such as provided in the Advent of Code-competition) a suitable strategy is often to break it down into lines, and store each line as a separate item within a list:

my list utilities script pic

Subsequently the list may be “read” (and sometimes be decomposed further) “line-by-line” (= one item at a time), e.g.:

I’ve been looking for a function (reporter) to substitute for my list utilities script pic 4 … with one added feature: the first item will be removed from the input list immediately after reading - in this context such mechanism works much like readln in Pascal. Thus the code of the client process above may be shortened to something like this:

My proposal is this really small and simple function:

my list utilities script pic 3

Perhaps my list utilities script pic 7 is not particularly elegant, being imperative style and all that. Actually I had started out trying to code the whole thing in a functional style, employing my list utilities script pic 6, but couldn’t figure out how. I guess it could also be done in OOP-with-procedures style (Snap*!* Manual, chapter VIII) … anyone?

The official best way to process the lines from the file is to use MAP, if you're trying to compute some function of the lines, or FOR EACH ITEM if you want to mutate something for each line.

The official second best way is to write a recursive procedure:

Either of those solutions can be purely functional.

Your solution is okay, too, provided that you don't mind erasing your input data. But you might, for example, want to do something else with each line after you finish the first pass.

But I wouldn't want your PICK procedure in the List Utilities library, because it really encourages people to process lists destructively, and we're trying to build functional programmers. And, as you say, it's easy to write. If it were big and complicated, that might be a reason to provide it in a library.

I see what you mean, and wrote an alternative reporter function, inspired by the “OOP with Procedures” chapter from the Reference Manual. It keeps all data intact:

And here’s an example of how to apply it:

An alternative implementation is:

VPW basis script pic 7

Both implementations have similar behavior, reporting a error (“reporter doesn’t report”) when trying to read past the end of the list.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.