Letter frequency: Difference between revisions

Content added Content deleted
(completely RNRS Scheme with the exception of format, uses native Scheme character representations, more canonical indentation, and an association list instead of a vector)
Line 2,277: Line 2,277:
=={{header|Scheme}}==
=={{header|Scheme}}==


Using guile scheme 2.0.11, but the functions that don't use format should work in any implementation.
=== Imperative version ===


Note that this prints the scheme representations of characters in no particular order.
{{novice example|scheme}}


<lang scheme>(use-modules (ice-9 format))
For brevity, outputs only lower-case letters.


(define (char-freq port table)
<lang scheme>#!/usr/local/bin/gosh
(if
(eof-object? (peek-char port))
table
(char-freq port (add-char (read-char port) table))))


(define (add-char char table)
(use srfi-1) ;; iota
(cond
((null? table) (list (list char 1)))
((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr table)))
(#t (cons (car table) (add-char char (cdr table))))))


(define *freqs* (make-vector 256 0))
(define (format-table table)
(if
(not (null? table))
(begin
(format #t "~10s~10d~%" (caar table) (cadar table))
(format-table (cdr table)))))


(define (main args)
(define (print-freq filename)
(with-input-from-file "../word-list.txt" count-char-freqs)
(format-table (char-freq (open-input-file filename) '())))
(show-char-freqs #\a #\z))


(print-freq "letter-frequency.scm")</lang>
(define (count-char-freqs)
(let* ((ln (read-line))
(at-eof (eof-object? ln)))
(if (not at-eof)
(let ((string-chars (string->list ln)))
(for-each count-char-freq string-chars)
(count-char-freqs)))))


Output when reading own source:
(define (count-char-freq ch)
#\( 48
(if (char-alphabetic? ch)
#\u 6
(let* ((char-num (char->integer (char-downcase ch)))
(frq (vector-ref *freqs* char-num)))
#\s 9
(vector-set! *freqs* char-num (+ 1 frq)))))
#\e 51
#\- 19

#\m 9
(define (show-char-freqs first-letter last-letter)
#\o 17
(format #t "Letter Frequency~%")
#\d 19
(let* ((first-num (char->integer first-letter))
(last-num (char->integer last-letter))
#\l 30
#\space 97
(num-count (+ 1 (- last-num first-num)))
(nums-list (iota num-count first-num)))
#\i 17
(for-each show-char-freq nums-list)))
#\c 28
#\9 1

#\f 21
(define (show-char-freq let-num)
#\r 40
(let ((ch (integer->char let-num))
(frq (vector-ref *freqs* let-num)))
#\a 51
(format #t "~6a ~8a~%" ch frq)))</lang>
#\t 39
#\) 48

#\newline 25
Example output:
#\n 18

#\h 13
Letter frequency
a 16421
#\q 7
b 4115
#\p 9
c 8216
#\b 20
d 5799
#\j 1
e 20144
#\? 4
f 2662
#\k 1
g 4129
#\1 4
h 5208
#\+ 1
i 13980
#\# 2
j 430
#\g 1
k 1925
#\" 4
l 10061
#\~ 3
m 5828
#\0 2
n 12097
#\% 1
o 12738
#\' 1
p 5516
#\y 1
q 378
#\. 1
r 13436
s 10210
t 12836
u 6489
v 1902
w 1968
x 617
y 3633
z 433


=={{header|Seed7}}==
=={{header|Seed7}}==