Take from the list when zoomed

I have a list of values ​​that I would like to use while the value is increasing. I assume that he will always top the list and then compare it with the next value. The function will continue as long as it continues to increase. Upon reaching the list item that is less than or equal to the desired value, the list is returned.

takeIncreasing :: (Ord a) => [a] -> [a] takeIncreasing [1,2,3,4,3,5,6,7,8] -- Should return [1,2,3,4] 

A summary can compare the last accumulation element with the next value and add if the condition is met, but will continue to the end of the list. I would like the function to stop accepting in the first case the restriction was not fulfilled.

This is similar to a monad application, but cannot determine if the existing monad does this.

+3
list functional-programming haskell
Apr 19 '16 at 2:27
source share
4 answers

Reset [...] will continue until the end of the list. I would like the function to stop accepting in the first case the restriction was not fulfilled.

There may be a short circuit on the right:

 fun :: Ord a => [a] -> [a] fun [] = [] fun (x:xs) = x: foldr go (const []) xs x where go xfi = if i < x then x: fx else [] 

then

 \> fun [1,2,3,4,3,undefined] [1,2,3,4] 

or an endless list of sizes:

 \> fun $ [1,2,3,4,3] ++ [1..] [1,2,3,4] 
+9
Apr 19 '16 at 2:41 on
source share

Correct folds are magical, so you don’t even need to match patterns in a list.

 twi xs = foldr go (const []) xs Nothing where go x _ (Just prev) | x < prev = [] go xr _ = x : r (Just x) 
+4
Apr 19 '16 at 5:10
source share

Or one whose IMO has slightly less code complexity:

 takeIncreasing :: Ord x => [x] -> [x] takeIncreasing (x:x':xs) | x < x' = x : takeIncreasing (x':xs) | otherwise = [x] takeIncreasing xs = xs 

This is a little less smart than previous sentences. I like the inconvenient code.

+3
Apr 19 '16 at 11:53 on
source share

No crease solution:

 takeIncreasing :: Ord a => [a] -> [a] takeIncreasing [] = [] takeIncreasing (x:xs) = (x :) . map snd . takeWhile (uncurry (<)) $ zip (x:xs) xs 
+2
Apr 19 '16 at 7:31
source share



All Articles