如何在 Scala 中调用一个方法 n 次? [英] How to call a method n times in Scala?
问题描述
我有一个案例,我想调用一个方法 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.
推荐答案
一个更实用的解决方案是使用具有不可变队列和 Queue
的 fill
的折叠和 drop
方法:
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屋!