Clojure, lesson 8
Clojure strings are Java strings: immutable sequences of characters. Clojure adds str,
subs and format in the core library, and a set of tidy helpers in clojure.string.
A character is written with a backslash, like \H, and is a different type from the one-letter
string "H". (str \H) turns a character into a string.
Because a string is a sequence of characters, all the sequence functions from the last lesson
work on it: (filter #(= % \a) "banana") gives the three \a characters, and
counts them.
2 exercises to try what you just read.
(count (filter ...))str/split cuts a string using a regular expression, written #"...". The pattern #"\s+"
means "one or more whitespace characters", so repeated spaces don't produce empty pieces in the
middle:
A string that starts with spaces still gives an empty first piece, so trim before splitting.
str glues pieces together; format gives you control over layout:
%-8s pads a string to 8 characters on the right; %5d pads a number to 5 on the left. That is
handy for lining up columns.
The last exercise is a receipt printer. It uses almost every lesson: reading input, converting text to numbers, functions, sequence functions, and formatted output. Plan before you type:
line-seq and drop the blank ones.{:name "apple" :qty 3 :price 2} with a small function.reduce (or map plus reduce +) and print them.Using keywords like :name as map keys is the Clojure way to describe a record of data. A keyword
can also be called as a function to look itself up: (:qty item) is the same as
(get item :qty).
Read a full name on one line. Print the initials in upper case, each followed by a dot. The name may be in any case and may contain extra spaces between words.
Sample input:
Sample output:
Each input line describes one item: a name, a quantity and a unit price, separated by single
spaces. Prices are whole numbers. For every item print name: quantity x price = subtotal, then
finish with the total number of items and the total cost. Ignore empty lines.
Sample input:
Sample output:
(require '[clojure.string :as str])
(def s "Hello, Clojure")
(count s) ; 14
(first s) ; \H (a character)
(subs s 7) ; "Clojure" (from index 7 to the end)
(subs s 0 5) ; "Hello" (from 0 up to, not including, 5)
(str/upper-case s) ; "HELLO, CLOJURE"
(str/trim " padded ") ; "padded"
(str/reverse "abc") ; "cba"(str/split "red green blue" #"\s+") ; ["red" "green" "blue"]
(str/join ", " ["red" "green"]) ; "red, green"
(str/join ["a" "b" "c"]) ; "abc"(str/starts-with? url "http")
(str/ends-with? file ".clj")
(str/includes? "banana" "nan") ; true
(str/index-of "banana" "n") ; 2 (nil if not found)
(str/blank? " ") ; true(str "apples: " 12) ; "apples: 12"
(format "%.2f" 3.5) ; "3.50"
(format "%-8s|%5d" "apples" 12) ; "apples | 12"grace brewster hopperG.B.H.apple 3 2
bread 1 4
cheese 2 7apple: 3 x 2 = 6
bread: 1 x 4 = 4
cheese: 2 x 7 = 14
Items: 6
Total: 24