Reputation: 76
Given the code:
data Error a = Fail|Ok a
deriving (Eq, Ord, Show)
split :: Int -> [a] -> (Error ([a],[a]))
split 0 list = Ok ([], list)
split n list
| n < 0 = Fail
| n > length (list) = Fail
| otherwise = Ok (take n list, drop n list)
interleave :: [a] -> [a] -> [a]
interleave list [] = list
interleave [] list = list
interleave (x:xs) (y:ys) = x : y : interleave xs ys
shuffle :: [Int] -> [a] -> Error [a]
How I write the function shuffle
which will take a list of Ints, and split another list based on those ints. Examples of the int list would be intList = [20,23,24,13] where shuffle will split a list after the 20th element, interleave, split after the 23rd element, interleave, and so on.
Upvotes: 0
Views: 137
Reputation: 76
I figured it out:
shuffle [] xs = Ok (xs)
shuffle (x:xs) list = case (split x list) of
Fail -> Fail
Ok (l1, l2) -> shuffle xs (interleave l1 l2)
Upvotes: 0
Reputation: 7360
Okay, what you want is basically the following:
Given a list xs
and indices [a1, a2, a3, ..]
, split xs
at a1
, interleave, split it at a2
and interleave, and so on...
Now that leaves us with two functions:
step :: Int -> [a] -> [a]
step index xs = ??? -- something with split and interleave
shuffle :: [a]
shuffle [] xs = xs
shuffle (i:indices) xs = let newList = step i xs
in ??? -- something with recursion
Try to write the rest of these functions on yourself.
step
can easily be expressed aslet (x1, x2) = split index xs in interleave x1 x2
. Basically, the rest ofshuffle
can be written asshuffle indices newList
.
Upvotes: 1