相关疑难解决方法(0)

如何在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
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为关闭是一个很好的解决方案,但我不能让它工作.我也尝试过for-loop,但它不是一个漂亮的功能解决方案.

recursion closures loops scala anonymous-function

18
推荐指数
5
解决办法
1万
查看次数

Scala - 组合函数n次

我有一个看起来像这样的函数:

def emulate: (Cpu => Cpu) => (Cpu => Cpu) = render => {
  handleOpcode   andThen
  handleTimers   andThen
  handleInput    andThen
  debug          andThen
  render
}
Run Code Online (Sandbox Code Playgroud)

我想多次调用handleOpcode函数(比如说10次).在Haskell中,我可能会写一个这样的函数:

ntimes n f = foldr (.) id (replicate n f)
Run Code Online (Sandbox Code Playgroud)

但在Scala中,我不确定如何写它.我试过了:

def nTimes(n: Int, f: => Any) = {
  val l = List.fill(n)(f)
  l.foldRight(identity[Function]){ (x, y) => y.andThen(x) }
}
Run Code Online (Sandbox Code Playgroud)

但类型都错了.

有没有一种简单的方法来实现这一目标?理想情况下,无需创建自己的功能.也许是斯卡拉兹的东西?

scala scalaz

11
推荐指数
2
解决办法
939
查看次数

标签 统计

scala ×2

anonymous-function ×1

closures ×1

loops ×1

recursion ×1

scalaz ×1