Haskell迭代列表4 elem

时间:2018-04-07 15:34:49

标签: list haskell recursion

如何逐个迭代四元素列表,然后将这四张卡添加到元组中?

基本上这个功能可以接收要杀死的套装,按顺序玩的牌以及先玩过的玩家。

该游戏是由双人玩的,所以它返回一个元组,其中第一对夫妇赢得了胜利,而第二对夫妇获胜。

winnedCards:: Suit-> [Card] -> Int -> ([Card],[Card])
winnedCards [] _ = ([],[])
winnedCards (Suit type) cardsPlayed positionFirstPlayPerson
 | snd(xs) == 3 = (take 4 (cardsPlayed),[])
 | snd(xs) == 1 = (take 4 (cardsPlayed),[])
 | otherwise = ([],take 2 (cardsPlayed))
 where xs = whoHasWon (take 4 (cardsPlayed)) (Suit type)

whoHasWon返回获胜者的位置。我认为我必须谨慎,因为我必须迭代4乘4,然后在每次迭代后将结果添加到元组。

1 个答案:

答案 0 :(得分:3)

正如Willem Van Onsem在评论中提到的,你的功能似乎做了太多的工作。如果您尝试将列表拆分为四元组,请将其与逻辑的其余部分分开。

toFourTuple :: [a] -> [(a, a, a, a)]
toFourTuple [] = []
toFourTuple (a:b:c:d:rest) = (a, b, c, d) : toFourTuple rest
toFourTuple _  = error "list not divisible by four"
                 -- how should this be handled?

对于其他人,知道Monoid a => (a, a)的Monoid实例将mappend实现为mappend (x, y) (x', y') = (x <> x', y <> y')可能很有用,因此如果生成(leftside, rightside)子列表的列表,你可以mconcat他们在一起。

xs = [ ([1]   , [3])
     , ([2, 4], [5])
     , ([6]   , [7, 9, 11, 13])
     ]
mconcat xs = ([1,2,4,6],[3,5,7,9,11,13])

当然这也是渐进的。

-- |Separates [Int] into ([odds], [evens])
splitByMod2 :: [Int] -> ([Int], [Int])
splitByMod2 [] = ([], [])
splitByMod2 (x:xs)
  | odd x  = ([x], []) `mappend` splitByMod2 xs
  | even x = ([], [x]) `mappend` splitByMod2 xs
  | otherwise = error "This cannot happen"