fscheck生成的字符串的大小在min和amp;之间最大限度 [英] fscheck generating string with size between min & max

查看:68
本文介绍了fscheck生成的字符串的大小在min和amp;之间最大限度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写一个FsCheck生成器,该生成器生成具有给定时间间隔的长度的字符串.

I try to write a FsCheck generator that generates strings with length in a given interval.

我的尝试如下:

let genString minLength maxLength = 
    let isValidLength (s : string) = 
        s.Length >= minLength && s.Length <= maxLength

    Arb.generate
    |> Gen.suchThat isValidLength
    |> Arb.fromGen

...我得到了错误:

...and I get the error:

"System.Exception : No instances of class FsCheck.Arbitrary`1[a] for type System.String with arguments set []"

我在做什么错了?

谢谢!

更新1:

我设法这样编写生成器:

I managed to write the generator like this:

let genStrings minLength maxLength = 
    gen {
        let! length = Gen.choose (minLength, maxLength)
        let! chars = Gen.arrayOfLength length Arb.generate<char>
        return new String(chars)
    }

有更好的方法吗?

更新2:我想将其添加为一个单独的问题,但与我原来的问题几乎相同.

UPDATE 2: I wanted to add this as a separate question but it's pretty much the same issue as my original one.

所以我将上面的代码重构为以下结构,以便重用序列生成器:

So I refactored the above code to the following structure in order to reuse the sequence generator:

let seqOfLength lengthInterval generator =
    gen {
        let! length = Gen.choose lengthInterval
        let! items = Gen.arrayOfLength length generator
        return items |> Seq.ofArray
    }

let sizedString lengthInterval =
    seqOfLength lengthInterval Arb.generate<char>
    |> Gen.map Strings.ofCharSeq

现在我遇到运行时错误:

Now I'm getting the runtime error:

System.Exception : No instances of class FsCheck.Arbitrary`1[a] for type System.Char with arguments set []

...这使我回到原来的问题:为什么它找不到System.Char的任意实例?我认为基本类型的任意值默认情况下已注册.我在做什么错了?

...which brings me back to my original issue: Why do can't it find any instance of Arbitrary for System.Char? I thought the arbitrary for the basic types are registered by default. What am I doing wrong?

谢谢!

推荐答案

您的示例代码从FsCheck v2.14.3开始有效

Your sample code works as of FsCheck v2.14.3

let seqOfLength lengthInterval generator =
    gen {
        let! length = Gen.choose lengthInterval
        let! items = Gen.arrayOfLength length generator
        return items |> Seq.ofArray
    }
let stringOfLength lengthInterval =
    seqOfLength lengthInterval Arb.generate<char>
    |> Gen.map String.Concat

这篇关于fscheck生成的字符串的大小在min和amp;之间最大限度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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