<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/the-new-pqr-parser-and-rs-else-problem/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://radfordneal.wordpress.com/2018/11/27/the-new-pqr-parser-and-rs-else-problem/"> R Programming – Radford Neal's blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<table>
<tbody>
<tr>
<td valign="top"><a rel="nofollow" href="https://radfordneal.files.wordpress.com/2013/12/logolg.png" target="_blank"><img src="https://radfordneal.files.wordpress.com/2013/12/logolg.png?w=256&h=200&fit=256%2C200&resize=256%2C200" alt="" width="256" align="top" data-recalc-dims="1" height="200"></a></td>
<td valign="top">The <a rel="nofollow" href="https://radfordneal.wordpress.com/2018/11/25/new-version-of-pqr-with-major-speed-improvements/" target="_blank">latest version of pqR</a> (mostly) solves R’s “else” problem, by modifying the new parser previously introduced in pqR.  I’ll explain the “else” problem and solution here, and also present other advantages of pqR’s parser over the R Core parser, including a big speed advantage in one context.</td>
</tr>
</tbody>
</table>
<p><span></span></p>
<h3>The “else” problem in R</h3>
<p>Probably most new R programmers have encountered the following problem. They put some statements like the following in a file, say “sltp.r”:</p>
<pre>sltp &lt;- iris$Sepal.Width &lt; iris$Petal.Width
if (any(sltp)) print(iris[sltp,])
else cat(&quot;Sepal width is never less than petal width\n&quot;)
</pre>
<p>They then try to execute this script with “source”, and get this result:</p>
<pre>> source(&quot;sltp.r&quot;)
Error in source(&quot;sltp.r&quot;) : sltp.r:3:1: unexpected 'else'
2: if (any(sltp)) print(iris[sltp,])
3: else
   ^
</pre>
<p>Trying to run the script with Rscript has the same problem:</p>
<pre>$ Rscript sltp.r
Error: unexpected 'else' in &quot;else&quot;
Execution halted
$
</pre>
<p>This is puzzling, since the same code works fine inside a function whose body is in curly brackets:</p>
<pre>> f &lt;- function () {
+   sltp &lt;- iris$Sepal.Width &lt; iris$Petal.Width
+   if (any(sltp)) print(iris[sltp,])
+   else cat(&quot;Sepal width is never less than petal width\n&quot;)
+ }
> f()
Sepal width is never less than petal width
</pre>
<p>Now, there’s a reason for this. When entering expressions interactively, R is supposed to print the value of the expression as soon<br>
as it’s been entered. But how can it know whether an “if” statement at the end of a line with no else clause is complete (there is no “else” part), or whether instead the user intends to enter an “else” clause on the next line?</p>
<p>One can imagine kludges to get around this in many cases, but the following example shows that there’s not going to be a general<br>
solution:</p>
<pre>> a &lt;- 1:9; for (i in 1:9) if (a[i]>5) print(a[i])
[1] 6
[1] 7
[1] 8
[1] 9
</pre>
<p>After entering the first line above, the user expects to see the output below. They don’t expect to be asked to enter more text in case that text might be an “else” clause.</p>
<p>Situations like the one above are fairly rare, however. One <i>could</i> decide that the user has to enter a blank line after such an “if” statement to confirm that there is no “else” clause — that’s what Python does. But let’s suppose we don’t want to do that. Then we have to evaluate the expression containing the “if” immediately, and consider a following “else” to be an error.</p>
<p>But for <i>non-interactive</i> input, there’s no need to disallow a top-level “else” at the start of a line. Yet it has always been an error in R Core implementations. It no longer is an error in pqR — in input from a file read by Rscript, by “source”, or by “parse”, as well when “parse” is applied to a vector of character strings, it is now OK for an “else” be appear at the start of a line. This avoids annoyances when writing scripts, and also problems when pasting code into a script that was copied from inside a function with curly brackets (where “else” at the start of a line has always been legal).</p>
<p>I don’t know whether this problem has persisted so long in R Core implementations just due to inertia, or because it’s hard to modify the R Core parser to do this. It was fairly easy to modify the pqR parser, though there were some picky details involved.</p>
<h3>New operators</h3>
<p>The new pqR parser has also facilitated the introduction of new operators in pqR. The <tt>..</tt> operator for reliable sequence generation was introduced <a rel="nofollow" href="https://radfordneal.wordpress.com/2016/06/25/fixing-rs-design-flaws-in-a-new-version-of-pqr/" target="_blank">previously</a>. The latest release introduces <tt>!</tt> and <tt>!!</tt> as operator forms of “paste0” and “paste”. It might be hard to modify the R Core parser to include these operators, because their correct parsing requires use of context — “<tt>..</tt>” is allowed as part of an identifier (but only at the start or end in pqR), and  “<tt>!!</tt>” can be two successive unary-not operators, but not in a context where the new <tt>!!</tt> operator can legally appear.</p>
<h3>Top-down recursive descent parsing</h3>
<p>This leads into the biggest difference between the new pqR parser and the old R Core parser.</p>
<p>The R Core parser is a bottom-up parser automatically generated from a grammar using the Bison/Yacc parser generator. Automatically generated? Sounds wonderful! But one of the inside secrets of computer science is that, despite decades of development, automatic parser generators are not actually very useful. As an illustration of this, gcc previously used such a parser, but abandoned it.</p>
<p>The generally-preferred method is to manually write a top-down “recursive-descent” parser. In theory, this shouldn’t be. Top-down parsers with k-symbol lookahead can handle grammars in the class LL(k); bottom-up parsers with k-symbol lookahead can handle grammars in the class LR(k), which is larger than LL(k). But in practice, most programming languages are in the LL(k) class if one assumes low-level tokenization has been handled, and dealing with funny contextual issues like the pqR <tt>..</tt> and <tt>!!</tt> operators is easier in a top-down parser. Furthermore, the advantage of just writing a grammar and having code for the parser generated automatically is largely illusory, since the code for recursive-descent parsers reads almost like a grammar, with one recursive function for each non-terminal symbol. The code gets more cluttered when one puts in the semantics, but this aspect is also easier in a recursive-descent parser than when using a parser generator.</p>
<h3>Parsing speed</h3>
<p>The new pqR parser is faster than the R Core parser, but typically only moderately so. One exception, however, is when parsing is done for Rscript, and an expression (e.g., a function definition) extends over many lines — R Core implementations take time growing as the <i>square</i> of the number of lines, whereas pqR takes linear time (as one would expect). </p>
<p>This gross inefficiency is due not just to the R Core parser itself but also to how it interfaces to R’s “read-eval-print loop” (the “REPL”). The R Core implementation used in Rscript first tries parsing the first line of input, and checks whether the parser says it has a complete expression. If not, it tries parsing the first two lines of input. If that doesn’t give a complete expression, it tries parsing the first three lines of input. And so forth.</p>
<p>Here’s an illustration of the resulting inefficiency. File x2.r contains the following:</p>
<pre>f &lt;- function (a) {
  a &lt;- a+1; a &lt;- a+1; a &lt;- a+1; a &lt;- a+1
  a &lt;- a+1; a &lt;- a+1; a &lt;- a+1; a &lt;- a+1
}
print(f(0))
</pre>
<p>Files x300.r and x600.r contain the same thing except that there are 300 and 600 repetitions of the line in the function definition rather than two repetitions.</p>
<p>The time for running these scripts with R-3.5.1’s version of Rscript can be seen here:</p>
<pre>$ time R-3.5.1-gcc8/bin/Rscript x2.r
[1] 8

real    0m0.109s
user    0m0.096s
sys     0m0.014s
$ time R-3.5.1-gcc8/bin/Rscript x300.r
[1] 1200

real    0m0.866s
user    0m0.839s
sys     0m0.029s
$ time R-3.5.1-gcc8/bin/Rscript x600.r
[1] 2400

real    0m2.554s
user    0m2.523s
sys     0m0.032s
</pre>
<p>And for comparison, here are the times with pqR-2018-11-18’s version of Rscript:</p>
<pre>$ time pqR-2018-11-18-gcc8/bin/Rscript x2.r
[1] 8

real    0m0.070s
user    0m0.052s
sys     0m0.019s
$ time pqR-2018-11-18-gcc8/bin/Rscript x300.r
[1] 1200

real    0m0.072s
user    0m0.062s
sys     0m0.012s
$ time pqR-2018-11-18-gcc8/bin/Rscript x600.r
[1] 2400

real    0m0.069s
user    0m0.058s
sys     0m0.012s

</pre>
<p>One can see that pqR is faster even for x2.r, but more importantly, with pqR the time for x300.r and x600.r is negligibly different, as one would expect since even 2400 additions should take negligible time. The huge increase in time with R-3.5.1 is due to the quadratic growth in the time to parse the function definition.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://radfordneal.wordpress.com/2018/11/27/the-new-pqr-parser-and-rs-else-problem/"> R Programming – Radford Neal's blog</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/HZGuqW1e_qE" height="1"></a></div>