I’m just puzzled with this one, it’s a Haskell loop-sort-of-thing which I can’t figure out how to write. Basically, I’ve defined three functions split, riffle and shuffle.
split :: [a] -> ([a],[a])
split xs = splitAt (length xs `div` 2) xs
riffle :: [a] -> [a] -> [a]
riffle xs [] = xs
riffle [] ys = ys
riffle (x:xs) (y:ys) = x:y:riffle xs ys
shuffle :: Int -> [a] -> [a]
shuffle 0 xs = xs
shuffle n xs = shuffle (n-1) (riffle a b)
where (a, b) = split xs
Basically split just splits a list in half, riffle is supposed to ‘interlace’ two lists, so for example:
riffle [1,2,3] [4,5,6] = [1,4,2,5,3,6]
And shuffle is to iterate the amount of splitting and riffling of the list items. Now I need to define a function repeats which outputs how many iterations of shuffle would it take to get the original list again. The function is defined as such:
repeats :: [Int] -> Int
I’m just stuck as to how you can perform a loop over the shuffle… I think it has something to do with list comprehension but I couldn’t get anything. I have yet to try a lambda expression but I don’t think it’s necessary. By the way, the shuffle should be done on lists with even number of items. Any ideas?
One way of solving this is to take advantage of laziness and use
iterateto generate the infinite list of iterated shuffles of the input.The first element of the list is the original one, so we drop that with
tail, then usetakeWhileto get the ones that were different from the original.Now, you just need to take the
lengthof that list and add one to get the required number of shuffles.