简体   繁体   English

如何终止 haskell 中的数组修改 function?

[英]How to terminate an array modification function in haskell?

So I have this function...所以我有这个 function...

removeDuplicate :: [CustomType] -> [CustomType]
removeDuplicate [] = []
removeDuplicate [x] = [x]
removeDuplicate [x, y] = 
    if x==y then [x]
    else [x, y]
removeDuplicate (x:y:xs) = 
    if x==y
        then removeDuplicate ([x] ++ xs)
    else removeDuplicate ([y] ++ xs ++ [x])

Here, I have to check if there is an element in the array(sorted) which is equal to other elements in the array.在这里,我必须检查数组中是否有一个元素(已排序)与数组中的其他元素相等。

I am unable to work on a termination condition for this function.我无法处理此 function 的终止条件。 It just goes into an infinite loop over here.它只是在这里进入无限循环。

Normally, I could have used a visited array or count for this kind of situation but I'm new to Haskell and I am not sure what is the way to handle this situation.通常,对于这种情况,我可以使用已访问数组或计数,但我是 Haskell 的新手,我不确定处理这种情况的方法是什么。

PS Please let me know if any other details are needed. PS如果需要任何其他细节,请告诉我。

removeDuplicate ([y] ++ xs ++ [x]) does not reduce the size of the array, and will thus eventually keep cycling the list. removeDuplicate ([y] ++ xs ++ [x])不会减小数组的大小,因此最终会继续循环列表。 Indeed, if you have a list [1,2,4] , it wll be called with removeDuplicate [1,2,4] , then removeDuplicate [2,4,1] and then removeDuplicate [4,1,2] and thus again removeDuplicate [1,2,4] , this will keep repeating itself.事实上,如果你有一个列表[1,2,4] ,它将被调用removeDuplicate [1,2,4] ,然后removeDuplicate [2,4,1] ,然后removeDuplicate [4,1,2] ,因此再次removeDuplicate [1,2,4] ,这将不断重复。

You should ensure that you each time work on a smaller list.您应该确保每次都在较小的列表上工作。 This can here be done by just emitting the这可以通过发出

removeDuplicate :: Eq a => [a] -> [a]
removeDuplicate [] = []
removeDuplicate [x] = [x]
removeDuplicate (x:xs@(y:_))
    | x == y = removeDuplicate xs
    | otherwise = x : removeDuplicate xs

This will only filter out duplicates if these are "neighbors", you thus can for example sort the list as a pre-processing step.如果这些是“邻居”,这只会过滤掉重复项,因此您可以例如对列表进行排序作为预处理步骤。

If you want to handle lists where the duplicates can occur at any location, you should work with an accumulator that keeps track of the already seen items:如果要处理可能在任何位置出现重复的列表,则应使用累加器来跟踪已看到的项目:

removeDuplicates :: Eq a => [a] -> [a]
removeDuplicates = go []
    where go _ [] = []
          go seen (x:xs)
               | x `elem` seen = …
               | otherwise = …

where I leave implementing the parts as an exercise.我把实现部分作为练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM