如何根据列表中的先前值过滤Haskell中的列表元素? [英] How to filter list elements in Haskell based on previous value in the list?

查看:62
本文介绍了如何根据列表中的先前值过滤Haskell中的列表元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力在Haskell中创建一个函数,该函数根据条件基于列表中的上一个元素来过滤列表中的数字.

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.

示例

上一个数字是2的倍数

myFunction [1, 2, 5, 6, 3]
# expected output:
[5,3]

我知道如何应用filter,但是到目前为止,我已经看到过滤器一次只接受一个参数.

I know how to apply filter but so far I have seen that the filters take only one argument at a time.

我尝试使用scanl1foldl1map,但是我是Haskell的新手,但我无法这样做.有任何线索吗?

I tried with scanl1, foldl1, and map but I'm new to Haskell and I have not been able to do so; any clue?

推荐答案

编辑

应该是:

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)

因为输入:

myFuntion [1, 2, 5, 6, 3]

正确的输出应为:

[5,3]

这篇关于如何根据列表中的先前值过滤Haskell中的列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆