如何在Scala中调用n次方法? [英] How to call a method n times in Scala?

查看:420
本文介绍了如何在Scala中调用n次方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我想调用一个方法n次,其中n是一个Int.在Scala中,有没有以功能性"方式做到这一点的好方法?

I have a case where I want to call a method n times, where n is an Int. Is there a good way to do this in a "functional" way in Scala?

case class Event(name: String, quantity: Int, value: Option[BigDecimal])

// a list of events
val lst = List(
    Event("supply", 3, Some(new java.math.BigDecimal("39.00"))),
    Event("sale", 1, None),
    Event("supply", 1, Some(new java.math.BigDecimal("41.00")))
    )

// a mutable queue
val queue = new scala.collection.mutable.Queue[BigDecimal]

lst.map { event =>
    event.name match {
        case "supply" => // call queue.enqueue(event.value) event.quantity times
        case "sale" =>   // call queue.dequeue() event.quantity times
    }
}

我认为闭包对此是一个很好的解决方案,但我无法使其正常运行.我也尝试过使用for循环,但这不是一个漂亮的功能性解决方案.

I think a closure is a good solution for this, but I can't get it working. I have also tried with a for-loop, but it's not a beautiful functional solution.

推荐答案

更实用的解决方案是使用带有不可变队列的折叠以及Queuefilldrop方法:

A more functional solution would be to use a fold with an immutable queue and Queue's fill and drop methods:

 val queue = lst.foldLeft(Queue.empty[Option[BigDecimal]]) { (q, e) =>
   e.name match {
     case "supply" => q ++ Queue.fill(e.quantity)(e.value)
     case "sale"   => q.drop(e.quantity)
   }
 }

甚至更好的是,在Event的子类中捕获您的"supply"/"sale"区别,并避免笨拙的Option[BigDecimal]业务:

Or even better, capture your "supply"/"sale" distinction in subclasses of Event and avoid the awkward Option[BigDecimal] business:

sealed trait Event { def quantity: Int }
case class Supply(quantity: Int, value: BigDecimal) extends Event
case class Sale(quantity: Int) extends Event

val lst = List(
  Supply(3, BigDecimal("39.00")),
  Sale(1),
  Supply(1, BigDecimal("41.00"))
)

val queue = lst.foldLeft(Queue.empty[BigDecimal]) { (q, e) => e match {
  case Sale(quantity)          => q.drop(quantity)
  case Supply(quantity, value) => q ++ Queue.fill(quantity)(value)
}}

这并不能直接回答您的问题(如何多次调用一个函数),但是肯定是比较习惯的.

This doesn't directly answer your question (how to call a function a specified number of times), but it's definitely more idiomatic.

这篇关于如何在Scala中调用n次方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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