在Scala中使用累加器映射列表的功能方法 [英] Functional way to map over a list with an accumulator in Scala

查看:213
本文介绍了在Scala中使用累加器映射列表的功能方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写简洁的代码以映射到列表,一边累积值,一边在输出列表中使用该值.

使用递归函数和模式匹配很简单(请参见下文).但是我想知道是否有一种方法可以使用诸如map和fold等组合函数的函数编程系列来实现.显然,除非您使用在调用外部定义的可变变量并在主体中对其进行修改,否则map和fold不好用. /p>

也许我可以用State Monad来做到这一点,但想知道是否有一种我缺少的方法,并且利用了Scala标准库.

// accumulate(List(10, 20, 20, 30, 20))
// => List(10, 30, 50, 80, 100,)

def accumulate(weights : List[Int], sum : Int = 0, acc: List[Int] = List.empty) : List[Int] = {
  weights match {
    case hd :: tl =>
      val total = hd + sum
      accumulate(tl, total, total :: acc)
    case Nil =>
      acc.reverse
  }
}

解决方案

这可以通过扫描来完成:

val result = list.scanLeft(0){case (acc, item) => acc+item}

扫描会将初始值0包含在输出中,因此您必须将其删除:

result.drop(1)

I would like to write succinct code to map over a list, accumulating a value as I go and using that value in the output list.

Using a recursive function and pattern matching this is straightforward (see below). But I was wondering if there is a way to do this using the function programming family of combinators like map and fold etc. Obviously map and fold are no good unless you use a mutable variable defined outside the call and modify that in the body.

Perhaps I could do this with a State Monad but was wondering if there is a way to do it that I'm missing, and that utilizes the Scala standard library.

// accumulate(List(10, 20, 20, 30, 20))
// => List(10, 30, 50, 80, 100,)

def accumulate(weights : List[Int], sum : Int = 0, acc: List[Int] = List.empty) : List[Int] = {
  weights match {
    case hd :: tl =>
      val total = hd + sum
      accumulate(tl, total, total :: acc)
    case Nil =>
      acc.reverse
  }
}

解决方案

This could be done with scan:

val result = list.scanLeft(0){case (acc, item) => acc+item}

Scan will include the initial value 0 into output so you have to drop it:

result.drop(1)

这篇关于在Scala中使用累加器映射列表的功能方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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