Rebol3 Code Examplex
Letter frequency
Count how often each letter appears in text.
Rebol [
title: "Rosetta code: Letter frequency"
file: %Letter_frequency.r3
url: https://rosettacode.org/wiki/Letter_frequency
]
letter-frequency: function[
text [string! file! url!]
/limit chars [bitset!] "count only chars in this bitset"
/case "case-sensitive search"
][
dict: make map! 24
unless string? text [text: read/string text]
foreach c text [
unless case [c: lowercase c] ;; normalise to lowercase unless /case
if all [limit not find/:case chars c][continue] ;; skip chars outside allowed set
put/:case dict c either n: dict/:c [n + 1][1] ;; increment or initialise counter
]
dict
]
;; Example:
print ["Using input:" as-green mold str: "aa B cC!"]
alpha: charset [#"a"-#"z" #"A"-#"Z"]
foreach test [
[letter-frequency :str]
[letter-frequency/limit :str :alpha]
[letter-frequency/limit/case :str :alpha]
[letter-frequency/limit %Letter_frequency.r3 :alpha]
][
print [mold/only test "^/;==" mold/flat try test]
]
Output:
Using input: "aa B cC!"
letter-frequency :str
;== #[#"a" 2 #" " 2 #"b" 1 #"c" 2 #"!" 1]
letter-frequency/limit :str :alpha
;== #[#"a" 2 #"b" 1 #"c" 2]
letter-frequency/limit/case :str :alpha
;== #[#"a" 2 #"B" 1 #"c" 1 #"C" 2]
letter-frequency/limit %Letter_frequency.r3 :alpha
;== #[#"r" 53 #"e" 91 #"b" 4 #"o" 25 #"l" 42 #"t" 82 #"i" 45 #"s" 46 #"a" 41 #"c" 45 #"d" 13 #"f" 17 #"q" 9 #"u" 22 #"n" 38 #"y" 12 #"h" 15 #"p" 12 #"g" 6 #"w" 4 #"k" 3 #"x" 6 #"m" 13 #"v" 1 #"z" 2]