[英]How can I define a ScalaCheck generator that produces a subset of a sequence's elements?
[英]scalacheck: define a generator for an infinite stream with some dependence on previous elements
我試圖限定Gen[Stream[A]]
為無限(懶惰地評估)流A
S其中每個元素A
可以依賴於前一元素。
作為最小的情況,我們可以采用Gen[Stream[Int]]
,其中下一個元素是上一個元素的+1
或+2
。 作為參考,下面是一個haskell實現:
increasingInts :: Gen [Int]
increasingInts = arbitrary >>= go
where
go seed = do
inc <- choose (1,2)
let next = seed + inc
rest <- go next
return (next : rest)
我已經在Stream[Gen[A]]
上嘗試過Gen.sequence
,但是得到了stackoverflow。 我也試着定義Gen
從頭開始,但構造gen
的Gen
是私人的,私人的方法/類型的作品。
這種嘗試還會產生堆棧溢出。
def go(seed: Int): Gen[Stream[Int]] =
for {
inc <- Gen.choose(1, 2)
next = seed + inc
rest <- Gen.lzy(go(next))
} yield next #:: rest
val increasingInts: Gen[Stream[Int]] = go(0)
increasingInts(Gen.Parameters.default, Seed.random()).get foreach println
所以我被卡住了。 有任何想法嗎?
您想要的可以通過以下方式實現:
val increasingInts = {
val increments = Gen.choose(1, 2)
val initialSeed = 0
for {
stream <- Gen.infiniteStream(increments)
} yield stream.scanLeft(initialSeed)(_ + _)
}
.scanLeft
類似於.foldLeft
但保留中間值,從而為您提供另一個Stream
。
我在這里寫了有關scanLeft
: https : scanLeft
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.