Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate character sequence from 'a' to 'z' in clojure

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?

like image 289
ntalbs Avatar asked Jul 26 '12 13:07

ntalbs


4 Answers

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)
like image 183
mikera Avatar answered Nov 18 '22 23:11

mikera


According to this StackOverflow Answer a simple solution would be:

(map char (range 97 123))

like image 30
Syssiphus Avatar answered Nov 18 '22 23:11

Syssiphus


AFAIK, no such a fancy way as Scala. How about

(flatten (partition 1 "abcdefghijklmnopqrstuvwxyz"))

Edit

More fancy way, thanks to @rhu

(seq "abcdefghijklmnopqrstuvwxyz") ; if you copied this from an earlier version, \w and \v were in the wrong positions
like image 9
xiaowl Avatar answered Nov 19 '22 00:11

xiaowl


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

like image 3
Dave Yarwood Avatar answered Nov 18 '22 22:11

Dave Yarwood