Reece
Reece

Reputation: 8088

How do I create a set of characters in Scala?

I'd like to create a Set of character ranges in Scala, something like A..Za..z0..9. Here's my take:

scala> ('A' to 'Z').toSet.union(('a' to 'z').toSet).union(('0' to '9').toSet)
res3: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d)

This can't be the idiomatic way to do this. What's a better way?

Upvotes: 3

Views: 5917

Answers (5)

Andrei Nae
Andrei Nae

Reputation: 11

If you want to generate all the possible characters, doing this should generate all the values a char can take:

(' ' to '~').toSet 

Upvotes: 1

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

I guess it can't be simpler than this:

('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')

You might guess that ('A' to 'z') will include both, but it also adds some extra undesirable characters, namely:

([, \, ], ^, _, `)

Note:

This will not return a Set but an IndexedSeq. I assumed you don't mind the implementation, but if you do, and do want a Set, just call toSet to the result.

Upvotes: 1

Landei
Landei

Reputation: 54574

('0' to 'z').filter(_.isLetterOrDigit).toSet

Upvotes: 4

Blaisorblade
Blaisorblade

Reputation: 6488

A more functional version of your code is this:

scala> Traversable(('A' to 'Z'), ('a' to 'z'), ('0' to '9')) map (_ toSet) reduce (_ ++ _)

Combining it with the above solutions, one gets:

scala> Seq[Seq[Char]](('A' to 'Z'), ('a' to 'z'), ('0' to '9')) reduce (_ ++ _) toSet

If you have just three sets, the other solutions are simpler, but this structure also works nicely if you have more ranges or they are given at runtime.

Upvotes: 3

Paul Butcher
Paul Butcher

Reputation: 10852

How about this:

scala> ('a' to 'z').toSet ++ ('A' to 'Z') ++ ('0' to '9')
res0: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d)

Or, alternatively:

scala> (('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')).toSet
res0: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d)

Upvotes: 18

Related Questions