Skip to content

Instantly share code, notes, and snippets.

@samth
Created March 18, 2021 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samth/36e66372ccd3b0d291c77472a1321f0e to your computer and use it in GitHub Desktop.
Save samth/36e66372ccd3b0d291c77472a1321f0e to your computer and use it in GitHub Desktop.
#lang racket/base
(require racket/string racket/bytes racket/vector racket/port)
(define h (make-hash))
(#%declare #:unsafe)
(define (split-lines)
(for* ([l (in-bytes-lines)])
(let loop ([i 0] [last 0])
(cond [(= i (bytes-length l))
(unless (eq? i last)
(hash-update! h (bytes-downcase! (subbytes l last i)) add1 0))]
[(eq? (bytes-ref l i) (char->integer #\space))
(unless (eq? i last)
(hash-update! h (bytes-downcase! (subbytes l last i)) add1 0))
(loop (add1 i) (add1 i))]
[else
(loop (add1 i) last)]))))
(define (bytes-downcase! b)
(for ([(n i) (in-indexed (in-bytes b))])
(when (<= (char->integer #\A) n (char->integer #\Z))
(bytes-set! b i (- n (- (char->integer #\A) (char->integer #\a))))))
b)
(time (split-lines))
(define v
(time
(for/vector #:length (hash-count h)
([(k v) (in-hash h)])
(cons k v))))
(time (vector-sort! v > #:key cdr))
(define p (current-output-port) #; (open-output-nowhere))
(time
(for ([pair (in-vector v)])
(write-bytes (car pair) p) (write-bytes #" " p)
(write (cdr pair) p)
(newline p)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment