Reputation: 4258
Is their a way in Clojure to go from an int to that int as a character, e.g. 1 to \1 ?
I have a string s
and I want to parse out the digits that match a number n
(n will always be 0 to 9)
e.g.
(let [n 1]
(filter #(= ??? %) "123123123"))
Where ??? would n as \n, e.g. 1 would return "111"
Or maybe there is a better way to filter a string to only instance of a single digit?
Upvotes: 1
Views: 444
Reputation: 4122
And as usual in Clojure, there's always a reduce
one-line to solve the original problem: "I just want the count of how many times that digit appears."
(reduce (fn [m ch] (update m ch (fnil inc 0))) {} "123123123")
==> {\1 3, \2 3, \3 3}
A lot to unpack here, if you are new to Clojure. Reduce is used to iterate over the String, counting occurrences of each character and storing it in a map.
From inner to outer:
(fnil inc 0)
returns a function that runs inc
with any argument provided. However, if the argument is nil, it will replace it with 0 instead. This is perfect for adding a new entry to the map.
update
is used to look up an existing key ch
in m
and calculate a new value (by calling the function returned by (fnil inc 0
)), i.e. if the ch
is not in m
this will run (inc 0) => 1
, if ch
is in m
it will return the incremented counter.
(fn [m ch] ...)
is the reducing function.
This is the most difficult part to understand. It takes two parameters.
The first is the last return value of this function (generated by an earlier iteration) or if it is the first time this function runs, the initial value provided: {}
(there's also a third way to call reduce, see (doc reduce)
)
The second argument ch
is the current character in the String provided (since String is a CharSequence and counts as a collection).
So the reducing function is called for each character and we just return the current map with an updated count for each character, starting with {}
.
Upvotes: 4
Reputation: 37008
The "java" way:
user=> (Character/forDigit 1 10) ; number and radix
\1
The "calculaty" way (add the int of \0
to it and then back to char):
user=> (char (+ 1 (int \0)))
\1
Upvotes: 6