gpt4 book ai didi

haskell - 从列表列表中删除整数对,同时保持原始顺序 - Haskell

转载 作者:行者123 更新时间:2023-12-02 10:11:39 24 4
gpt4 key购买 nike

我一直在努力从列表列表中删除重复项,同时保留余数和空列表的原始位置。比方说:

list1 = [[1],[2],[1,2],[4],[1,4]]
list2 =[[1],[2],[1,2],[4],[1,4],[2,4]]
list3 = [[1,2,4],[1,4],[2,4],[1,4],[1,2,4]]

那么输出应该是:

[[],[],[],[],[1]]

[[],[],[],[],[1],[2,4]]

[[],[],[,],[],[2,4]]

(删除哪些对并不重要)

但是,只有首先压平列表,然后我失去空列表的原始位置,我才能使其正常工作。如果有人知道我如何解决这个问题,我将不胜感激!

代码很困惑,但适用于平面列表:

remPair [] = []
remPair (x:xs) = if elem x xs then
let
n = elemIndices x xs
(ys, zs) = splitAt (head n) xs
in remPair (ys ++ (drop 1 zs))
else [x] ++ remPair xs

最佳答案

正确响应

我尝试用 Haskell 方式解决这个问题,但是这段代码的性能很糟糕并且很难阅读。我只是想看看能否解决这个问题。

import Data.List (elemIndices)

appendHead :: a -> [[a]] -> [[a]]
appendHead x [] = [[x]]
appendHead x (ys:yss) = (x:ys):yss

-- | count how many time an element occurs in a list of lists
count :: Eq a => a -> [[a]] -> Int
count _ [] = 0
count x (ys:yss) = (length $ elemIndices x ys) + count x yss

-- | assume count is 1 or greater for simplicity
rmAllButLast :: Int -> Int -> [[Int]] -> [[Int]]
rmAllButLast x xCount yss =
if xCount == 0
then yss
else
let protectLastElement cond = if even xCount then cond else True in
snd $
foldl
(\(xIndex,acc) ys ->
(\y -> acc++[y]) <$> foldl
(\(xIndex,acc) y ->
if protectLastElement (xIndex < xCount-1) && x == y
then (xIndex+1, acc)
else (xIndex, acc++[y]))
(xIndex, [])
ys
)
(0, [])
yss

rmPairs :: [[Int]] -> [[Int]]
rmPairs [] = []
rmPairs ([]:yss) = [] : rmPairs yss
rmPairs ((x:xs):yss) =
let xCount = count x (xs:yss) in
if xCount == 0
then appendHead x $ rmPairs (xs:yss)
else rmPairs $ rmAllButLast x xCount (xs:yss)

旧响应

编辑:下面的代码不是作者想要的,但我会保留它,以便下面的评论有意义。

如果你想删除重复项(任何发生一次或多次的事情都会减少到一个值)或实际对(有两个这个值,所以如果有偶数,则删除它们两个,我不是100% x 的值,则全部去除,如果 x 为奇数则有一个)。假设是前者并且不考虑性能:

remPair :: [[Int]] -> [[Int]]
remPair [] = []
remPair ([]:yss) = [] : remPair yss
remPair (xs:yss) = remPairFromFlat xs : remPair yss
where
flatYss = concat yss
remPairFromFlat [] = []
remPairFromFlat (z:zs) =
let flat = zs ++ flatYss in
if z `elem` flat
then remPairFromFlat zs
else z : remPairFromFlat zs

remPair迭代列表的列表。如果第一个列表不为空,它将展平列表的其余部分,然后迭代 xs 的元素并创建一个本地平面列表 ysxs的尾部.

关于haskell - 从列表列表中删除整数对,同时保持原始顺序 - Haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58755144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com