1 ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 ;; about the language level of this file in a form that our tools can easily process.
3 #reader(lib "" "lang")((modname |27.2|) (read-case-sensitive #t) (teachpacks ((lib "" "teachpack" "htdp") (lib "" "teachpack" "htdp") (lib "" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "" "teachpack" "htdp") (lib "" "teachpack" "htdp") (lib "" "teachpack" "htdp")))))
4 ;Exercise 27.2.1. Determine what the list-of-lines representation for empty, (list 'NL), and (list 'NL 'NL) should be. Why are these examples important test cases?
6 ;A file is either
7 ;1. empty or
8 ;2. (cons s f)
9 ;where s is a symbol and f is a file.
11 ;Examples
12 ;
13 ;(file->list-of-lines empty)
14 ;empty
15 ;(file->list-of-lines (list 'NL))
16 ;(list empty)
17 ;(file->list-of-lines (list 'NL 'NL))
18 ;(list empty empty)
20 ;The NEWLINE character is represented by 'NL
21 (define NEWLINE 'NL)
23 ;file->list-of-lines : file -> (listof (listof symbols))
24 ;Converts a-file into a (listof (listof symbols)) representing the file. Each new list starts right at the end of a newline symbol and ends at the first occurrence of a newline symbol. file->list-of-lines uses generative recursion: the first line is appended to the front of the remainder of the file that has already been converted into a list of lines.
25 ;Termination Argument: Since each application of file->list-of-lines necessarily shortens the argument for the new generative recursion, the paramater must get smaller over time and eventually become the empty list, for which a trivial solution is available.
27 (define (file->list-of-lines a-file)
28 (cond
29 [(empty? a-file) empty]
30 [else (cons (first-line a-file)
31 (file->list-of-lines (remove-first-line a-file)))]))
33 ;first-line : file -> (listof symbols)
34 ;Returns the first line of a-file.
36 (define (first-line a-file)
37 (cond
38 [(symbol=? NEWLINE (first a-file)) empty]
39 [else (cons (first a-file)
40 (first-line (rest a-file)))]))
42 ;remove-first-line : file -> file
43 ;Given a-file, remove the first line.
45 (define (remove-first-line a-file)
46 (cond
47 [(symbol=? NEWLINE (first a-file)) (rest a-file)]
48 [else (remove-first-line (rest a-file))]))
50 (file->list-of-lines '(Hi my name is Joe NL
51 and I live in a button factory NL
52 I have a wife NL
53 and three kids NL))