在增加的同时从列表中提取 [英] Take From a List While Increasing

查看:85
本文介绍了在增加的同时从列表中提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个价值列表,我希望从价值增加的时候拿走。我认为它会始终将列表的头部,然后将其与下一个值进行比较。只要这种情况继续增加,功能将继续发挥作用。

  takeIncreasing ::(Ord a)返回一个列表元素,该列表元素的返回值小于或等于前面的值。 => [a]  - > [a] 
takeIncreasing [1,2,3,4,3,5,6,7,8] - 应返回[1,2,3,4]

折叠可以将累积的上一个元素与下一个值进行比较,如果条件得到满足,但会继续到列表的末尾。我希望函数在第一个实例中不能满足约束。

这看起来像是一个monad的应用程序,但不能确定现有monad是否可以完成此操作。

解决方案


折叠会延续到列表的末尾。我希望函数在第一个实例中不能满足约束。

正确的折叠可能导致短路:

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

然后,

  \>好玩[1,2,3,4,3,undefined] 
[1,2,3,4]

或无限大小列表:

  \> fun $ [1,2,3,4,3] ++ [1 ..] 
[1,2,3,4]


I have a list of values that I would like to take from while the value is increasing. I assume it would always take the head of the list and then compare it to the next value. The function will continue to take as long as this continues to increase. Upon reaching an list element that is less than or equal the pervious 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 fold could compare the last element of the accumulation with the next value and append if the condition is met, but would continue to the end of the list. I would like the function to stop taking at the first instance the constraint is not met.

This seems like an application of a monad but cannot determine if an existing monad accomplishes this.

解决方案

A fold [...] would continue to the end of the list. I would like the function to stop taking at the first instance the constraint is not met.

A right fold can short circuit:

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

then,

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

or infinite size list:

\> fun $ [1,2,3,4,3] ++ [1..]
[1,2,3,4]

这篇关于在增加的同时从列表中提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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