simpel Haskell列表排序/改组模式

时间:2014-11-05 14:41:06

标签: haskell

我正在尝试制作一个列入列表的算法,并根据以下操作步骤重新组织列表。

[1 , 2, 3, 4 , 5, 6, 7 , 8, 9 ]
[1 , 3, 5 , 7, 9 ] ++ [2 , 4, 6, 8 ]
[1 , 3, 5 , 7, 9 ] ++ [2 , 6] ++ [ 4, 8 ]
[1 , 3, 5 , 7, 9 , 2, 6 , 4, 8 ]

这是我到目前为止,然后我不知道接下来该做什么。有什么帮助吗?

ever xs = if xs == [] then [ ] else head xs: ever (drop 1 residue)
    Where residue 1 drop = xs

3 个答案:

答案 0 :(得分:3)

以下是CPS版本:

shuffle [] = []
shuffle xs = shuffle' xs shuffle where
    shuffle' (x:y:xs) cont = x : shuffle' xs (cont . (y:))
    shuffle'      xs  cont = xs ++ cont []

答案 1 :(得分:2)

我建议采用更加组合的方法来提高可读性。

import Data.Either

alternate :: [a -> b] -> [a] -> [b]
alternate fs = zipWith ($) (cycle fs)

shuffle = (\es -> lefts es ++ rights es) . alternate [Left,Right]

alternate旋转应用于列表的函数。在shuffleEither的构造函数交替应用。然后我们简单地将lefts和权利从列表中删除并将它们放在一起。

答案 2 :(得分:0)

这就是我的所作所为:

splitAlt :: [a] -> ([a],[a])
splitAlt = foldr (\x (ys, zs) -> (x:zs, ys)) ([],[])

splitAlt功能将[1,2,3,4,5,6,7,8,9]拆分为([1,3,5,7,9],[2,4,6,8])

shuffle :: [a] -> [a]
shuffle [] = []
shuffle xs = let (ys,zs) = splitAlt xs
             in ys ++ shuffle zs

这应该会给你你想要的结果。