簡體   English   中英

在 Scala 中執行塊 n 次是否有簡短的語法?

[英]Is there a brief syntax for executing a block n times in Scala?

當我想重復執行 n 次時,我發現自己編寫了這樣的代碼:

for (i <- 1 to n) { doSomething() }

我正在尋找更短的語法,如下所示:

n.times(doSomething())

Scala 中已經存在這樣的東西了嗎?

編輯

我想過使用 Range 的 foreach() 方法,但是該塊需要采用一個它從不使用的參數。

(1 to n).foreach(ignored => doSomething())

您可以使用 Pimp My Library 模式輕松定義一個。

scala> implicit def intWithTimes(n: Int) = new {        
     |   def times(f: => Unit) = 1 to n foreach {_ => f}
     | }
intWithTimes: (n: Int)java.lang.Object{def times(f: => Unit): Unit}

scala> 5 times {
     |   println("Hello World")
     | }
Hello World
Hello World
Hello World
Hello World
Hello World

Range 類有一個 foreach 方法,我認為這正是您所需要的。 例如,這個:

 0.to(5).foreach(println(_))

產生

0
1
2
3
4
5

使用scalaz 5

doSomething.replicateM[List](n)

使用scalaz 6

n times doSomething

這與大多數類型的預期一樣(更准確地說,對於每個 monoid ):

scala> import scalaz._; import Scalaz._; import effects._;
import scalaz._
import Scalaz._
import effects._

scala> 5 times "foo"
res0: java.lang.String = foofoofoofoofoo

scala> 5 times List(1,2)
res1: List[Int] = List(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

scala> 5 times 10
res2: Int = 50

scala> 5 times ((x: Int) => x + 1).endo
res3: scalaz.Endo[Int] = <function1>

scala> res3(10)
res4: Int = 15

scala> 5 times putStrLn("Hello, World!")
res5: scalaz.effects.IO[Unit] = scalaz.effects.IO$$anon$2@36659c23

scala> res5.unsafePerformIO
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

您也可以說doSomething replicateM_ 5僅當您的doSomething是慣用值時才有效(請參閱Applicative )。 它具有更好的類型安全性,因為您可以這樣做:

scala> putStrLn("Foo") replicateM_ 5
res6: scalaz.effects.IO[Unit] = scalaz.effects.IO$$anon$2@8fe8ee7

但不是這個:

scala> { System.exit(0) } replicateM_ 5
<console>:15: error: value replicateM_ is not a member of Unit

讓我看看你在 Ruby 中實現了這一點。

我不知道圖書館里有什么。 您可以定義可以根據需要導入的實用程序隱式轉換和類。

class TimesRepeat(n:Int) {
  def timesRepeat(block: => Unit): Unit = (1 to n) foreach { i => block }
}
object TimesRepeat {
  implicit def toTimesRepeat(n:Int) = new TimesRepeat(n)
}

import TimesRepeat._

3.timesRepeat(println("foo"))

在我寫這篇文章的時候,拉胡爾剛剛發布了一個類似的答案......

它可以像這樣簡單:

scala> def times(n:Int)( code: => Unit ) {
          for (i <- 1 to n) code
       }
times: (n: Int)(code: => Unit)Unit

scala> times(5) {println("here")}
here
here
here
here
here
def times(f: => Unit)(cnt:Int) :Unit = {
  List.fill(cnt){f}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM