2015-07-14.scm 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env gosh
  2. ;; In the dictionary, find the longest ordered word
  3. ;; An ordered word is one which has its letter in alphabetical order
  4. (import (scheme base)
  5. (scheme char)
  6. (scheme file)
  7. (scheme write)
  8. (srfi 95)) ;; For 'sorted?'
  9. (define dictionary
  10. (open-input-file "/usr/share/dict/words"))
  11. (define (next-word)
  12. ;; Words with punctuation will be automatically rejected
  13. (let ((next (read-line dictionary)))
  14. (if (eof-object? next)
  15. (begin
  16. (close-input-port dictionary)
  17. next)
  18. (string-downcase next))))
  19. (define-record-type type-word-list
  20. (word-list size contents)
  21. word-list?
  22. (size wl-size)
  23. (contents wl-contents))
  24. (define (update-wl wl word)
  25. (if (and (>= (string-length word) (wl-size wl))
  26. (sorted? (string->list word) char<?))
  27. (word-list (string-length word)
  28. (if (> (string-length word) (wl-size wl))
  29. (list word)
  30. (cons word (wl-contents wl))))
  31. wl))
  32. (define (make-null-wl)
  33. (word-list 0 '("")))
  34. (define longest-sorted
  35. (let loop ((wl (make-null-wl))
  36. (next (next-word)))
  37. (if (eof-object? next)
  38. wl
  39. (loop (update-wl wl next)
  40. (next-word)))))
  41. (write (wl-contents longest-sorted))
  42. (newline)