Haskell Gem – Unwrapping Indented Text
November 03, 2009
While processing some email, I needed a script to unwrap indented lines in email headers. I wrote a Haskell program that turned out to be a short and sweet demonstration of simple but interesting Haskell features (pattern matching, guards, type inference, function composition, and the humble cons) so I thought I’d share it.
If you’re new to Haskell,
[]is the empty list[a]is a list with a single elementax : ycreates a new list by placing elementxat the front of listy++is concatenateinteractis a function taking a single argument, a function that takes a string and returns a string, and returns a bit of IO that runs the string transformation function on the contents of STDIN and prints the result.(period) is a binary operator that composes functionsfoldris right-fold, and behaves like this:foldr f d [a, b, c] == f a (f b (f c d))- Lines of the form
| a = bare guards, which evaluate tobifaevaluates toTrue
Example usage:
[/tmp]% cat > header
This is a normal line.
This is a slightly longer line that
__wraps with two spaces.
A short line.
Another example of a long line that
____wraps with tabs (not just once,
____but twice.
Final line.
[/tmp]% cat header | runhaskell Unwrap.hs
This is a normal line.
This is a slightly longer line that wraps with two spaces.
A short line.
Another example of a long line that wraps with tabs (not just once, but twice.
Final line.