[英]Learning Haskell: Making a function that returns a list of elements that only appear once
I'm learning Haskell and I'm trying to make a recursive function that receives a List of integers and returns a List of integers that only appears once in the list ( once:: [Int] -> [Int]
), so, for example, if the input list is [4, 8, 1, 5, 1, 6, 2, 3, 4, 2]
the return would be [8, 5, 6, 3]
, but I'm having some problems making the code, in how to make this into a recursive function.我正在学习 Haskell 并且我正在尝试制作一个递归 function ,它接收一个整数列表并返回一个仅在列表中出现一次的整数列表(
once:: [Int] -> [Int]
),所以,例如,如果输入列表是[4, 8, 1, 5, 1, 6, 2, 3, 4, 2]
则返回[8, 5, 6, 3]
,但我遇到了一些问题制作代码,如何将其变成递归 function。
I'm also trying to make it using list comprehension, I'm currently reading about it on Learn You A Haskell, but um also stuck, so if you also have an idea on how to make it using list comprehension I would be thankful to see how both implementations work.我也在尝试使用列表理解来实现它,我目前正在Learn You A Haskell 上阅读它,但嗯也卡住了,所以如果你也知道如何使用列表理解来实现它,我将不胜感激看看这两种实现是如何工作的。
Edit:编辑:
once [] = []
once (x:xs)
| (x `notElem` xs) = x : once xs
| otherwise = once xs
But as it is my code is doing the exact opposite, is returning me the repeated elements, and when I try to invert the return of the guards it just returns the complete list without the repeated elements, I'm really out of ideas on how to make it return what I want, only the unique elements that apear once in the list.但是因为我的代码正在做完全相反的事情,正在返回重复的元素,当我尝试反转守卫的返回时,它只返回没有重复元素的完整列表,我真的不知道如何让它返回我想要的,只有在列表中出现一次的唯一元素。
There are basically three possible cases:基本上有三种可能的情况:
x
is an element in the remaining list xs
, then we skip that item and filter out all items in the tail when we recurse;x
是剩余列表xs
中的一个元素,那么我们在递归时跳过该项并过滤掉尾部的所有项; andx
does not appear in the rest of the list xs
, in that case we yield x
, and recurse on xs
.x
没有出现在列表xs
的 rest 中,在这种情况下,我们产生x
并在xs
上递归。 The function thus looks like: function 因此看起来像:
once :: [Int] -> [Int]
once [] = []
once (x:xs)
| x `elem` xs = …
| otherwise = …
I leave it as an exercise to fill in the …
parts.我把它作为练习来填写
…
部分。 For the second case, you can make use of filter:: (a -> Bool) -> [a] -> [a]
.对于第二种情况,您可以使用
filter:: (a -> Bool) -> [a] -> [a]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.