Skip to content

Instantly share code, notes, and snippets.

@samth

samth/count.rkt

Created Mar 18, 2021
Embed
What would you like to do?
#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