0

我有几个与 fold_left/right 相关的问题。

  1. 如何累积两个或多个值?如果使用元组是好的解决方案?
  2. 如何中止 fold 的工作?例如,我们必须找到任何数字的第一次出现,并返回位置。我的意思是休息(C++)。
4

2 回答 2

1

zurgl's comment is a great answer (maybe move it down to the answer region).

You can use an exception to terminate a fold early. It's good to try to structure your code so you don't have to do this (in my opinion). Code without exceptions is easier to understand, more composable, parallelizable, etc.

于 2013-10-27T16:12:51.497 回答
1

we must find firstly occurrence of any number那么你必须遍历你所有的列表[1;1;1;1;5],这里不需要中止。为了处理部分递归,还有其他功能,例如 dropwhile、takewhile ... 或者您可以定义您需要的功能。将折叠视为类型之间的投影,您有一个源类型和一个带有种子值的目标类型(累加器),然后折叠是实现这种转换的过程。是的,使用元组是一个很好的解决方案,IMO。

于 2013-10-27T19:37:10.393 回答