[racket] complex sort or how to sort lines

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Fri May 25 12:29:10 EDT 2012


On May 25, 2012, at 12:16 PM, Don Green wrote:

> Given the output of Racket's read-words/line function, which produces a list of lists. Each word is in a list, each group of words on a line is in a list, all within a list.
> 
> Any ideas on how to sort on the car (first element) of each list that corresponds to a line?
> 
> In other words, I want to sort lines based on the first word on a line.  I want to keep the lines intact.  
> Thanks.
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users





#lang racket

(require 2htdp/batch-io rackunit)

;; --- answer to your question: 
(define (answer file)
  (sort (read-words/line file) string<=? #:key first))

;; --- test set up
(define content
  #<< eos
This is a silly sample file. 
Do you think it is long enough? 
Or should I add a line? 
 eos
  )

(define expected
  #<< eos
Do you think it is long enough?
Or should I add a line?
This is a silly sample file.

 eos
  )

(define file (path->string (make-temporary-file "tst~a")))
(with-output-to-file file
  #:exists 'replace
  (lambda () 
    (for ((ch content)) (display ch))))

;; --- test
(check-equal? (with-output-to-string
               (lambda ()
                 (for ((ln (answer file)))
                   (displayln (string-join ln)))))
              expected)
 

Posted on the users mailing list.