Why util.Random.shuffle doesn't work on Array?

2,480 views
Skip to first unread message

Venusaur

unread,
Mar 6, 2012, 9:41:40 PM3/6/12
to scala-user
Hi. I'm new in scala.
After I learned about Random, I wanted to test methods of Random.

However, I couldn't understand why shuffle can accept List, but not
Array.

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Client VM, Java
1.7.0_02)
.
Type in expressions to have them evaluated.
Type :help for more information.

scala> util.Random.shuffle(List(1, 3, 5, 7, 9))
res0: List[Int] = List(3, 9, 5, 7, 1)

scala> util.Random.shuffle(Array(1, 3, 5, 7, 9))
<console>:8: error: inferred type arguments [Int,Array] do not conform
to method
shuffle's type parameter bounds [T,CC[X] <: TraversableOnce[X]]
util.Random.shuffle(Array(1, 3, 5, 7, 9))
^

scala>


Is there any workarounds for this?

Thanks in advance.

Matthew Pocock

unread,
Mar 6, 2012, 10:02:28 PM3/6/12
to Venusaur, scala-user
Hi,

On 7 March 2012 02:41, Venusaur <bup...@gmail.com> wrote:
Hi. I'm new in scala.
After I learned about Random, I wanted to test methods of Random.

However, I couldn't understand why shuffle can accept List, but not
Array.

Array is a bit of a 2nd class citizen in the collections library.
 
scala> util.Random.shuffle(Array(1, 3, 5, 7, 9))
<console>:8: error: inferred type arguments [Int,Array] do not conform
to method
 shuffle's type parameter bounds [T,CC[X] <: TraversableOnce[X]]
             util.Random.shuffle(Array(1, 3, 5, 7, 9))
                         ^

You could try .toSeq on the array:

 util.Random.shuffle(Array(1, 3, 5, 7, 9).toSeq)

I think arrays are usually coerced into traversables via an implicit conversion to WrappedArray. It looks like the type of shuffle is preventing this conversion from happening. Adding .toSeq to the array forces this conversion.


Thanks in advance.

No problem. In general, I'd advise you stay clear of arrays in scala unless you are talking to Java or have a real-world performance bottleneck that is best addressed with a mutable, fixed-length data structure.

Matthew

--
Dr Matthew Pocock
Integrative Bioinformatics Group, School of Computing Science, Newcastle University
skype: matthew.pocock
tel: (0191) 2566550

Michael Schmitz

unread,
Mar 7, 2012, 12:16:39 PM3/7/12
to Matthew Pocock, Venusaur, scala-user
It's so unfortunate that we need to recommend against arrays ;-(
Reply all
Reply to author
Forward
0 new messages