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

后端 未结 4 1427
夕颜
夕颜 2021-01-01 20:28

I want to generate character sequence from \'a\' to \'z\'. In scala, I can generate character sequence very simply:

(\'a\' to \'z\')

But in

相关标签:
4条回答
  • 2021-01-01 21:05

    According to this StackOverflow Answer a simple solution would be:

    (map char (range 97 123))

    0 讨论(0)
  • 2021-01-01 21:05

    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))
    ("                                                                    
    0 讨论(0)
  • 2021-01-01 21:08

    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)
    
    0 讨论(0)
  • 2021-01-01 21:23

    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
    
    0 讨论(0)
提交回复
热议问题