I want to generate character sequence from 'a' to 'z'. In scala, I can generate character sequence very simply:
('a' to 'z')
But in clojure, I end up with the following code:
(->> (range (int \a) (inc (int \z))) (map char))
or
(map char (range (int \a) (inc (int \z))))
It seems to me verbose. Are there any better ways to do it?
If code looks "verbose" it's often just a sign that you should factor it out into a separate function. As a bonus you get the chance to give the function a meaningful name.
Just do something like this and your code will be much more readable:
(defn char-range [start end]
(map char (range (int start) (inc (int end)))))
(char-range \a \f)
=> (\a \b \c \d \e \f)
According to this StackOverflow Answer a simple solution would be:
(map char (range 97 123))
AFAIK, no such a fancy way as Scala. How about
(flatten (partition 1 "abcdefghijklmnopqrstuvwxyz"))
More fancy way, thanks to @rhu
(seq "abcdefghijklmnopqrstuvwxyz") ; if you copied this from an earlier version, \w and \v were in the wrong positions
If you're interested in a library that gives you a convenient char-range
function, my library djy
has one: see djy.char/char-range
.
boot.user=> (char-range \a \z)
(\a \b \c \d \e \f \g \h \i \j \k \l \m \n \o \p \q \r \s \t \u \v \w \x \y \z)
It even handles supplemental Unicode characters that are large enough that they require 2 characters, representing them as strings:
boot.user=> (char-range (char' 0x1f910) (char' 0x1f917))
("🤐" "🤑" "🤒" "🤓" "🤔" "🤕" "🤖" "🤗")
djy: a library of character utility functions for Clojure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With