Exercise 146: Design a program that converts a list of lines into a string.
The strings should be separated by blank spaces (" ").
The lines should be separated with a newline ("\n").
Challenge: Remove all extraneous white spaces in your version of the Piet Hein poem. When you are finished with the design of the program, use it like this:
(write-file "ttt.dat" (collapse (read-words/line "ttt.txt")))
The two files "ttt.dat" and "ttt.txt" should be identical.
(require 2htdp/batch-io)
(define FILE "ttt.txt")
; read-words/line reads the content of file f and produces it as
; a list of lists,
; one per line; each line is represented as a list of white-space
; separated tokens .
(define (collapse a)
(collapse-lines (read-words/line FILE)))
; List-of-Strings -> String
(define (collapse-lines llos)
(cond ((empty? llos) "")
((cons? llos) (string-append (collapse-los (first llos)) "\n" (collapse-lines (rest llos))))))
; List-of-Strings -> String
; collapses a 1 dimensional list of tokens into a string
; (eg NOT a list of lists of strings, just a list of strings
; A List-of-Strings is one of:
; – empty
; – (cons String List-of-Strings)
(define (collapse-los los)
(cond ((empty? los) "")
((= 1 (length los)) (first los))
((cons? los) (string-append (first los) " " (collapse-los (rest los))))))
(check-expect (collapse-los empty) "")
(check-expect (collapse-los (cons "slowly" (cons "you" (cons "climb" empty))))
"slowly you climb")
No comments:
Post a Comment