Scala - 组合函数 n 次 [英] Scala - compose function n times

查看:44
本文介绍了Scala - 组合函数 n 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function that looks like this:

def emulate: (Cpu => Cpu) => (Cpu => Cpu) = render => {
  handleOpcode   andThen
  handleTimers   andThen
  handleInput    andThen
  debug          andThen
  render
}

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

I want to call the handleOpcode function n number of times (say 10 times). In Haskell I might write a function like so:

ntimes n f = foldr (.) id (replicate n f)

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

But in Scala, I'm not sure how I might write it. I tried:

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

但是类型都错了.

有没有简单的方法来实现这一目标?理想情况下,无需创建我自己的函数.也许 Scalaz 有什么东西?

Is there a simple way to achieve this? Ideally without having to create my own function. Something in Scalaz perhaps?

推荐答案

你可以使用 Function.chain 方法:

scala> val add1 = (x:Int) => x+1
add1: Int => Int = <function1>

scala> val add5 = Function.chain(List.fill(5)(add1))
add5: Int => Int = <function1>

scala> add5(5)
res1: Int = 10

这篇关于Scala - 组合函数 n 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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