如何在Scala中调用一个方法n次?
我有一个例子,我想调用一个方法 n 次,其中 n 是一个 Int。在 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 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
}
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为最简单的解决方案是使用范围:
但您也可以创建这个小辅助函数:
此代码将打印“hello”10 次。隐式转换
intTimes
使方法times
可用于所有整数。所以在你的情况下它应该看起来像这样:The simplest solution is to use range, I think:
But you can also create this small helper function:
this code will print "hello" 10 times. Implicit conversion
intTimes
makes methodtimes
available on all ints. So in your case it should look like this:不完全是您问题的答案,但如果您有同态(即转换
A => A
),则使用 scalaz 您可以将自然幺半群用于Endo[A]
所以:
Not quite an answer to your question, but if you had an endomorphism (i.e. a transformation
A => A
), then using scalaz you could use the natural monoid forEndo[A]
So that:
一个更实用的解决方案是使用带有不可变队列和
Queue
的fill
和drop
方法的折叠:或者更好的是,捕获您的
Event
子类中的"supply"
/"sale"
区别,避免尴尬的Option[BigDecimal]
业务:这并不能直接回答你的问题(如何调用函数指定的次数),但这绝对更惯用。
A more functional solution would be to use a fold with an immutable queue and
Queue
'sfill
anddrop
methods:Or even better, capture your
"supply"
/"sale"
distinction in subclasses ofEvent
and avoid the awkwardOption[BigDecimal]
business:This doesn't directly answer your question (how to call a function a specified number of times), but it's definitely more idiomatic.
简单、内置,您将获得单位列表作为纪念品!
但如果您进行函数式编程,则永远不需要多次调用函数。
Simple, built-in, and you get a List of Units as a souvenier!
But you'll never need to call a function multiple times if you're programming functionally.
通过递归:
With recursion: