Thanks. So I tried<div><br></div><div><div><div>upTo n p =</div><div>    liftM2 (:) p (upTo (n-1) p)</div><div><br></div><div>which doesn&#39;t quite work because the recursion does not have a base case. The following gets me closer:</div>

<div><br></div><div><div>upTo n p =</div><div>    if n &lt;= 0 then</div><div>        return []</div><div>    else</div><div>        liftM2 (:) p (upTo (n-1) p)</div><div><br></div></div><div>&gt; parse (upTo 3 digit) &quot;&quot; &quot;123ab&quot;</div>

<div>Right &quot;123&quot;</div><div><br></div><div>However:</div><div><br></div><div><div>&gt; parse (upTo 4 digit) &quot;&quot; &quot;123ab&quot;</div><div>Left (line 1, column 4):</div><div>unexpected &quot;a&quot;</div>

<div>expecting digit</div><div><br></div></div><div>The semantics of (upTo n p) should be to parse at most n tokens, but if less than n tokens are available that should still be a successful parse. And the next token should be the first one upTo failed on.</div>

<div><br></div><div>I attempted to use the &quot;try&quot; parser in various locations but that doesn&#39;t seem to help, or maybe I&#39;m using it incorrectly.</div><div><br></div></div><div><br></div></div><div><div class="gmail_quote">

On Sat, Oct 17, 2009 at 5:15 AM, Christian Maeder <span dir="ltr">&lt;<a href="mailto:Christian.Maeder@dfki.de">Christian.Maeder@dfki.de</a>&gt;</span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">

Ashish Agarwal schrieb:<br>
<div><div></div><div class="h5">&gt; Hi. I&#39;m just learning Parsec and Haskell. It is a great library, and I<br>
&gt; see how &quot;many&quot; lets you parse 0 or more items, &quot;many1&quot; parses 1 or more<br>
&gt; items, and &quot;count&quot; parses exactly n items. However, there is no<br>
&gt; combinator that parses between m and n items. What would be the best<br>
&gt; implementation for this?<br>
<br>
</div></div>I would write an &quot;upTo&quot; parser with the same type as &quot;count&quot; that parses<br>
not exactly but at most n items. Your desired parser is than the<br>
concatenated results of &quot;count m p&quot; and &quot;upTo (n - m) p&quot; (achieved by<br>
&quot;liftM2 (++)&quot;).<br>
<br>
For &quot;upTo&quot; a recursive definition seems best (other may come up with<br>
tricky combinator application.) &quot;upTo 0 p&quot; (or something less than 0)<br>
returns &quot;[]&quot; and &quot;upTo n p&quot; is an &quot;option [] ...&quot; parser of one &quot;p&quot;<br>
result followed by the &quot;upTo (n - 1) p&quot; result:<br>
<br>
&quot;option [] (liftM2 (:) p (upTo (n - 1) p))&quot;<br>
<br>
HTH Christian<br>
<br>
Another possibility is to use &quot;many&quot; and check if the resulting list has<br>
the desired length (if not fail), but that may consume too many tokens<br>
that subsequent parsers are supposed to consume.<br>
</blockquote></div><br></div>