<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Clojure Q&amp;A - Recent questions tagged generator</title>
<link>https://ask.clojure.org/index.php/tag/generator</link>
<description></description>
<item>
<title>`(s/gen ratio?)` throws exceptions</title>
<link>https://ask.clojure.org/index.php/13877/s-gen-ratio-throws-exceptions</link>
<description>&lt;p&gt;&lt;code&gt;(s/gen ratio?)&lt;/code&gt; is &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/clojure/spec.alpha/blob/c630a0b8f1f47275e1a476dcdf77507316bad5bc/src/main/clojure/clojure/spec/gen/alpha.clj#L187&quot;&gt;implemented&lt;/a&gt; as &lt;code&gt;(gen/such-that ratio? gen/ratio)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The problem is that about 10% of the time &lt;code&gt;gen/ratio&lt;/code&gt; returns a whole number, which fails the &lt;code&gt;ratio?&lt;/code&gt; predicate. If that happens 10 times in a row, &lt;code&gt;gen/such-that&lt;/code&gt; throws an exception.&lt;/p&gt;
&lt;p&gt;With a large enough sample size, &lt;code&gt;(s/gen ratio?)&lt;/code&gt; reliably fails:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(dorun (gen/sample (s/gen ratio?) 10000000))

Execution error (ExceptionInfo) at clojure.test.check.generators/fn (generators.cljc:435).
Couldn't satisfy such-that predicate after 10 tries.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A quick fix is to increase the &lt;code&gt;max-tries&lt;/code&gt; param for &lt;code&gt;such-that&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(dorun (gen/sample (gen/such-that ratio? gen/ratio 100) 10000000))

=&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I do however also find it odd that &lt;code&gt;(s/gen ratio?)&lt;/code&gt; always generates &lt;code&gt;Ratio&lt;/code&gt;s, but &lt;code&gt;gen/ratio&lt;/code&gt; generates a mixture of ratios and integers. So perhaps a better fix would be to update &lt;code&gt;gen/ratio&lt;/code&gt; to not generate integers?&lt;/p&gt;
</description>
<category>Spec</category>
<guid isPermaLink="true">https://ask.clojure.org/index.php/13877/s-gen-ratio-throws-exceptions</guid>
<pubDate>Wed, 08 May 2024 07:44:49 +0000</pubDate>
</item>
</channel>
</rss>