Skip to content

Commit babb422

Browse files
committed
shuffle, shufflePure
1 parent eb6e966 commit babb422

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

pub/functora/src/prelude/Functora/Prelude.hs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ module Functora.Prelude
104104
randomListPure,
105105
randomByteString,
106106
randomByteStringPure,
107+
shuffle,
108+
shufflePure,
107109
expBackOff,
108110
expBackOffSecondsAfter,
109111
secondsToNominalDiffTime,
@@ -1084,6 +1086,21 @@ randomByteStringPure qty =
10841086
first BS.pack
10851087
. randomListPure qty
10861088

1089+
shuffle :: [a] -> IO [a]
1090+
shuffle xs = do
1091+
gen <- Random.newStdGen
1092+
pure $ shufflePure gen xs
1093+
1094+
shufflePure :: (Random.RandomGen g) => g -> [a] -> [a]
1095+
shufflePure _ [] = []
1096+
shufflePure _ [x] = [x]
1097+
shufflePure prevGen xs =
1098+
case splitAt idx xs of
1099+
(xs0, x : xs1) -> x : shufflePure nextGen (xs0 <> xs1)
1100+
_ -> error "IMPOSSIBLE_SHUFFLE_PURE"
1101+
where
1102+
(idx, nextGen) = Random.randomR (0, length xs - 1) prevGen
1103+
10871104
expBackOff :: forall a. (From a Natural) => a -> Natural
10881105
expBackOff = (2 ^) . from @a @Natural
10891106

0 commit comments

Comments
 (0)