Implementations of the various forms of reversing a file.
"Reversing" a file is an interesting concept, because there are so many different things that people mean by that phrase. Most of them are trivial to do with eddie.
Herein is a bestiary of backwards files, and how to use eddie to produce them.
Reverse the complete file
The easiest "reverse" with eddie is to reverse all the characters in the file, which is just:
$ eddie reverse /etc/motd
Reversing the lines
Printing each line in reverse - though in the same order - is another common meaning for reversing a file, and is about the most complicated thing in this list:
$ eddie 'unlines . map reverse . lines' /etc/motd
This pattern - turning the list into lines, then mapping a function over each line - is pretty common, and long enough to be unwieldy. So there's a flag that causes eddie to apply the pattern parts for you, so the above can be written as:
$ eddie -l reverse /etc/motd
Lines in reverse order
Printing the lines from the end of the file forward, with each line in forward order, isn't much harder:
$ eddie unlines.reverse.lines /etc/motd
This pattern - processing the lines as a list - is also common, so there's a shorthand for it as well:
$ eddie -l -L unlines.reverse /etc/motd
In this case, the
-L option causes the lines to be processed as a list instead of one at a time, but we still have to put the results back into a single string.
Reversing the words
Printing each word reversed, though in the same order, is no harder than reversing lines:
$ eddie -l 'unwords . map reverse . words' /etc/motd
-l flag preserves the line breaks. If you leave it off, each word still gets reversed, but the process of breaking the input up into words loses the lines.
Reversing the words on a line
For this one, we want to print the lines in the proper order, reversing the order of the words on the line, but leave the words reading forward. The long-winded way to do this is:
$ eddie 'unlines . map unwords . map reverse . map words . lines' /etc/motd
Haskell's functional nature allows the three map'ed functions to be composed, giving:
$ eddie 'unlines . map (unwords . reverse . words) . lines' /etc/motd
which is the pattern handled by the
-l flag, so we can do this as:
$ eddie -l unwords.reverse.words /etc/motd
Words in reverse order
Printing the words in reverse order, but each word in forward order, isn't a common meaning for reverse, but is only a little harder than what we've done so far:
$ eddie -L -l 'unlines . map (unwords . reverse . words) . reverse' /etc/motd
The hard part of this example is preserving the line breaks. If you didn't care about that, you could do this as:
$ eddie unwords.reverse.words /etc/motd