-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapping.rkt
41 lines (34 loc) · 1.08 KB
/
wrapping.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#lang racket/base
(require racket/list
racket/string)
(provide wrap)
(define chars-per-line 45)
(define lines-per-page 4)
(define (wrap str)
(define sections (string-split str "\n"))
(apply append (map wrap-section sections)))
(define (wrap-section str)
(define lines (break-lines str))
(define pages (break-pages lines))
(map (λ (p) (string-join p "\n")) pages))
(define (break-lines str)
(define words (string-split str))
(for/fold ([lines '()]
[this-line (car words)]
#:result (reverse (cons this-line lines)))
([word (cdr words)])
(define new-length (+ (string-length this-line)
(string-length word)))
(if (> new-length chars-per-line)
(values (cons this-line lines) word)
(values lines (string-append this-line " " word)))))
(define (break-pages lines)
(cond
[(null? lines) '()]
[(< (length lines) lines-per-page) (list lines)]
[else
(define-values (these rest)
(split-at lines lines-per-page))
(cons these
(break-pages
rest))]))