How to call a method n times in Scala?

后端 未结 5 1029
轮回少年
轮回少年 2021-02-18 23:04

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: S         


        
5条回答
  •  梦毁少年i
    2021-02-18 23:43

    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 for Endo[A]

    N times func apply target
    

    So that:

    scala> import scalaz._; import Scalaz._
    import scalaz._
    import Scalaz._
    
    scala> Endo((_:Int) * 2).multiply(5)
    res3: scalaz.Endo[Int] = Endo()
    
    scala> res1(3)
    res4: Int = 96
    

提交回复
热议问题