Reading/Printing a file
A friend of mine at work, also bitten by the functional bug, has been hacking on some Scala.
He showed me some code yesterday and I thought it might be fun to convert it. I am not going to post his code, as that would be presumptuous, but I have mine to show.
The goal is to read up a file, and then print that file prepending each line with the number of characters in that line, as well as padding the beginning so that everything lines up.
The usual caveats about my newbness.
; Get the name of the document from the cli
(def arg (first *command-line-args*))
; Convert the doc to a vector
(def lines (vec (.split (slurp arg) "\n")))
; Takes a string, and finds out how long
; the length, of the length is
(defn length-of-length[s]
(.length (str (.length s))))
; Returns the longest element from a collection
(defn get-longest-line[lines]
(reduce (fn [x y]
(if (>(.length x)(.length y))
x y))lines))
; Repeat s string t times.
(defn pad[s t]
(take t (repeat s)))
; Find the maximum width of a line from the doc
(def max-width (length-of-length (get-longest-line lines)))
; Take the vector of the file, iterate over the lines and
; print each one prepended with the number of characters that
; appear in that line
(doseq [line lines]
(let [num-spaces (- max-width (length-of-length line))]
(println (apply str " " (pad " " num-spaces)) (.length line) " | " line)))
Tip of the hat to ‘Chousuke’ in #clojure for the clue on ‘apply’.
Example
$ java -cp /opt/clojure/clojure.jar clojure.main scala.clj test.txt
50 | This is a text file with lines that vary in length
0 |
13 | ^^ Blank line
34 | Some other text that is mid length
9 | Oh hai!!!
Thanks for playing!
The Scala example was taken verbatim from Programming in Scala chapter 3. Ok by me to post it – may or may not be ok by the book’s authors.