Scala – 组合函数n次
发布时间:2020-12-16 19:06:52 所属栏目:安全 来源:网络整理
导读:我有一个这样的功能: def emulate: (Cpu = Cpu) = (Cpu = Cpu) = render = { handleOpcode andThen handleTimers andThen handleInput andThen debug andThen render} 我想调用handleOpcode函数n次(比如10次).在Haskell中,我可能会写一个这样的函数: ntime
我有一个这样的功能:
def emulate: (Cpu => Cpu) => (Cpu => Cpu) = render => { handleOpcode andThen handleTimers andThen handleInput andThen debug andThen render } 我想调用handleOpcode函数n次(比如10次).在Haskell中,我可能会写一个这样的函数: ntimes n f = foldr (.) id (replicate n f) 但是在Scala中,我不知道如何写.我试过了: def nTimes(n: Int,f: => Any) = { val l = List.fill(n)(f) l.foldRight(identity[Function]){ (x,y) => y.andThen(x) } } 但是类型都是错的. 有没有一个简单的方法来实现呢?理想地,无需创建自己的功能. Scalaz还有什么? 解决方法
您可以使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |