I have a filterFirst function that only works the right way some of the time and I'm not sure why. The function should receive a Boolean argument and if it's false, it should remove the first element in the list; if not, it should leave the list alone.
Here are two conditional functions I've been using:
isNegative :: Int -> Bool
isNegative x
| x < 0 = True
| otherwise = False
isPositive:: Int -> Bool
isPositive x
| x > 0 = True
| otherwise = False
Here's the function:
filterFirst :: (a -> Bool) -> [a] -> [a]
filterFirst x xs = foldr condition (\x -> []) xs True
where
condition y ys True
| x y = y : ys True
| otherwise = ys False
condition y ys False = y : ys False
filterFirst
returns the correct answer with:
filterFirst isNegative [1,2,(-3)]
[2,-3]
But then this actually filters out the negative:
filterFirst isPositive [1,2,(-3)]
[1,2]
Why is it removing the negative number from the list and not the first element?
Also, and this might need to be a secondary post, but is there a way to change this slightly so that it filters the last element if the condition is met?