purescript-random icon indicating copy to clipboard operation
purescript-random copied to clipboard

Add `shuffle` function

Open mjepronk opened this issue 6 years ago • 2 comments

I think there is not yet a shuffle function in a general purpose library (I did find one in quickcheck, but it uses the Gen monad). I'm thinking something like this:

shuffle :: Array a -> Effect (Array a)

Would it make sense to add it here? Would you like a PR (it might add some dependencies though, notably purescript-arrays)? I think a basic implementation using the Yates-Fisher algorithm in the ST monad would be the most performant.

mjepronk avatar Aug 24 '19 15:08 mjepronk

Was just looking for the same!

i-am-the-slime avatar Aug 03 '21 12:08 i-am-the-slime

I feel like it's probably out of scope for the library, partially because it's too specific - if we add this but you want to shuffle a List, then what? How about a NonEmptyArray and NonEmptyList, or maybe even a Foldable? etc.

My solution to this usually is to do something like:

shuffle :: ∀ a. Array a -> Effect (Array a)
shuffle xs = map fst <<< Array.sortWith snd <$> traverse (\x -> Tuple x <$> Random.random) xs

Obviously very inefficient compared to Fisher-Yates, but anecdotally I've not really encountered a situation where it was a problem yet.

garyb avatar Aug 03 '21 14:08 garyb