Last active
September 17, 2017 20:31
-
-
Save logc/5d5295c1ce00fa9fc7af42f8afcbbfb2 to your computer and use it in GitHub Desktop.
Faster Command Line Tools in Racket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang typed/racket/base | |
(require racket/cmdline | |
racket/string) | |
(: parse (-> String Integer Integer (Values String Integer))) | |
(define (parse line key-field-pos val-field-pos) | |
(let ([fields (string-split line "\t")]) | |
(values (list-ref fields key-field-pos) | |
(assert (string->number (list-ref fields val-field-pos)) | |
exact-integer?)))) | |
(: count-vals (-> Input-Port Integer Integer (Values String Integer))) | |
(define (count-vals filehandle key-field-pos val-field-pos) | |
(define: default : Integer 0) | |
(define: counter : (Mutable-HashTable String Integer) (make-hash)) | |
(define: max-key : String "") | |
(define: max-val-seen : Integer 0) | |
(for ([line (in-lines filehandle)]) | |
(define-values (key val) | |
(parse line key-field-pos val-field-pos)) | |
(define: old-val : Integer (hash-ref! counter key (lambda () default))) | |
(define: new-val : Integer (+ old-val val)) | |
(hash-set! counter key new-val) | |
(when (new-val . > . max-val-seen) | |
(set! max-val-seen new-val) | |
(set! max-key key))) | |
(values max-key max-val-seen)) | |
(module+ main | |
(define: args : (Vectorof String) (current-command-line-arguments)) | |
(define: filename : String (vector-ref args 0)) | |
(define: key-field-pos : Integer | |
(assert (string->number (vector-ref args 1)) exact-integer?)) | |
(define: val-field-pos : Integer | |
(assert (string->number (vector-ref args 2)) exact-integer?)) | |
(define: in : Input-Port (open-input-file filename #:mode 'text)) | |
(define-values (max-key max-val) (count-vals in key-field-pos val-field-pos)) | |
(printf "max_key: ~a sum: ~a~n" max-key max-val)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by Faster Command Line Tools in D