问题
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.
Example
the previous number is a multiple of 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.
I tried with scanl1
, foldl1
, and map
but I'm new to Haskell and I have not been able to do so; any clue?
回答1:
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:
[5,3]
回答2:
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
.
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]
λ>
来源:https://stackoverflow.com/questions/58687161/how-to-filter-list-elements-in-haskell-based-on-previous-value-in-the-list