[英]How to filter list elements in Haskell based on previous value in the list?
I'm working on creating a function in Haskell that filters the numbers of a list on a condition based on the previous element in the list.我正在努力在 Haskell 中创建一个 function,它根据列表中的前一个元素过滤列表的编号。
Example例子
the previous number is a multiple of 2前一个数字是 2 的倍数
myFunction [1, 2, 5, 6, 3]
# expected output:
[5,3]
I know how to apply filter
but so far I have seen that the filters take only one argument at a time.我知道如何应用filter
,但到目前为止我已经看到过滤器一次只接受一个参数。
I tried with scanl1
, foldl1
, and map
but I'm new to Haskell and I have not been able to do so;我尝试使用scanl1
、 foldl1
和map
但我是 Haskell 的新手,我无法这样做; any clue?任何线索?
Edit编辑
It should be:它应该是:
myFunction [] = []
myFunction [x] = []
myFunction [x,y] = if (x `mod` 2) == 0 then [y] else []
myFunction (x:y:xs) = if (x `mod` 2) == 0
then y : (myFunction xs)
else myFunction (y:xs)
because for the input:因为对于输入:
myFuntion [1, 2, 5, 6, 3]
the correct output should be:正确的 output 应该是:
[5,3]
If you prefer to use library functions, there is a known trick for this sort of situations, which consists in zip'ing the input with its own tail, that is the initial list minus its first element.如果您更喜欢使用库函数,对于这种情况有一个已知的技巧,它包括使用自己的尾部压缩输入,即初始列表减去其第一个元素。
λ>
λ> inls = [1, 2, 5, 6, 3]
λ>
λ> let pairs = zip (tail inls) inls
λ> pairs
[(2,1),(5,2),(6,5),(3,6)]
λ>
and the resulting pair list is then an easy target for map
and filter
.然后生成的对列表是map
和filter
的简单目标。 As in:如:
λ> let myFunction ls = let pairs = zip (tail ls) ls in map fst $ filter (even . snd) pairs
λ>
λ> ls
[1,2,5,6,3]
λ>
λ> myFunction ls
[5,3]
λ>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.