鉴于代码:
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]
我如何编写函数shuffle
,它将获取Int列表,并根据这些int拆分另一个列表。 int列表的示例是intList = [20,23,24,13],其中shuffle将在第20个元素之后拆分列表,交错,在第23个元素之后拆分,交错,等等。
答案 0 :(得分:1)
好的,你想要的基本上如下:
给定列表xs
和索引[a1, a2, a3, ..]
,在xs
处拆分a1
,交错,将其拆分为a2
并交错,依此类推。
现在我们有两个功能:
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
尝试自己编写其余的这些功能。
step
可以很容易地表达为let (x1, x2) = split index xs in interleave x1 x2
。基本上,shuffle
的其余部分可以写为shuffle indices newList
。
答案 1 :(得分:0)
我明白了:
shuffle [] xs = Ok (xs)
shuffle (x:xs) list = case (split x list) of
Fail -> Fail
Ok (l1, l2) -> shuffle xs (interleave l1 l2)