<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog 4 &#187; Programming</title>
	<atom:link href="http://nickzarr.com/blog4/category/programming-2/feed/" rel="self" type="application/rss+xml" />
	<link>http://nickzarr.com/blog4</link>
	<description>Chosen by fair dice roll. Guaranteed random.</description>
	<lastBuildDate>Sun, 22 Apr 2012 18:29:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Setting up csi in Chicken</title>
		<link>http://nickzarr.com/blog4/2012/04/setting-up-csi-in-chicken/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setting-up-csi-in-chicken</link>
		<comments>http://nickzarr.com/blog4/2012/04/setting-up-csi-in-chicken/#comments</comments>
		<pubDate>Sun, 22 Apr 2012 18:23:02 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Chicken]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1786</guid>
		<description><![CDATA[The default Chicken Scheme command line interpreter does not have readline support enabled by default. Here&#8217;s how you set it up: First install the readline-dev packages for your OS. For Ubuntu I installed the libreadline6-dev package using apt-get, but this may vary a bit depending on which OS you&#8217;re running. Then you need to get [...]]]></description>
			<content:encoded><![CDATA[<p>The default Chicken Scheme command line interpreter does not have readline support enabled by default.  Here&#8217;s how you set it up:</p>
<p>First install the readline-dev packages for your OS.  For Ubuntu I installed the libreadline6-dev package using apt-get, but this may vary a bit depending on which OS you&#8217;re running.</p>
<pre class="brush: plain; title: ; notranslate">
sudo apt-get install libreadline6-dev
</pre>
<p>Then you need to get the readline egg from the egg repository and install it.  Fortunately chicken-install makes this a snap!</p>
<pre class="brush: plain; title: ; notranslate">
chicken-install readline
</pre>
<p>Then create a new file called .csirc in your home directory and also a .csi.history file:</p>
<pre class="brush: plain; title: ; notranslate">
touch ~/.csirc
touch ~/.csi.history
</pre>
<p>And put the following in .csirc:</p>
<pre class="brush: plain; title: ; notranslate">
(use readline irregex)
(current-input-port (make-gnu-readline-port))
(gnu-history-install-file-manager
  (string-append (or (get-environment-variable &quot;HOME&quot;) &quot;.&quot;) &quot;/.csi.history&quot;))
</pre>
<p>That&#8217;s it!  Readline and history should now work in Chicken!</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2012/04/setting-up-csi-in-chicken/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Issue tracking and wikis</title>
		<link>http://nickzarr.com/blog4/2012/01/issue-tracking-and-wikis/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=issue-tracking-and-wikis</link>
		<comments>http://nickzarr.com/blog4/2012/01/issue-tracking-and-wikis/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 17:00:40 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1772</guid>
		<description><![CDATA[Recently I made a stupid, sleep-deprived error. I won&#8217;t go into too much detail, as it&#8217;s unimportant, however I made some sweeping changes to a number of of my git repositories. Rather than properly merging the changes into my project&#8217;s respective Github repositories I decided to simply delete the Github repos, create new ones and [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I made a stupid, sleep-deprived error.  I won&#8217;t go into too much detail, as it&#8217;s unimportant, however I made some sweeping changes to a number of of my git repositories.  Rather than properly merging the changes into my project&#8217;s respective Github repositories I decided to simply delete the Github repos, create new ones and upload the changes from my local repo.</p>
<p>Had I been more careful, or paid more attention to the numerous warnings during this process, I would have made backups of my wiki and issue tracker data.  Unfortunately I did not and the next day when I went to make some updates to the wiki of one of my projects I was hit with the realization that the data was lost forever.</p>
<p>I&#8217;ve only just started using the Github wiki and issue trackers a few months ago, so the data loss was not catastrophic.  In total I probably lost about 30 hours worth of work, however it will likely take me twice that to recreate the data and there will be some things that will never be recovered.</p>
<p>Overall I was happy with my (limited) experience of using Github issues and wiki.  Being able to reference issues from commits and vice versa was a nice feature and the wiki served its purpose well enough.  Previously I kept my issues/to-do list in the source code itself, which worked well enough, but didn&#8217;t provide as much flexibility as a dedicated issue tracker.  Switching to Github&#8217;s issue tracker provided a centralized location for all my bugs and to-do items, as well as a history of completed tasks which had a positive influence on my workflow.  For documentation I used README files, and I still do, however a wiki provides a much larger canvas and leads to writing more through documentation.</p>
<p>Having had a taste of these features and the resulting increase productivity and quality of my projects, I do not want to return to the old way of doing things.  However my recent experience has enlightened me as to some of the downsides of using these tools.</p>
<h2>Issues and documentation are part of your project</h2>
<p>The overall insight this experience has given me is that issues and documentation are part of your project.  Every file in your project is stored in the same repository, why isn&#8217;t the issue tracker and wiki data stored in that same repo?</p>
<p>Granted my mistake was a stupid one, stemming from carelessly performing operations which cannot be undone.  However consider the case of moving your central repository from Github to another service or private host.  The move isn&#8217;t as simple as changing the origin and pushing to the new repo, instead you have to backup the issues/wiki and transfer that in a second step.  Sometimes transferring that data is difficult, especially if the tools provided by the new host are radically different.</p>
<p>Having all your issue/wiki data stored in the same repo as your source code means that there are (likely) multiple copies of that data on many different machines.  Changing hosts for the central repository is a simple matter of pushing to a new origin.  Developers can use their preferred tools to work with issues and documentation.  </p>
<p>I&#8217;ve done a cursory search for issue trackers/wikis which are designed to be included in the main git repository and have found <a href="https://github.com/jeffWelling/ticgit">ticgit</a> which takes care of issue tracking.  I haven&#8217;t had a chance yet to evaluate it, but plan on doing so in the near future.  I haven&#8217;t yet found a solution for a wiki.</p>
<p>Ideally I would like both an issue tracker and wiki with a similar interface (as much as that is possible).  If I&#8217;m unable to find a suitable solution I will likely take this up as my next project.  Here are some of the features that I&#8217;m looking for:</p>
<dl>
<dt>Version Control</dt>
<dd>Changes to issues or wiki should be tracked by version control.</dd>
<dt>Users</dt>
<dd>New issues or changes should be associated with a user (git name + email + key).</dd>
<dt>Editing</dt>
<dd>Editing should be allowed through a number of tools (web, command line, text editor/IDE) and should support markdown format.</dd>
<dt>Viewing</dt>
<dd>Viewing the tracker/wiki should be allowed through a number of tools (web, editor/IDE).</dd>
<dt>Alerts</dt>
<dd>A program can monitor the repo for changes and alert users via email when changes occur.</dd>
</dl>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2012/01/issue-tracking-and-wikis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping into Javascript &#8211; Good news and bad news</title>
		<link>http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-good-news-and-bad-news</link>
		<comments>http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 12:54:31 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[jamochatrade]]></category>
		<category><![CDATA[jumping into javascript]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1737</guid>
		<description><![CDATA[I have resumed development of the JamochaTrade project and there has been a lot of progress over the last week or so. The last article left off with a very rudimentary candlestick chart that got its data via cross-domain JSON. I am pleased to announce that a UI has been added, along with the ability [...]]]></description>
			<content:encoded><![CDATA[<p>I have resumed development of the JamochaTrade project and there has been a lot of progress over the last week or so.  The last article left off with a very rudimentary candlestick chart that got its data via cross-domain JSON.  I am pleased to announce that a UI has been added, along with the ability to buy and sell stocks, limit and stop orders, 5 different chart types (candlestick, bar, ohlc, hlc and line), a portfolio view, pending orders view, advancing time by week/month is animated as well as a host of other improvements.</p>
<p>Unfortunately the speed at which these features have been added has ended the step-by-step nature of this series.  I will continue to provide progress updates and hope to produce a number of articles based on architecture or challenges that arise during development.  Though there is not much discussion, you can still <a href="https://github.com/jacktrades/JamochaTrade/commits/master">follow along with the commit log</a> of the project.  Each commit is relatively small and, in most cases, addresses a single concern.  There is also some information provided in the <a href="https://github.com/jacktrades/JamochaTrade/issues">issue tracker</a>, which I have been making heavy use of and almost every commit has an associated issue.</p>
<p>The project is not yet ready for release, however there is a <a href="http://nickzarr.com/demos/jamochatrade/">preview version available</a>.  Criticisms, comments, bug reports and feature requests are more than welcome.  You can leave comments below or file a bug report or feature request on the <a href="https://github.com/jacktrades/JamochaTrade/issues">issue tracker</a>.</p>
<h3><a href="http://nickzarr.com/demos/jamochatrade/" title="JamochaTrade">Try the demo</a></h3>
<p>&nbsp;</p>
<p><strong>Features:</strong></p>
<ul>
<li>5 chart types (candlestick, bar, ohlc, hlc, line)</li>
<li>15, 30, 60 and 90 day charts</li>
<li>Change chart colors</li>
<li>Advance time by day, week or month (animated)</li>
<li>Buy/sell stocks</li>
<li>Portfolio view</li>
<li>Sell directly from portfolio view</li>
<li>Market, limit and stop orders</li>
<li>Pending order pane</li>
<li>Cancel pending orders</li>
<li>Change theme of site</li>
<li>Previously viewed stock data is cached for fast switching</li>
<li>Most features auto-hide when not necessary to reduce clutter</li>
<li>Account balance and total portfolio value show gains/losses</li>
</ul>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt01-e1321274006867.png" alt="Screenshot 1" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt02-e1321274476128.png" alt="Screenshot 2" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt03-e1321274459766.png" alt="Screenshot 3" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt04-e1321274438189.png" alt="Screenshot 4" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt05-e1321274136418.png" alt="Screenshot 5" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt06-e1321274036579.png" alt="Screenshot 6" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript wisdom from the jQuery source code</title>
		<link>http://nickzarr.com/blog4/2011/11/javascript-wisdom-from-the-jquery-source-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-wisdom-from-the-jquery-source-code</link>
		<comments>http://nickzarr.com/blog4/2011/11/javascript-wisdom-from-the-jquery-source-code/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 11:44:45 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1724</guid>
		<description><![CDATA[Here are a few things I learned from reading the jQuery source code. I&#8217;m documenting them here because they&#8217;re edge cases that are, in some cases, difficult to reproduce and debug. The jQuery source code is very clean and well commented and has many more gems than what is listed here. &#160; getElementById sometimes returns [...]]]></description>
			<content:encoded><![CDATA[<p>Here are a few things I learned from reading the <a href="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">jQuery source code</a>.  I&#8217;m documenting them here because they&#8217;re edge cases that are, in some cases, difficult to reproduce and debug.  The jQuery source code is very clean and well commented and has many more gems than what is listed here.</p>
<p>&nbsp;</p>
<h3>getElementById sometimes returns elements by name in some versions of IE and Opera.</h3>
<pre class="brush: jscript; title: ; notranslate">
                                // HANDLE: $(&quot;#id&quot;)
                                } else {
                                        elem = document.getElementById( match[2] );

                                        // Check parentNode to catch when Blackberry 4.6 returns
                                        // nodes that are no longer in the document #6963
                                        if ( elem &amp;&amp; elem.parentNode ) {
                                                // Handle the case where IE and Opera return items
                                                // by name instead of ID
                                                if ( elem.id !== match[2] ) {
                                                        return rootjQuery.find( selector );
                                                }

                                                // Otherwise, we inject the element directly into the jQuery object
                                                this.length = 1;
                                                this[0] = elem;
                                        }

                                        this.context = document;
                                        this.selector = selector;
                                        return this;
                                }
</pre>
<p>Even something as simple as getElementById can have edge cases you have to take into account.  In IE 6 and 7 for Windows and some versions of Opera, dom elements can be returned by name instead of id.  In addition, as seen in the comments of the code above, Blackberry 4.6 can return nodes that are not even in the document.</p>
<p>See references <a href="http://remysharp.com/2007/02/10/ie-7-breaks-getelementbyid/">here</a> and <a href="http://www.456bereastreet.com/archive/200802/beware_of_id_and_name_attribute_mixups_when_using_getelementbyid_in_internet_explorer/">here</a>.</p>
<p>&nbsp;</p>
<h3>A false positive on the domready event can cause rapid page refreshing.</h3>
<pre class="brush: jscript; title: ; notranslate">
        // Handle when the DOM is ready
        ready: function( wait ) {
                // Either a released hold or an DOMready/load event and not yet ready
                if ( (wait === true &amp;&amp; !--jQuery.readyWait) || (wait !== true &amp;&amp; !jQuery.isReady) ) {
                        // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                        if ( !document.body ) {
                                return setTimeout( jQuery.ready, 1 );
                        }
</pre>
<p>The domready event, which is present in some form or another in many browsers can fire before the dom is actually loaded.  This can cause continuous page reloads and other errors which are hard to reproduce and debug.  The solution to this is to check that the document.body is not null before accepting the domready event.</p>
<p>Of course you can always fall back to the window.onload event, however this will force you to wait until the entire content of the page (including possibly large images) has loaded.</p>
<p>See references <a href="http://bugs.jquery.com/ticket/5443">here</a> and <a href="http://www.sigsiu.net/forum/community-board-for-troubleshooting-problems/internet-explorer-dom-readiness-problem-and-solution-explained/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/11/javascript-wisdom-from-the-jquery-source-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; lambda</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-lambda/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-lambda</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-lambda/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 08:55:03 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1690</guid>
		<description><![CDATA[GOTO Part 9 &#124; Environments We are finally going to implement lambda and procedures. To begin implementing procedures we have to define a procedure type, just like we did with primitives. A procedure has 3 basic parts. A list of parameters, a body and an environment. So we&#8217;ll set up a new procedure type with [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-environments/" title="Scheme in Python – Environments">GOTO Part 9 | Environments</a></p>
<p>We are finally going to implement lambda and procedures.</p>
<p>To begin implementing procedures we have to define a <strong>procedure</strong> type, just like we did with primitives.  A procedure has 3 basic parts.  A list of <strong>parameters</strong>, a <strong>body</strong> and an <strong>environment</strong>.  So we&#8217;ll set up a new procedure type with these fields and call it <strong>Procedure</strong>.</p>
<p><strong>scheme_types.py</strong></p>
<pre class="brush: python; highlight: [29,30,31,32,33]; title: ; wrap-lines: false; notranslate">
class Symbol(str):
  &quot;&quot;&quot;A symbol is an immutable string, but must be its own type.&quot;&quot;&quot;
  pass

class The_Empty_List():
  &quot;&quot;&quot;The empty list is used as a list terminator and should be a singleton&quot;&quot;&quot;
  def __repr__(self):
    return &quot;()&quot;

the_empty_list = The_Empty_List()

class Pair(object):
  &quot;&quot;&quot;A pair is a classic Lisp cons cell used to implement lists&quot;&quot;&quot;
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr
  def __iter__(self):
    x = self
    while not isinstance(x, The_Empty_List):
      yield x.car
      x = x.cdr
  def __repr__(self):
    return &quot;(&quot; + ' '.join([str(i) for i in list(self)]) + &quot;)&quot;

class Primitive(object):
  def __init__(self, fn):
    self.fn = fn

class Procedure(object):
  def __init__(self, parameters, body, environment):
    self.parameters = parameters
    self.body = body
    self.environment = environment
</pre>
<p>Like primitives, procedures are handled by the <strong>scheme_apply</strong> procedure.  We&#8217;ll temporarily add a placeholder in scheme_apply for procedures.  In addition we need new syntax to create a procedure.  The syntax for procedures in Scheme is (lambda (parameters) body).  Most Schemes allow the syntax (define (name params &#8230;) body &#8230;) but this is really just shorthand for (define name (lambda (params &#8230;) body &#8230;)).  For now we won&#8217;t overload the define keyword, choosing instead to define functions the more verbose way.</p>
<p>It is important to take note of this before moving on.  In many programming languages defining a function is a single step.  However logically, there are 2 different operations that take place.  First a function object is created, then that function object is bound to a symbol.  By requiring the (define name (lambda &#8230;)) syntax we are making these two steps explicit.</p>
<p><strong>scheme_eval.py</strong></p>
<pre class="brush: python; highlight: [1,62,63]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair, Primitive, the_empty_list, Procedure
from buffered_input import Buff
from scheme_read import scheme_read

##############################################################################
## Environments
##############################################################################

def current_environment(env):
  &quot;&quot;&quot;Return the frame of the current environment&quot;&quot;&quot;
  return env.car

def enclosing_environment(env):
  &quot;&quot;&quot;Return the environment stack with the first frame removed&quot;&quot;&quot;
  return env.cdr

def extend_environment(bindings, base_environment):
  &quot;&quot;&quot;Push a new frame onto the given base_environment&quot;&quot;&quot;
  return Pair(bindings, base_environment)

global_environment = extend_environment({}, the_empty_list)
special_forms = {}

def set_symbol(symbol, val, env):
  &quot;&quot;&quot;Set the binding (symbol, val) in the current frame of env&quot;&quot;&quot;
  current_environment(env)[symbol] = val

def lookup_symbol_value(symbol, environment):
  &quot;&quot;&quot;Return the value of symbol or Unbound Symbol error&quot;&quot;&quot;
  env = environment
  while env != the_empty_list:
    if symbol in current_environment(env):
      return current_environment(env)[symbol]
    else:
      env = enclosing_environment(env)
  return &quot;Error: Unbound symbol: &quot; + symbol

##############################################################################
## Eval and Apply
##############################################################################

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr, env):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr, env)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr, env)
    else:
      return scheme_apply(scheme_eval(expr.car, env), [scheme_eval(a, env) for a in expr.cdr])
  else:
    return &quot;scheme_eval: not implemented&quot;

def scheme_apply(proc, args):
  if type(proc) is Primitive:
    return apply(proc.fn, args)
  elif type(proc) is Procedure:
    return &quot;Attempted to apply a procedure&quot;
  else:
    return &quot;Error: Undefined procedure&quot;

##############################################################################
## Builtin Syntax
##############################################################################

def special_form_handler(expr, env):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

def load(expr):
  &quot;&quot;&quot;Given a filename, open it and eval each expression in the global_environment&quot;&quot;&quot;
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_eval(scheme_read(b), global_environment)
    b.remove_whitespace()
  f.close()

special_forms['scheme-syntax'] = special_form_handler
special_forms['load'] = load
</pre>
<p><strong>syntax.scm</strong></p>
<pre class="brush: plain; highlight: [19,20,21,22]; title: ; notranslate">
(scheme-syntax define-primitive &quot;
def f(expr, env):
  set_symbol(expr.car, Primitive(eval(expr.cdr.car)), env)
&quot;)

(scheme-syntax define &quot;
def f(expr, env):
  set_symbol(expr.car, scheme_eval(expr.cdr.car, env), env)
&quot;)

(scheme-syntax if &quot;
def f(expr, env):
  if scheme_eval(expr.car, env):
    return scheme_eval(expr.cdr.car, env)
  else:
    return scheme_eval(expr.cdr.cdr.car, env)
&quot;)

(scheme-syntax lambda &quot;
def f(expr, env):
  return Procedure(expr.car, expr.cdr.car, env)
&quot;)
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
(define a (lambda (x) x))
a
;===&gt; &lt;scheme_types.Procedure object at 0xb733b10c&gt;
(a 42)
;===&gt; Attempted to apply a procedure
</pre>
<p>Now that we have a basic outline for what our procedures will look like, we can focus on making them work!</p>
<p>To apply a procedure we have to evaluate the <strong>body</strong>.  In the example above the body of the procedure is just <strong>x</strong>.  However we can&#8217;t just evaluate <strong>x</strong> because <strong>x</strong> is not bound to anything yet.  </p>
<p>First we need to create a new environment and bind the parameters to the arguments supplied in the procedure call.  In this case we have to bind <strong>x</strong> to the value <strong>42</strong>.  Then we just evaluate each expression in the body within the new environment and return the result of evaluating the last expression.</p>
<pre class="brush: python; highlight: [63,64]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair, Primitive, the_empty_list, Procedure
from buffered_input import Buff
from scheme_read import scheme_read

##############################################################################
## Environments
##############################################################################

def current_environment(env):
  &quot;&quot;&quot;Return the frame of the current environment&quot;&quot;&quot;
  return env.car

def enclosing_environment(env):
  &quot;&quot;&quot;Return the environment stack with the first frame removed&quot;&quot;&quot;
  return env.cdr

def extend_environment(bindings, base_environment):
  &quot;&quot;&quot;Push a new frame onto the given base_environment&quot;&quot;&quot;
  return Pair(bindings, base_environment)

global_environment = extend_environment({}, the_empty_list)
special_forms = {}

def set_symbol(symbol, val, env):
  &quot;&quot;&quot;Set the binding (symbol, val) in the current frame of env&quot;&quot;&quot;
  current_environment(env)[symbol] = val

def lookup_symbol_value(symbol, environment):
  &quot;&quot;&quot;Return the value of symbol or Unbound Symbol error&quot;&quot;&quot;
  env = environment
  while env != the_empty_list:
    if symbol in current_environment(env):
      return current_environment(env)[symbol]
    else:
      env = enclosing_environment(env)
  return &quot;Error: Unbound symbol: &quot; + symbol

##############################################################################
## Eval and Apply
##############################################################################

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr, env):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr, env)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr, env)
    else:
      return scheme_apply(scheme_eval(expr.car, env), [scheme_eval(a, env) for a in expr.cdr])
  else:
    return &quot;scheme_eval: not implemented&quot;

def scheme_apply(proc, args):
  if type(proc) is Primitive:
    return apply(proc.fn, args)
  elif type(proc) is Procedure:
    new_env = extend_environment(dict(zip(proc.parameters, args)), proc.environment)
    return [scheme_eval(e,new_env) for e in proc.body][-1]
  else:
    return &quot;Error: Undefined procedure&quot;

##############################################################################
## Builtin Syntax
##############################################################################

def special_form_handler(expr, env):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

def load(expr):
  &quot;&quot;&quot;Given a filename, open it and eval each expression in the global_environment&quot;&quot;&quot;
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_eval(scheme_read(b), global_environment)
    b.remove_whitespace()
  f.close()

special_forms['scheme-syntax'] = special_form_handler
special_forms['load'] = load
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
(define test (pred conseq alt)
  (if pred conseq alt))
(test 1 2 3)
;===&gt; 2
(define-primitive + &quot;lambda x,y: x+y&quot;)
(define-primitive &lt; &quot;lambda x,y: x&lt;y&quot;)
(define a (lambda (x y) (if (&lt; x y) (a (+ x 1) y) x)))
(a 1 3)
;===&gt; 3
</pre>
<p>With that, we have implemented lambda in Scheme!  However there are some glaring omissions from our implementation.  For example ((lambda () 42)) will result in an iteration over non-sequence error from trying to iterate over the_empty_list.  Also, tail-call elimination is not implemented as required by the Scheme standard.  </p>
<p>Also note that there is very little error-checking going on here.  For instance calling a procedure with the wrong number of arguments results in the whole interpreter crashing.  This would not be good in a production language.  However including error checking in this code would probably triple its size at least.  The point of this exercise is to learn the concepts, not write a bullet-proof language.</p>
<p>I will likely come back to this at some point in the future and address some of these concerns.  The rest is left for you to experiment with.  You can get more information on how and what to implement from <a href="http://www.schemers.org/Documents/Standards/R5RS/">R5RS</a>.</p>
<p>I will be <a href="http://nickzarr.com/blog4/tag/jumping-into-javascript/">Jumping back into Javascript</a> for the next few posts at least, so this series will not be updated for a while (with the exception of bug fixes).  When I do get back to language design and implementation, I will probably pick back up with the Scheme version of this interpreter, or possibly with a new project on compiling.</p>
<p>If you have any questions about how to proceed from here, or just want to show off your own version, please leave a comment.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.10">Checkout this version on GitHub (v0.10)</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-lambda/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Environments</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-environments/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-environments</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-environments/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 23:54:46 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1669</guid>
		<description><![CDATA[GOTO Part 8 &#124; Primitive procedures and apply We&#8217;ve been dealing with an environment ever since part 5 in this series when we implemented define, except we&#8217;ve been calling it a frame. Until now our frame has served us well, it has provided a simple environment where we could set and retrieve the value of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-primitive-procedures-and-apply/" title="Scheme in Python – Primitive procedures and apply">GOTO Part 8 | Primitive procedures and apply</a></p>
<p>We&#8217;ve been dealing with an <strong>environment</strong> ever since <a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-assignment-and-define/" title="Scheme in Python – Assignment and define">part 5</a> in this series when we implemented define, except we&#8217;ve been calling it a <strong>frame</strong>.  Until now our frame has served us well, it has provided a simple environment where we could set and retrieve the value of symbols.  However implementing procedures requires us to add a few features to our frame.  Consider the code below.</p>
<pre class="brush: plain; title: ; notranslate">
(define x 5)
(define (func x)
  x)
(func 100)
;===&gt; 100
</pre>
<p>With our frame this wouldn&#8217;t work as expected.  Because we have already defined x in the global environment, there will be one of two problems with the x in <strong>func</strong>.  Our function could use the global value of x (5) instead of the supplied value (100) or when the supplied value (100) is mapped onto the function body it will overwrite the value of the global value of x (5) with the supplied value (100).</p>
<p>Currently we do not make any distinction between variables in a function body and in the global environment.  To properly implement procedures we will have to figure out a way to do that.  Consider the next bit of code.</p>
<pre class="brush: plain; title: ; notranslate">
(define x 5)
(define (func y)
  (+ x y))
(func 10)
;===&gt; 15
</pre>
<p>Even though we need to make a distinction between environments they also need to be connected.  In the example above we use the global variable x in func without ever declaring it.  This is accomplished by a method called chaining environments.  </p>
<pre class="brush: plain; title: ; notranslate">
(define x 1)
(define (outer-func y)
  (define (inner-func z)
    (+ x y z)
  (inner-func 3))
(outer-func 2)
;===&gt; 6
</pre>
<p>The environments produced by the above code are best described by the diagram below.</p>
<p><img src="https://docs.google.com/drawings/pub?id=1ODj7-OmaC-KHAITY2fvGrQIFqCn9sxMbit2iNjWrj2E&amp;w=580&amp;h=568"></p>
<p>So when x appears in inner-func we have to check inner-func&#8217;s environment for x, then outer-func&#8217;s environment for x and finally the global environment for x before we raise an undefined symbol error.</p>
<p>You may have noticed that the diagram above looks a lot like a <a href="http://nickzarr.com/blog4/2011/02/20/what-in-the-hell-are-linked-lists/">linked list</a>.  We can take our frame and combine it with linked lists to form an environment.  It is more informative (and closer to the actual design) to view environments from the point of view of eval.  This diagram is a view of the environment structure when the code (+ x y z) is evaluated.</p>
<p><img src="https://docs.google.com/drawings/pub?id=1RkD5O0pGCY08TLdkPzRIIp0fsxkPrB7z2vXqY37ZyZs&amp;w=580&amp;h=568"></p>
<p>I used the names <strong>current-environment</strong> to refer to the inner-func environment and <strong>enclosing-environment</strong> to refer to the outer-func environment.  We will use these same names in our source code.  Note that the <strong>global-environment</strong> is just the <strong>enclosing-environment</strong> of outer-func, the only thing special about it is that its <strong>enclosing-environment</strong> is the empty list.</p>
<p>In addition we need to replace our global frame with <strong>global_environment</strong>, which we&#8217;ll do by providing a procedure <strong>extend_environment</strong>, and change <strong>lookup_symbol_value</strong> to check enclosing-environments if the symbol is not found.</p>
<p><strong>scheme_eval.py</strong></p>
<pre class="brush: python; highlight: [1,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,42]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair, Primitive, the_empty_list
from buffered_input import Buff
from scheme_read import scheme_read

def current_environment(env):
  &quot;&quot;&quot;Return the frame of the current environment&quot;&quot;&quot;
  return env.car

def enclosing_environment(env):
  &quot;&quot;&quot;Return the environment stack with the first frame removed&quot;&quot;&quot;
  return env.cdr

def extend_environment(bindings, base_environment):
  &quot;&quot;&quot;Push a new frame onto the given base_environment&quot;&quot;&quot;
  return Pair(bindings, base_environment)

global_environment = extend_environment({}, the_empty_list)
special_forms = {}

def set_symbol(symbol, val, env):
  &quot;&quot;&quot;Set the binding (symbol, val) in the current frame of env&quot;&quot;&quot;
  current_environment(env)[symbol] = val

def lookup_symbol_value(symbol, environment):
  &quot;&quot;&quot;Return the value of symbol or Unbound Symbol error&quot;&quot;&quot;
  env = environment
  while env != the_empty_list:
    if symbol in current_environment(env):
      return current_environment(env)[symbol]
    else:
      env = enclosing_environment(env)
  return &quot;Error: Unbound symbol: &quot; + symbol

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr, global_environment)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr)
    else:
      return scheme_apply(scheme_eval(expr.car), [scheme_eval(a) for a in expr.cdr])
  else:
    return &quot;scheme_eval: not implemented&quot;

def scheme_apply(proc, args):
  if type(proc) is Primitive:
    return apply(proc.fn, args)
  else:
    return &quot;Error: Undefined procedure&quot;

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

def load(expr):
  &quot;&quot;&quot;Given a filename, open it and eval each expression in the global_environment&quot;&quot;&quot;
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_eval(scheme_read(b))
    b.remove_whitespace()
  f.close()

special_forms['scheme-syntax'] = special_form_handler
special_forms['load'] = load
</pre>
<p>We also need to make some changes to syntax.scm to use the new set_symbol function.</p>
<p><strong>syntax.scm</strong></p>
<pre class="brush: plain; highlight: [3,8]; title: ; notranslate">
(scheme-syntax define-primitive &quot;
def f(expr):
  set_symbol(expr.car, Primitive(eval(expr.cdr.car)), global_environment)
&quot;)

(scheme-syntax define &quot;
def f(expr):
  set_symbol(expr.car, scheme_eval(expr.cdr.car), global_environment)
&quot;)

(scheme-syntax if &quot;
def f(expr):
  if scheme_eval(expr.car):
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)
&quot;)
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
(define a 5)
;===&gt; #&lt;unspecified&gt;
a
;===&gt; 5
</pre>
<p>Before we go any further I&#8217;m going to add in some comments to the scheme_eval.py file, mainly to group code into logical sections.  I won&#8217;t provide a highlighted diff here, but you will notice the sections in the next bit of code.</p>
<p>To use the full potential of our new environments we are going to have to rewrite our program a little bit to pass them around correctly.  Since eval is the main method of dispatch for our interpreter we&#8217;ll supply the environment as an argument to eval, which means finding every use of scheme_eval and adding the env argument.  We&#8217;ll also have to pass an environment variable to procedures like set_symbol and lookup_symbol_value.  One final place we&#8217;ll need environments is in scheme-syntax, we&#8217;ll have to change the stored procedures there to use &#8220;def f(expr, env):&#8221; instead of just &#8220;def f(expr):&#8221;.</p>
<pre class="brush: python; highlight: [46,50,53,55,69,79]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair, Primitive, the_empty_list
from buffered_input import Buff
from scheme_read import scheme_read

##############################################################################
## Environments
##############################################################################

def current_environment(env):
  &quot;&quot;&quot;Return the frame of the current environment&quot;&quot;&quot;
  return env.car

def enclosing_environment(env):
  &quot;&quot;&quot;Return the environment stack with the first frame removed&quot;&quot;&quot;
  return env.cdr

def extend_environment(bindings, base_environment):
  &quot;&quot;&quot;Push a new frame onto the given base_environment&quot;&quot;&quot;
  return Pair(bindings, base_environment)

global_environment = extend_environment({}, the_empty_list)
special_forms = {}

def set_symbol(symbol, val, env):
  &quot;&quot;&quot;Set the binding (symbol, val) in the current frame of env&quot;&quot;&quot;
  current_environment(env)[symbol] = val

def lookup_symbol_value(symbol, environment):
  &quot;&quot;&quot;Return the value of symbol or Unbound Symbol error&quot;&quot;&quot;
  env = environment
  while env != the_empty_list:
    if symbol in current_environment(env):
      return current_environment(env)[symbol]
    else:
      env = enclosing_environment(env)
  return &quot;Error: Unbound symbol: &quot; + symbol

##############################################################################
## Eval and Apply
##############################################################################

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr, env):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr, env)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr, env)
    else:
      return scheme_apply(scheme_eval(expr.car, env), [scheme_eval(a, env) for a in expr.cdr])
  else:
    return &quot;scheme_eval: not implemented&quot;

def scheme_apply(proc, args):
  if type(proc) is Primitive:
    return apply(proc.fn, args)
  else:
    return &quot;Error: Undefined procedure&quot;

##############################################################################
## Builtin Syntax
##############################################################################

def special_form_handler(expr, env):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

def load(expr):
  &quot;&quot;&quot;Given a filename, open it and eval each expression in the global_environment&quot;&quot;&quot;
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_eval(scheme_read(b), global_environment)
    b.remove_whitespace()
  f.close()

special_forms['scheme-syntax'] = special_form_handler
special_forms['load'] = load
</pre>
<p><strong>repl.py</strong></p>
<pre class="brush: python; highlight: [3,10]; title: ; notranslate">
import sys
from scheme_read import scheme_read
from scheme_eval import scheme_eval, special_forms, global_environment
from scheme_types import Pair
from buffered_input import Buff

special_forms['load'](Pair(&quot;syntax.scm&quot;, None))

while True:
  inp = scheme_eval(scheme_read(Buff(sys.stdin)), global_environment)
  if inp != None:
    print ';===&gt;', inp
</pre>
<p><strong>syntax.chicken</strong></p>
<pre class="brush: plain; highlight: [2,3,7,8,12,13,14,16]; title: ; notranslate">
(scheme-syntax define-primitive &quot;
def f(expr, env):
  set_symbol(expr.car, Primitive(eval(expr.cdr.car)), env)
&quot;)

(scheme-syntax define &quot;
def f(expr, env):
  set_symbol(expr.car, scheme_eval(expr.cdr.car, env), env)
&quot;)

(scheme-syntax if &quot;
def f(expr, env):
  if scheme_eval(expr.car, env):
    return scheme_eval(expr.cdr.car, env)
  else:
    return scheme_eval(expr.cdr.cdr.car, env)
&quot;)
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
(define a 5)
a
;===&gt; 5
(if 1 2 3)
;===&gt; 2
(if #f 1 2)
;===&gt; 2
(define-primitive + &quot;lambda x,y: x+y&quot;)
(+ 3 5)
;===&gt; 8
</pre>
<p>If you still don&#8217;t fully understand environments, that&#8217;s OK.  You&#8217;ll get a chance to play around with them in the next part where we&#8217;ll finally cover implementing procedures in Lispy!</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.09">Checkout this version on GitHub (v0.09)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-lambda/" title="Scheme in Python – lambda">GOTO Part 10 | lambda</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-environments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Primitive procedures and apply</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-primitive-procedures-and-apply/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-primitive-procedures-and-apply</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-primitive-procedures-and-apply/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 20:16:32 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1652</guid>
		<description><![CDATA[GOTO Part 7 &#124; Refactor and load The goal for this part is to implement primitive procedures, apply and a method of setting new primitives. The first thing we need to do is figure out a way to represent our primitive procedures. SICP uses tagged lists, which are just regular lists with the first element [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-refactor-and-load/" title="Scheme in Python – Refactor and load">GOTO Part 7 | Refactor and load</a></p>
<p>The goal for this part is to implement primitive procedures, apply and a method of setting new primitives.</p>
<p>The first thing we need to do is figure out a way to represent our primitive procedures. <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html#%_sec_4.1.3"> SICP</a> uses tagged lists, which are just regular lists with the first element designated as a tag.  Python uses objects to define new types and since we&#8217;ve already been doing that, we&#8217;ll continue here.  </p>
<pre class="brush: python; highlight: [25,26,27]; title: ; notranslate">
class Symbol(str):
  &quot;&quot;&quot;A symbol is an immutable string, but must be its own type.&quot;&quot;&quot;
  pass

class The_Empty_List():
  &quot;&quot;&quot;The empty list is used as a list terminator and should be a singleton&quot;&quot;&quot;
  def __repr__(self):
    return &quot;()&quot;

the_empty_list = The_Empty_List()

class Pair(object):
  &quot;&quot;&quot;A pair is a classic Lisp cons cell used to implement lists&quot;&quot;&quot;
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr
  def __iter__(self):
    x = self
    while not isinstance(x, The_Empty_List):
      yield x.car
      x = x.cdr
  def __repr__(self):
    return &quot;(&quot; + ' '.join([str(i) for i in list(self)]) + &quot;)&quot;

class Primitive(object):
  def __init__(self, fn):
    self.fn = fn
</pre>
<p>If the symbol of an expression of the form (symbol args &#8230;) is not found in special_forms it must be a procedure application (or not exist).  To apply a primitive procedure first we have to evaluate all the arguments using scheme_eval.  Then we use that list as the args value to apply(primitive, args).  The primitive returns a Scheme value and we continue on.</p>
<p>For now we&#8217;re going to hardcode one primitive + into our interpreter.  We&#8217;ll come up with something a little more elegant next.</p>
<pre class="brush: python; highlight: [1,5,27,31,32,33,34,35]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair, Primitive
from buffered_input import Buff
from scheme_read import scheme_read

frame = {'+':Primitive(lambda x,y: x+y)}
special_forms = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr)
    else:
      return scheme_apply(scheme_eval(expr.car), [scheme_eval(a) for a in expr.cdr])
  else:
    return &quot;scheme_eval: not implemented&quot;

def scheme_apply(proc, args):
  if type(proc) is Primitive:
    return apply(proc.fn, args)
  else:
    return &quot;Error: Undefined procedure&quot;

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

def load(expr):
  &quot;&quot;&quot;Given a filename, open it and eval each expression in the global_environment&quot;&quot;&quot;
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_eval(scheme_read(b))
    b.remove_whitespace()
  f.close()

special_forms['scheme-syntax'] = special_form_handler
special_forms['load'] = load
</pre>
<pre class="brush: plain; title: ; notranslate">
(+ 3 4)
;===&gt; 7
(- 3 4)
;===&gt; Error: Undefined procedure
</pre>
<p>The next step is to allow defining primitive procedures from within Scheme, as we did with special forms.  We&#8217;ll implement define-primitive as a scheme-syntax macro.  First remove the line that sets the + symbol.  We&#8217;re only going to be modifying the syntax.scm file for now so that&#8217;s all I&#8217;ll show you.</p>
<p>We need to create a scheme-syntax macro that makes a Primitive object and sets it as the value of a symbol.  This macro is a lot like the define macro that we wrote earlier.  The only difference is instead of calling scheme_eval on the cadr we call eval and pass that result to make-primitive.</p>
<p><strong>syntax.scm</strong></p>
<pre class="brush: plain; highlight: [1,2,3,4]; title: ; notranslate">
(scheme-syntax define-primitive &quot;
def f(expr):
  frame[expr.car] = Primitive(eval(expr.cdr.car))
&quot;)

(scheme-syntax define &quot;
def f(expr):
  frame[expr.car] = scheme_eval(expr.cdr.car)
&quot;)

(scheme-syntax if &quot;
def f(expr):
  if scheme_eval(expr.car):
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)
&quot;)
</pre>
<p>With that we can define all sorts of primitives for our language&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
(define-primitive + &quot;lambda x,y: x+y&quot;)
(+ 3 4)
;===&gt; 7
(- 3 4)
;===&gt; Error: Undefined procedure

(define-primitive - &quot;lambda x,y: x-y&quot;)
(- 3 4)
;===&gt; -1

(define-primitive square &quot;lambda x: x*x&quot;)
(square 4)
;===&gt; 16

(define-primitive len &quot;len&quot;)
(len &quot;hello&quot;)
;===&gt; 5
</pre>
<p>You can start a new file and define a bunch of primitives, load it the same way you load syntax.scm.  I&#8217;m not going to define any primitives just yet but you are more than welcome to.  Instead in the next post we&#8217;ll implement environments and then it&#8217;s on to implementing lambda!</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.08">Checkout this version on GitHub (v0.08)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-environments/" title="Scheme in Python – Environments">GOTO Part 9 | Environments</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-primitive-procedures-and-apply/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Refactor and load</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-refactor-and-load/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-refactor-and-load</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-refactor-and-load/#comments</comments>
		<pubDate>Wed, 19 Oct 2011 04:05:44 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1603</guid>
		<description><![CDATA[GOTO Part 6 &#124; scheme-syntax macro In this part we&#8217;re going to be doing a bit of refactoring, so let&#8217;s start with that and a recap. The first thing that we&#8217;re going to do is remove define and if from our language. We&#8217;ll put them back in later, but first let&#8217;s look at what our [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-scheme-syntax-macro-2/" title="Scheme in Python – scheme-syntax macro">GOTO Part 6 | scheme-syntax macro</a></p>
<p>In this part we&#8217;re going to be doing a bit of refactoring, so let&#8217;s start with that and a recap.  The first thing that we&#8217;re going to do is remove define and if from our language.  We&#8217;ll put them back in later, but first let&#8217;s look at what our language looks like with only scheme-syntax defined.</p>
<pre class="brush: python; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair

frame = {}
special_forms = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr)
    else:
      return &quot;Error: unbound special form&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

special_forms['scheme-syntax'] = special_form_handler
</pre>
<p>Let&#8217;s take a moment to consider what we can do so far.  We now have a language that can understand self-evaluating Scheme values and lookup symbol values.  In addition to that it has exactly one primitive, a macro that defines other primitives by giving us access to Python.</p>
<p>You may consider this language lacking, and I admit it does not have many features.  However it is now possible to define any language construct (including procedures, eval and apply) from within Scheme with the help of scheme-syntax and Python underneath.  After writing this code we could define the rest of the language 100% from within Scheme (though it may not be easy).</p>
<p>However there are a few more things that conceptually belong in the core language.  One of those things is the ability to load a Scheme file.  This will let us break out our syntax definitions into another file and load it automatically before we start the repl.</p>
<pre class="brush: python; highlight: [2,3,36,37,38,39,40,41,42,43,46]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair
from buffered_input import Buff
from scheme_read import scheme_read

frame = {}
special_forms = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr)
    else:
      return &quot;Error: unbound special form&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

def load(expr):
  &quot;&quot;&quot;Given a filename, open it and eval each expression in the global_environment&quot;&quot;&quot;
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_eval(scheme_read(b))
    b.remove_whitespace()
  f.close()

special_forms['scheme-syntax'] = special_form_handler
special_forms['load'] = load
</pre>
<p>Now that we have load, we need something to load.  Create a new file called syntax.scm, or whatever you prefer.  This is where we will define our primitive syntax forms like define, if and lambda.  For this moment we&#8217;re going to leave it blank, and make the repl load it by default so we don&#8217;t have to do it manually each time.  </p>
<p>Also I&#8217;m going to make some changes to the repl to make our sessions look more like the examples I&#8217;ve been giving (so ;===> will come before the output and there will be no prompt for input).  Later I may go back to the beginning of this series and change this, as this is how it should have been from the start.  I&#8217;ll also take this opportunity to skip printing any None value which will make using expressions that don&#8217;t return values more aesthetically pleasing.</p>
<p><strong>repl.py</strong></p>
<pre class="brush: python; highlight: [3,4,7,10,11,12]; title: ; wrap-lines: false; notranslate">
import sys
from scheme_read import scheme_read
from scheme_eval import scheme_eval, special_forms
from scheme_types import Pair
from buffered_input import Buff

special_forms['load'](Pair(&quot;syntax.scm&quot;, None))

while True:
  inp = scheme_read(Buff(sys.stdin))
  if inp != None:
    print ';===&gt;', scheme_eval(inp)
</pre>
<p>Now we can define some special forms in syntax.scm to load by default.  For now we&#8217;ll just reimplement define and if.</p>
<p><strong>syntax.scm</strong></p>
<pre class="brush: plain; title: ; notranslate">
(scheme-syntax define &quot;
def f(expr):
  special_forms[expr.car] = scheme_eval(expr.cdr.car)
&quot;)

(scheme-syntax if &quot;
def f(expr):
  if scheme_eval(expr.car):
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)
&quot;)
</pre>
<pre class="brush: plain; title: ; notranslate">
(define a 5)
a
;===&gt; 5
(if 1 2 3)
;===&gt; 2
</pre>
<p>Now that we have implemented load we are one step closer to having a platform that we can build almost any language we want with.  To change languages all we would have to do is load a different syntax file.</p>
<p>I encourage you to play around with that concept for a little while.  Write two different syntax.scm files and implement a couple of basic forms like define, or and if.  Try to make your two implementations as different as possible even if making it different doesn&#8217;t make sense.  For instance in one implementation if could take a mandatory keyword before the alternate branch (if pred consequent else alt) or it could act like and, taking two predicates and only evaluating the consequent branch if both predicates evaluate to true.</p>
<p>This article is a little short on code because we made some larger conceptual changes that I did not want to breeze past.  In the next article we&#8217;ll implement primitive procedures and apply.  The ability to define procedures from within Scheme is just around the corner.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.07">Checkout this version on GitHub (v0.07)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-primitive-procedures-and-apply/" title="Scheme in Python – Primitive procedures and apply">GOTO Part 8 | Primitive procedures and apply</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-refactor-and-load/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; scheme-syntax macro</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-scheme-syntax-macro-2/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-scheme-syntax-macro-2</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-scheme-syntax-macro-2/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 22:18:35 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1587</guid>
		<description><![CDATA[GOTO Part 5 &#124; Assignment and define In the last part we implemented our first special form and the first expression that was not self-evaluating, define. The goal for this part is to implement (if predicate consequent alternate). We&#8217;re going to start by implementing if the same way we implemented define. The first thing to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-assignment-and-define/" title="Scheme in Python – Assignment and define">GOTO Part 5 | Assignment and define</a></p>
<p>In the last part we implemented our first special form and the first expression that was not self-evaluating, define.  The goal for this part is to implement (if predicate consequent alternate).</p>
<p>We&#8217;re going to start by implementing if the same way we implemented define.  The first thing to do is test if the car of the pair equals if, then call a helper procedure we&#8217;ll name apply_if.</p>
<p>We know that if will have to evaluate the predicate argument to determine whether to evaluate the consequent or alternate arguments.  If the predicate is true we will evaluate the consequent expression and not the alternate.  If the predicate is false we will evaluate the alternate expression and not the consequent.</p>
<pre class="brush: python; highlight: [24,25,31,32,33,34,35]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair

frame = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car == &quot;define&quot;:
      frame[expr.cdr.car] = scheme_eval(expr.cdr.cdr.car)
      return &quot;set symbol -&gt; value&quot;
    elif expr.car == &quot;if&quot;:
      return apply_if(expr.cdr.car, expr.cdr.cdr.car, expr.cdr.cdr.cdr.car)
    else:
      return &quot;scheme_eval: not implemented&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;

def apply_if(predicate, consequent, alternate):
  if scheme_eval(predicate):
    return scheme_eval(consequent)
  else:
    return scheme_eval(alternate)
</pre>
<pre class="brush: plain; title: ; notranslate">
(if 1 2 3)
;===&gt; 2
(if #f 2 3)
;===&gt; 3
</pre>
<p>Dispatching special forms using if is fine while you have a small number of primitive syntax forms.  However once you implement a large number of primitive syntax forms this method of dispatch becomes cumbersome.  Also note that it is not possible to extend the primitive syntax forms except by modifying the original source by hand.</p>
<p>&nbsp;</p>
<h3>Reusing the Frame</h3>
<p>On top of that we have already implemented a mechanism of associating and storing symbol and value pairs.  Let&#8217;s try something like that first, we&#8217;ll start by making another global dictionary called special_forms.  Then we&#8217;ll modify eval to check this dictionary instead of using if/elif.</p>
<pre class="brush: python; highlight: [4,22,23,24,25,29,30,31,32,33,34,35,36,37,38,39,40]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair

frame = {}
special_forms = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr)
    else:
      return &quot;Error: unbound special form&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;

def define(expr):
  frame[expr.car] = scheme_eval(expr.cdr.car)
  return &quot;set symbol -&gt; value&quot;

def apply_if(expr):
  if scheme_eval(expr.car):
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)

special_forms['define'] = define
special_forms['if'] = apply_if
</pre>
<pre class="brush: plain; title: ; notranslate">
(repl)
(define a 5)
;===&gt; #&lt;unspecified&gt;
a
;===&gt; 5
(if 1 2 3)
;===&gt; 2
(hello)
;===&gt; Not implemented
</pre>
<p>With that addition we are finished with the first level of the eval function.  An expression can only be one of three things: self-evaluating, a symbol or an application (either syntax or procedure which we&#8217;ll cover later).</p>
<p>How does it work?  special_forms stores (symbol, procedure) pairs where the symbol is a keyword (like define or if) and the procedure is the Python code that implements that special form.  Every procedure in special_forms takes a single argument, an unevaluated pair representing the rest of the expression passed to scheme_eval.  Because special forms have their own evaluation rules, it is the responsibility of this procedure to evaluate the expression and return a result.</p>
<p>In other words, when lispy-eval comes across a special form it transfers control to a Python procedure located in the special_forms dict.  That Python procedure is responsible for evaluating the arguments and returning a Scheme value.</p>
<p>Now that we have a data structure to hold our special_forms it would be a good idea to supply an easy mechanism to set a new special form.  For this purpose we&#8217;ll design a special form in Scheme that will set new special forms called scheme-syntax.</p>
<pre class="brush: python; highlight: [29,30,31,32,33,34]; title: ; wrap-lines: false; notranslate">
from scheme_types import Symbol, Pair

frame = {}
special_forms = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car in special_forms:
      return special_forms[expr.car](expr.cdr)
    else:
      return &quot;Error: unbound special form&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

special_forms['scheme-syntax'] = special_form_handler

def define(expr):
  frame[expr.car] = scheme_eval(expr.cdr.car)
  return &quot;set symbol -&gt; value&quot;

def apply_if(expr):
  if scheme_eval(expr.car):
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)

special_forms['define'] = define
special_forms['if'] = apply_if
</pre>
<pre class="brush: plain; title: ; notranslate">
(scheme-syntax quote &quot;def f(expr): return expr.car&quot;)
;===&gt; None
(1 2 3)
;===&gt; Error: unbound special form
(quote (1 2 3))
;===&gt; (1 2 3)
</pre>
<p>With the addition of scheme-syntax it is now possible to write Python directly in our interpreter.  Because of this we can now implement all of the primitive syntax forms in Scheme.  Some might consider this cheating, but eventually we&#8217;re going to want a way to interface with Python.  Why not implement it right away, use it, test it and make it solid by implementing everything else in it?  We&#8217;ll still have to make some modifications to the core interpreter to implement procedures and a load form later.</p>
<p>Because of Python&#8217;s restrictions on lambda expressions, this solution is not as elegant as the <a href="http://nickzarr.com/blog4/2011/02/scheme-syntax/" title="Lispy in Scheme | scheme-syntax macro">scheme-syntax form in Scheme in Scheme</a>.  For this version you must define a named function, and it must be named &#8220;f&#8221; to make this implementation work.  If you know of a more elegant way to approach this please let me know in the comments.  </p>
<p>We haven&#8217;t even gotten to the mutually recursive yin-yang that is the eval/apply cycle yet.  However, thanks to piggy-backing on Python, we already have a somewhat useful language.  A language without procedures is a pretty bad one, so we&#8217;ll keep pressing on, but check out some of the things that are possible already&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
(scheme-syntax print &quot;
def f(expr):
  print scheme_eval(expr.car)
  return None
&quot;)
;===&gt; None
(scheme-syntax loop &quot;
def f(expr):
  for n in range(scheme_eval(expr.car)):
    scheme_eval(expr.cdr.car)
&quot;)
;===&gt; None
(loop 3 (print &quot;Hi&quot;))
;===&gt; Hi
;===&gt; Hi
;===&gt; Hi
;===&gt; None
</pre>
<p>In the next article we&#8217;ll do  a little refactoring, remove define and if from the core of the interpreter and implement a load function so we can remove our syntax definitions out of the main interpreter file.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.06">Checkout this version on GitHub (v0.06)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-refactor-and-load/" title="Scheme in Python – Refactor and load">GOTO Part 7 | Refactor and load</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-scheme-syntax-macro-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Assignment and define</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-assignment-and-define/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-assignment-and-define</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-assignment-and-define/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 04:14:03 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1574</guid>
		<description><![CDATA[GOTO Part 4 &#124; Self-evaluating values Our goal in this part is to implement assignment via the form (define symbol value). There are three challenges to this goal. First we need to come up with a system to store symbol names and their values. Then we need to display those values when the symbol is [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-self-evaluating-values/" title="Scheme in Python – Self-evaluating values">GOTO Part 4 | Self-evaluating values</a></p>
<p>Our goal in this part is to implement assignment via the form (define symbol value).  There are three challenges to this goal.  First we need to come up with a system to store symbol names and their values.  Then we need to display those values when the symbol is eval&#8217;d.  Finally we need to recognize the define form and set the value of its symbol.</p>
<p>&nbsp;</p>
<h3>Starting with a Stub</h3>
<p>To start with we need to modify our eval procedure to recognize symbols.  We&#8217;ll call a procedure lookup_symbol_value that will eventually give the value of the symbol.  Right now we&#8217;ll just have it return a string stating our intentions.</p>
<pre class="brush: python; highlight: [1,3,4,13,14]; title: ; notranslate">
from scheme_types import Symbol

def lookup_symbol_value(symbol):
  return &quot;Here's where we lookup the value of the symbol.&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  else:
    return &quot;scheme_eval: not implemented&quot;
</pre>
<p>&nbsp;</p>
<h3>The Global Frame</h3>
<p>To set the value of a symbol we need to have somewhere to set it.  That somewhere is going to be a <a href="http://nickzarr.com/blog4/2011/02/20/what-in-the-hell-are-hash-tables/">dictionary</a>.  The dictionary that stores a set of names and their associated values is referred to as a frame.</p>
<p>For now we&#8217;ll define our frame as a global variable named frame.  Since we don&#8217;t have any method of assigning values to symbols yet, we define a symbol &#8220;test&#8221; when we make the frame so we can see if it works.</p>
<pre class="brush: python; highlight: [3,6,7,8,9]; title: ; notranslate">
from scheme_types import Symbol

frame = {'test':&quot;Value retrieved successfully&quot;}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  else:
    return &quot;scheme_eval: not implemented&quot;
</pre>
<p><br/></p>
<pre class="brush: plain; title: ; notranslate">
test
;===&gt; Value retrieved successfully
hello
;===&gt; Error: Unbound variable
</pre>
<p><br/></p>
<h3>(define symbol value)</h3>
<p>Now that we can store and retrieve the value of a symbol, we need a way to do it from within Scheme.  Scheme uses the form (define symbol value) to define a new symbol or set the value of an existing symbol.</p>
<p>The form (define symbol value) is a pair (also a list, but all lists are also pairs) so the first step to detecting its usage is to look for pairs.  The next step is to check the symbol in the car of that pair (or the first item of the list), if that symbol is &#8220;define&#8221; we run the code to define a symbol.  For now we&#8217;ll just return a string stating our intentions.</p>
<pre class="brush: python; highlight: [1,20,21,22,23,24]; title: ; notranslate">
from scheme_types import Symbol, Pair

frame = {'test':&quot;Value retrieved successfully&quot;}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car == &quot;define&quot;:
      return &quot;set the value of the symbol&quot;
    else:
      return &quot;scheme_eval: not implemented&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;
</pre>
<p><br/></p>
<pre class="brush: plain; title: ; notranslate">
test
;===&gt; Value retrieved successfully
(define a 1)
;===&gt; Set the value of the symbol.
(set a 1)
;===&gt; scheme_eval: not implemented
</pre>
<p><br/></p>
<h3>Setting the Value of Symbols</h3>
<p>To actually set the value of the symbol we need to get the arguments to define.  Getting the symbol argument is straightforward, however we need to eval the value argument as it might not be self-evaluating.</p>
<p>Usually (define symbol value) will return void, or nothing.  I have chosen to return a string here to give some visual feedback that setting the symbol happened as well as avoid having to modify the repl to handle None.  You can choose to take the more standard approach and return None here, then modify the repl to skip printing None values.</p>
<pre class="brush: python; highlight: [22,23]; title: ; notranslate">
from scheme_types import Symbol, Pair

frame = {}

def lookup_symbol_value(symbol):
  try:
    return frame[symbol]
  except KeyError:
    return &quot;Error: Unbound variable&quot;

def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) is Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) is Pair:
    if expr.car == &quot;define&quot;:
      frame[expr.cdr.car] = scheme_eval(expr.cdr.cdr.car)
      return &quot;set symbol -&gt; value&quot;
    else:
      return &quot;scheme_eval: not implemented&quot;
  else:
    return &quot;scheme_eval: not implemented&quot;
</pre>
<p><br/></p>
<pre class="brush: plain; title: ; notranslate">
a
;===&gt; Error: Unbound variable
(define a 5)
;===&gt; set symbol -&gt; value
a
;===&gt; 5
</pre>
<p><br/></p>
<p>In addition to being able to set symbols, we now have a glimpse into how basic forms (like define) are handled.  It really is no more complicated than checking the procedure name, evaluating the arguments that need to be, then passing the arguments to a Python procedure that implements the desired functionality.</p>
<p>* To any Schemers that may be reading this:  I avoided implementing environments here for two reasons.  I wanted to show the simplest implementation possible and in an upcoming post we will transform our global frame into a lookup table for primitive syntax.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.05">Checkout this version on GitHub (v0.05)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-scheme-syntax-macro-2/" title="Scheme in Python – scheme-syntax macro">GOTO Part 6 | scheme-syntax macro</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-assignment-and-define/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Self-evaluating values</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-self-evaluating-values/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-self-evaluating-values</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-self-evaluating-values/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 04:24:37 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1558</guid>
		<description><![CDATA[GOTO Part 3 &#124; Pairs and linked lists In the last post we finished implementing the read layer. There is a lot of room for improvement, however it will serve our purposes for the moment. With the read layer complete we can move on to the eval layer. The eval layer is where the Scheme [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-pairs-and-linked-lists/" title="Scheme in Python – Pairs and linked lists">GOTO Part 3 | Pairs and linked lists</a></p>
<p>In the last post we finished implementing the read layer.  There is a lot of room for improvement, however it will serve our purposes for the moment.  With the read layer complete we can move on to the eval layer.</p>
<p>The eval layer is where the <a href="http://nickzarr.com/blog4/series/lispy-in-scheme/" title="Lispy in Scheme">Scheme in Scheme</a> series starts and from here on there will be many similarities between these two series.  In fact a sizable portion of this post was simply copy/pasted from the <a href="http://nickzarr.com/blog4/series/lispy-in-scheme/" title="Lispy in Scheme">Scheme in Scheme</a> series.  With the exception of the code and language specific explanation of it, the rest of the series will also be a close replica.</p>
<p>Create a new file called scheme_eval.py, the rest of this series will focus mainly on this file.  In it we will define a function scheme_eval.  For now we&#8217;re simply going to echo the input back without processing it at all.</p>
<p><strong>scheme_eval.py</strong></p>
<pre class="brush: python; highlight: [1,2]; title: ; notranslate">
def scheme_eval(expr):
  return expr
</pre>
<p><strong>repl.py</strong></p>
<pre class="brush: python; highlight: [3,8]; title: ; notranslate">
import sys
from scheme_read import scheme_read
from scheme_eval import scheme_eval
from buffered_input import Buff

while True:
  print &quot;&gt; &quot;,
  print scheme_eval(scheme_read(Buff(sys.stdin)))
</pre>
<p>With that we have the basic layout of the interpreter.  If you read the last line backward you will see the layers of the interpreter print(eval(read(stdin))) all wrapped up in an infinite loop.  From this point we can concentrate on evaluating the expressions that scheme_read returns.</p>
<p><br/></p>
<h3>A Language of Numbers</h3>
<p>The simplest language is a language of numbers. Numbers are self-evaluating, so if the expression is a number we’ll just return it for now.  If the expression is anything else, we&#8217;ll return an error string, just as we did in the read layer.  If you are following along, you will probably want to add proper errors/error handling to your version.</p>
<pre class="brush: python; highlight: [2,3,4,5]; title: ; notranslate">
def scheme_eval(expr):
  if type(expr) is int:
    return expr
  else:
    return &quot;scheme_eval: not implemented&quot;
</pre>
<p><br/></p>
<h3>A Language of Self-Evaluating Values</h3>
<p>Continuing with our language of self-evaluating values is just as simple. Booleans, strings and characters are also self-evaluating so we’ll add them now. More complex data structures like hash tables are also self evaluating, however we’ll leave them for later.</p>
<pre class="brush: python; highlight: [1,2,3,6]; title: ; notranslate">
def self_evaluating(expr):
  t = type(expr)
  return t is int or t is float or t is str or t is bool

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  else:
    return &quot;scheme_eval: not implemented&quot;
</pre>
<p>The first stage of the eval layer is complete. We now have a functional language of self-evaluating values. Though one could argue exactly how functional it really is. The next step along our path will be to introduce symbols and implement assignment.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.04">Checkout this version on GitHub (v0.04)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-assignment-and-define/" title="Scheme in Python – Assignment and define">GOTO Part 5 | Assignment and define</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-self-evaluating-values/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Pairs and linked lists</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-pairs-and-linked-lists/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-pairs-and-linked-lists</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-pairs-and-linked-lists/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 22:53:19 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1514</guid>
		<description><![CDATA[GOTO Part 2 &#124; Extending the read layer In the last post we added support for booleans, characters, symbols and strings. There is only one major data type left to add in the read layer, the pair/linked list. A pair is a structure which contains 2 elements normally referred to as the car and cdr [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-extending-the-read-layer/" title="Scheme in Python – Extending the read layer">GOTO Part 2 | Extending the read layer</a></p>
<p>In the last post we added support for booleans, characters, symbols and strings.  There is only one major data type left to add in the read layer, the pair/linked list.</p>
<p>A pair is a structure which contains 2 elements normally referred to as the <strong>car</strong> and <strong>cdr</strong> in Scheme.  Lists are built on top of pairs where the car is some value and the cdr is another pair or the empty list.  In a <em>proper list</em> the cdr of the last pair must be the empty list.</p>
<p>To illustrate this concept a bit more clearly here is a diagram of the list &#8216;(1 2 3) in Scheme:</p>
<p><img src="http://docs.google.com/drawings/pub?id=1D5UHl9anYnTkiFgjCKYt14-MTUnCa4oXYiqGQkL6NpM&amp;w=354&amp;h=55"></p>
<p>This list is constructed out of 3 pairs.  The car of the first pair is the value 1 and the cdr is the second pair.  The car of the second pair has the value 2 and the cdr is the third pair.  The car of the third pair has the value 3 and the cdr contains the empty list (Nil in the diagram).</p>
<pre class="brush: python; title: ; notranslate">
class Pair:
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr
</pre>
<p>Above is the class definition for a very simple Pair object in Python.  We can construct the above list using the Pair class as follows:</p>
<pre class="brush: python; title: ; notranslate">
lst = Pair(1, Pair(2, Pair(3, None)))
</pre>
<p>This implementation of a list is called a linked list and you can find a more detailed description in my article <a href="http://nickzarr.com/blog4/2011/02/what-in-the-hell-are-linked-lists/" title="What In The Hell Are Linked Lists">WITH Linked Lists</a>.  Python does not have an implementation of a list in the core language, the list data type in Python is called an array in most other languages.</p>
<p>Scheme sourcecode is written using the linked list data type.  This is one of the most powerful features of the language as the sourcecode is just a regular Scheme data type.  This allows some really interesting features such as macros, but we won&#8217;t get into that just yet.</p>
<p>To start with we&#8217;ll implement the empty list.  Since this is a distinct object in Scheme we&#8217;ll make a new type called The_Empty_List and since we only need one empty list we&#8217;ll also make a global variable to refer to it called the_empty_list.  We&#8217;ll do this in the scheme_types.py file.</p>
<pre class="brush: python; highlight: [5,6,7,8,9,10]; title: ; notranslate">
class Symbol(str):
  &quot;&quot;&quot;A symbol is an immutable string, but must be its own type.&quot;&quot;&quot;
  pass

class The_Empty_List():
  &quot;&quot;&quot;The empty list is used as a list terminator and should be a singleton&quot;&quot;&quot;
  def __repr__(self):
    return &quot;()&quot;

the_empty_list = The_Empty_List()
</pre>
<p>Now that we have an empty list type we need to modify our reader to recognize it.  When the &#8220;(&#8221; character is encountered, scheme_read will call read_pair.  Since the only pair we&#8217;re going to allow for the moment is the empty list, we just need to check that the next character is &#8220;)&#8221; and return the_empty_list.</p>
<pre class="brush: python; highlight: [1,65,66,67,68,69,93,94]; title: ; notranslate">
from scheme_types import Symbol, the_empty_list

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return c.isalpha() or c in '-+*/&gt;&lt;=?!&amp;'

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  c = f.getc()
  if c == 's' and f.peek() == 'p':
    read_expected_string(f, &quot;pace&quot;)
    return ' '
  elif c == 'n' and f.peek() == 'e':
    read_expected_string(f, &quot;ewline&quot;)
    return '\n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while c != '\&quot;':
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  elif is_initial(c):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>With that done, we&#8217;re only two steps away from being able to read linked lists.  First we have to create a Pair type that will represent a Scheme pair.  To do this, we&#8217;ll add the following to the scheme_types.py file.</p>
<pre class="brush: python; highlight: [12,13,14,15,16,17,18,19,20,21,22]; title: ; notranslate">
class Symbol(str):
  &quot;&quot;&quot;A symbol is an immutable string, but must be its own type.&quot;&quot;&quot;
  pass

class The_Empty_List():
  &quot;&quot;&quot;The empty list is used as a list terminator and should be a singleton&quot;&quot;&quot;
  def __repr__(self):
    return &quot;()&quot;

the_empty_list = The_Empty_List()

class Pair(object):
  &quot;&quot;&quot;A pair is a classic Lisp cons cell used to implement lists&quot;&quot;&quot;
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr
  def __iter__(self):
    x = self
    while not isinstance(x, The_Empty_List):
      yield x.car
      x = x.cdr
  def __repr__(self):
    return &quot;(&quot; + ' '.join([str(i) for i in list(self)]) + &quot;)&quot;
</pre>
<p>In addition to a car and cdr field I have also implemented the __iter__ and __repr__ special methods.  __iter__ will help us later on when we work with these pairs by allowing easy conversion to a Python list data type or allowing the use of for/in or map.  For more information on __iter__ see the <a href="http://docs.python.org/library/stdtypes.html#typeiter">Python docs on iterators</a>.</p>
<p>The only thing left to do is modify read_pair.  The procedure to read a pair is as follows:</p>
<ol>
<li>Get a value for the car slot by calling scheme_read on the input file</li>
<li>Remove any whitespace</li>
<li>Get a value for the cdr by calling read_pair on the input file
<ul>
<li>If the next character is &#8220;)&#8221; set the cdr to the_empty_list</li>
<li>If the next character is anything else set the cdr to a new pair by calling read_pair</li>
</ul>
</li>
</ol>
<pre class="brush: python; highlight: [1,70,71,72,73,74]; title: ; notranslate">
from scheme_types import Symbol, the_empty_list, Pair

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return c.isalpha() or c in '-+*/&gt;&lt;=?!&amp;'

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  c = f.getc()
  if c == 's' and f.peek() == 'p':
    read_expected_string(f, &quot;pace&quot;)
    return ' '
  elif c == 'n' and f.peek() == 'e':
    read_expected_string(f, &quot;ewline&quot;)
    return '\n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while c != '\&quot;':
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  elif is_initial(c):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>There are two things to note about this implementation.  First, () is matched as the_empty_list when it really shouldn&#8217;t be, the correct syntax is &#8216;().  Second, any literal list over 1,000 elements will hit Python&#8217;s recursion limit.  This shouldn&#8217;t be a problem in the vast majority of cases, however it is something to be aware of.</p>
<p>With that, the read layer of our interpreter is complete (for the purposes of this series, there is a lot more that <em>could</em> be done).  From this point on we will be concentrating on the eval layer of the interpreter.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.03">Checkout this version on GitHub (v0.03)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-self-evaluating-values/" title="Scheme in Python – Self-evaluating values">GOTO Part 4 | Self-evaluating values</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-pairs-and-linked-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Extending the read layer</title>
		<link>http://nickzarr.com/blog4/2011/10/scheme-in-python-extending-the-read-layer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-extending-the-read-layer</link>
		<comments>http://nickzarr.com/blog4/2011/10/scheme-in-python-extending-the-read-layer/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 15:09:38 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1501</guid>
		<description><![CDATA[GOTO Part 1 &#124; Numbers In the last post we created a read function that worked with integers and floating point numbers. We also covered the basic layout of the read function. In this post we will extend the read function to handle booleans, characters, strings and symbols. We&#8217;ll start with booleans as they are [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/09/scheme-in-python-numbers/" title="Scheme in Python – Numbers">GOTO Part 1 | Numbers</a></p>
<p>In the last post we created a read function that worked with integers and floating point numbers.  We also covered the basic layout of the read function.  In this post we will extend the read function to handle booleans, characters, strings and symbols.</p>
<p>We&#8217;ll start with booleans as they are the smallest set.  There are 2 boolean values in Scheme #t and #f, which represent true and false respectively.  You probably noticed that both start with a # character and that is how we will recognize them in the reader.</p>
<p>We will represent #t and #f by the Python values True and False.  Since the code for this is so simple, we will handle this within the scheme_read function.</p>
<pre class="brush: python; highlight: [27,28,29,30,31,32,33,34]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>The code to handle booleans is pretty straightforward.  If the first character is #, then we get the next character.  If the next character is t or f, we return the appropriate boolean.  Otherwise, we return an error string.</p>
<p>The next thing we&#8217;ll handle is characters.  Characters in Scheme also start with the # symbol followed by a \, which gives us #\c where c is any character.  </p>
<p>There are some special characters, but we&#8217;ll start by implementing the basics.  We&#8217;ll check if an expression is a character in the same place as we check for booleans since they&#8217;re so similar.</p>
<pre class="brush: python; highlight: [20,21,22,37,38]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def read_character(f):
  c = f.getc()
  return c

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>Scheme has a few special characters that we must deal with, namely #\space and #\newline.  These will require a bit more work to process.  To help, we&#8217;ll define a function read_expected_string which will consume characters from the input buffer, provided they match what&#8217;s expected (and return an error if they don&#8217;t).</p>
<p>I won&#8217;t go over the workings of read_expected_string any further than to say it compares characters from the expected string and the input buffer one-by-one until it reaches the end.  We also need to add a check in read_character if the input buffer contains #\s or #\n.  Both of these could be either the characters s or n or the special characters #\space or #\newline.  To tell the difference we need to check the next character.</p>
<p>There are a few problems with this implementation, namely if you enter an invalid special character such as #\spxce it will leave unconsumed characters on the input buffer and will not return the error string.  Handling these error conditions would add a lot of bloat to the code, though you would definitely want to do this in your own implementation.</p>
<pre class="brush: python; highlight: [20,21,22,23,24,25,26,27,28,29,33,34,35,36,37,38,39,40]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  c = f.getc()
  if c == 's' and f.peek() == 'p':
    read_expected_string(f, &quot;pace&quot;)
    return ' '
  elif c == 'n' and f.peek() == 'e':
    read_expected_string(f, &quot;ewline&quot;)
    return '\n'
  else:
    return c

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>Next up are symbols, which are the names of variables/constants.  In most other languages symbols are not given their own type and you, as a user, are not allowed to manipulate them as first-class values.  However this is not the case in Scheme.</p>
<p>We will represent symbols in our implementation as strings.  However since we also need to implement strings, it is necessary to make symbols a distinct type.  Since we will need to make other types as well as have access to them outside the read layer, make a new file called scheme_types.py and enter the following definition.</p>
<pre class="brush: python; title: ; notranslate">
class Symbol(str):
  &quot;&quot;&quot;A symbol is an immutable string, but must be its own type.&quot;&quot;&quot;
  pass
</pre>
<p>How do we know if an expression is a symbol?  There is a limited set of values that a symbol may start with.  To test if a character is part of this set, we&#8217;ll provide a function is_initial.</p>
<p>Once we&#8217;ve identified that the expression is a symbol, the next step is to read each character into a buffer until we&#8217;ve hit a delimiter (just like reading a number).  Then we turn the buffer into a string and pass it to Symbol to create a new symbol.</p>
<pre class="brush: python; highlight: [1,7,8,9,48,49,50,51,52,53,54,55,74,75,76]; title: ; notranslate">
from scheme_types import Symbol

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return c.isalpha() or c in '-+*/&gt;&lt;=?!&amp;'

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  c = f.getc()
  if c == 's' and f.peek() == 'p':
    read_expected_string(f, &quot;pace&quot;)
    return ' '
  elif c == 'n' and f.peek() == 'e':
    read_expected_string(f, &quot;ewline&quot;)
    return '\n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  elif is_initial(c):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>The reader does not lookup the value of symbols, that&#8217;s the job of the eval layer, so we&#8217;re all done for handling symbols.  </p>
<p>With symbols done we only have strings left to implement for this part in the series.  Luckily the implementation for strings is almost exactly the same as the one for symbols.  Strings in Scheme start and end with &#8220;, so an expression is a string if the first character is a &#8220;.</p>
<p>The read_string function we&#8217;ll provide is a copy/paste of the read_symbol function with only one change.  Instead of <em>while not is_delimiter(c)</em> we will use <em>while c != &#8216;\&#8221;&#8216;</em> since delimiter characters are allowed to appear in strings.  Since the functionality is identical, you could abstract this into one function by adding a parameter that passes the stopping condition.  However I feel that it&#8217;s more clear, for this series, as two.</p>
<pre class="brush: python; highlight: [57,58,59,60,61,62,63,85,86]; title: ; notranslate">
from scheme_types import Symbol

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return c.isalpha() or c in '-+*/&gt;&lt;=?!&amp;'

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  c = f.getc()
  if c == 's' and f.peek() == 'p':
    read_expected_string(f, &quot;pace&quot;)
    return ' '
  elif c == 'n' and f.peek() == 'e':
    read_expected_string(f, &quot;ewline&quot;)
    return '\n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while c != '\&quot;':
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
    else:
      return &quot;Error boolean value must be #t or #f not #&quot; + c
  elif is_initial(c):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>With string handling completed there is only one major feature left for scheme_read, pairs.  Pairs are used to implement linked lists in Scheme.  The linked list is a very important data structure as all Scheme code is written and parsed into linked list format.  This code/data duality is one of the things that gives Scheme (and other Lisps) its great power.  The next post will be about the implementation of linked lists and how to parse them.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.02">Checkout this version on GitHub (v0.02)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-pairs-and-linked-lists/" title="Scheme in Python – Pairs and linked lists">GOTO Part 3 | Pairs and linked lists</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/10/scheme-in-python-extending-the-read-layer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Numbers</title>
		<link>http://nickzarr.com/blog4/2011/09/scheme-in-python-numbers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-numbers</link>
		<comments>http://nickzarr.com/blog4/2011/09/scheme-in-python-numbers/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 04:08:19 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1476</guid>
		<description><![CDATA[GOTO Part 0 &#124; Reading from stdin Stage 1 of implementing Scheme in Python is to write the reader. The entire read layer is self-contained so we don&#8217;t need to worry about evaluating and printing values just yet. To start with let&#8217;s take a look at the basic shape of the read function. We&#8217;re going [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/09/scheme-in-python-reading-from-stdin/" title="Scheme in Python – Reading from stdin">GOTO Part 0 | Reading from stdin</a></p>
<p>Stage 1 of implementing Scheme in Python is to write the reader.  The entire read layer is self-contained so we don&#8217;t need to worry about evaluating and printing values just yet.</p>
<p>To start with let&#8217;s take a look at the basic shape of the read function.  We&#8217;re going to call it scheme_read to avoid any name clashes that might arise, but other than that it should be more-or-less equivalent to any other Scheme read function.</p>
<pre class="brush: python; title: ; notranslate">
def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c:
    return &quot;Representation of a Scheme type.&quot;
</pre>
<p>scheme_read(f) is called with a buffered file-like object <strong>f</strong> that must support getc, ungetc, peek and remove_whitespace methods.  First we remove any leading whitespace as whitespace in Scheme is only significant as a delimiter.</p>
<p>Before we get started let&#8217;s implement a simple repl so that we can play with our new features as we add them.  Create a new file named repl.py and insert the following code.</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python
import sys
from scheme_read import scheme_read
from buffered_input import Buff

while True:
  print &quot;&gt; &quot;,
  print scheme_read(Buff(sys.stdin))
</pre>
<p>The next step is to get the first non-whitespace character, which we store in the variable <strong>c</strong>.  We will use this character (and possibly the next) to determine the type of the expression.  For instance if <strong>c</strong> is a digit then the remaining characters (until the next delimiter) must form a number, since digits are not allowed as the first character of an identifier.  We&#8217;ll do this check in the <strong>if c:</strong> portion of our code.  Let&#8217;s look at that code.</p>
<pre class="brush: python; highlight: [4,5]; title: ; notranslate">
def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit():
    return &quot;Representation of a Scheme number.&quot;
</pre>
<p>What if c is not a digit?  In that case, our read function does not recognize the input and we should return something that states this fact.  For now let&#8217;s just return a string that says &#8220;scheme_read: not implemented&#8221;.  Later on you may wish to make this a proper error, but returning a string here keeps things simple.</p>
<pre class="brush: python; highlight: [6,7]; title: ; notranslate">
def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit():
    return &quot;Representation of a Scheme number.&quot;
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>Now obviously, &#8220;Representation of a Scheme number.&#8221; is not actually a representation of a Scheme number.  To get that we have to read the number from <strong>f</strong>.  Instead of putting all the logic of reading a number into the if block, we should use a helper function here called read_number.</p>
<pre class="brush: python; highlight: [1,2,8]; title: ; notranslate">
def read_number(f):
  return &quot;Representation of a Scheme number.&quot;

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit():
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>We pass the file object <strong>f</strong> to <strong>read_number</strong> so that it can read and return the rest of the number.  But wait, we already read the first digit!  Before we pass the work off to <strong>read_number</strong>, we have to put the first digit back onto <strong>f</strong>.  We do this using the ungetc method.</p>
<pre class="brush: python; highlight: [8]; title: ; notranslate">
def read_number(f):
  return &quot;Representation of a Scheme number.&quot;

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit():
    f.ungetc(c)
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>Now to read a number we simply read a character at a time, placing each into a buffer, until we hit a delimiter.  To make that job easier we&#8217;ll provide a function <strong>is_delimiter</strong> that takes a character and returns <strong>True</strong> if that character is a delimiter and <strong>False</strong> if not.  Then we&#8217;ll use that to build a buffer and return an integer.</p>
<pre class="brush: python; highlight: [1,2,3,4,7,8,9,10,11,12,13]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  return int(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit():
    f.ungetc(c)
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>That takes care of positive integers, however the positive integers are a very small subset of numbers.  We are going to want to handle negative integers as well as positive and negative floating point numbers at least.  Luckily, this is very simple to do in Python.</p>
<pre class="brush: python; highlight: [13,14,15,16]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit():
    f.ungetc(c)
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>However, we&#8217;re not quite done yet.  Our implementation won&#8217;t handle negative numbers.  To do that we&#8217;re going to have to go back to the reader because &#8220;-&#8221; is not a digit and our current implementation will skip right over it.</p>
<pre class="brush: python; highlight: [23]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if c.isdigit() or (c == '-' and f.peek().isdigit()):
    f.ungetc(c)
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>We&#8217;re still not quite done though.  What about floating point values where 0 < n < 1 that start with a decimal point?</p>
<pre class="brush: python; highlight: [24]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (&#8216; &#8216;, &#8216;(&#8216;, &#8216;)&#8217;, &#8216;\&quot;&#8217;, &#8216;;&#8217;, &#8216;\n&#8217;) or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if &#8216;.&#8217; in buf:
    return float(buf)
  elif &#8216;/&#8217; in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == &#8216;-&#8217; and f.peek().isdigit())
      or (c == &#8216;.&#8217; and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>But wait, there's more!  What about negative floating point numbers where -1 < n < 0 which start with a "-."?</p>
<pre class="brush: python; highlight: [23]; title: ; notranslate">
def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return c in (' ', '(', ')', '\&quot;', ';', '\n') or not c

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  buf = &quot;&quot;.join(buf)
  if '.' in buf:
    return float(buf)
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(buf)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  else:
    return &quot;scheme_read: not implemented&quot;
</pre>
<p>As you can see, a lot of the work of implementing a programming language goes into dealing with corner cases.  In the next post we'll extend our reader to handle booleans, characters, strings and symbols.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.01">Checkout this version on GitHub (v0.01)</a></p>
<p><a href="http://nickzarr.com/blog4/2011/10/scheme-in-python-extending-the-read-layer/" title="Scheme in Python – Extending the read layer">GOTO Part 2 | Extending the read layer</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/09/scheme-in-python-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#8211; Reading from stdin</title>
		<link>http://nickzarr.com/blog4/2011/09/scheme-in-python-reading-from-stdin/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-reading-from-stdin</link>
		<comments>http://nickzarr.com/blog4/2011/09/scheme-in-python-reading-from-stdin/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 02:43:03 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Language Design]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1466</guid>
		<description><![CDATA[This implementation of Scheme in Python will be done in three phases: 1) Read Layer 2) Eval Layer 3) Language Layer The read layer The read layer is responsible for consuming source code and transforming it into a data structure so that it can be passed to the eval layer. The eval layer After the [...]]]></description>
			<content:encoded><![CDATA[<p>This implementation of Scheme in Python will be done in three phases:</p>
<p>1) Read Layer<br />
2) Eval Layer<br />
3) Language Layer</p>
<h3>The read layer</h3>
<p>The read layer is responsible for consuming source code and transforming it into a data structure so that it can be passed to the eval layer.</p>
<h3>The eval layer</h3>
<p>After the reader returns a data structure representing the source code, the eval layer evaluates it according to a set of rules and returns a value.</p>
<p>After an expression has been evaluated it&#8217;s value is often printed to the screen.  Immediately after that the program usually loops back to reading the next expression, hence the term REPL (Read, Eval, Print, Loop).</p>
<h3>The language layer</h3>
<p>This interpreter is designed using the &#8220;languages as libraries&#8221; concept.  This approach is currently being used by the Racket and PyPy projects (though in a much more advanced form).</p>
<p>A language is usually defined as the core components, or primitives, plus additional libraries written using those primitives.  In most languages it is an error to attempt to redefine a primitive procedure and even in languages where this is permissible, there is usually no way to swap all of the primitives.</p>
<p>Using the languages as libraries approach, we implement as little as possible in the source code of the interpreter and allow a file to be loaded with definitions of the primitives in the language itself.  This implementation only requires one primitive to be defined at the interpreter level<sup><a href="#1">1</a></sup>, define-syntax, which allows the user to define new primitive syntax.</p>
<h3>Before we begin</h3>
<p>The read function presented here is a port of the read function in <a href="http://michaux.ca/articles/scheme-from-scratch-bootstrap-v0_1-integers">Bootstrap Scheme by Peter Michaux</a>.  His implementation relies on the C functions getc and ungetc.  Unfortunately input in Python is line-buffered and not character-buffered and Python does not provide ungetc.</p>
<p>To accommodate for this I have created a class (Buff) which wraps stdin (or any other file-like object) and provides the functions getc, ungetc and peek.  Reading from input in this manner is not in the least bit Pythonic, however this method of reading is very simple and clearly shows the steps involved in lexing and parsing input strings.</p>
<p>The operation of Buff is simple.  getc reads a single character from the given file if there are no characters waiting in the buffer, otherwise it pops off the last character added to the buffer.  ungetc simply adds a character to the buffer, and peek uses getc to read a character and store it in a variable, then ungetc to put the character back in the buffer.</p>
<pre class="brush: python; title: ; notranslate">
class Buff:
  def __init__(self, f):
    self.f = f
    self.last = []

  def getc(self):
    if self.last:
      return self.last.pop(0)
    else:
      return self.f.read(1)

  def ungetc(self, c):
    self.last.insert(0, c)

  def peek(self):
    if self.last:
      return self.last[0]
    else:
      c = self.f.read(1)
      self.last.append(c)
      return c

  def remove_whitespace(self):
    c = self.getc()
    while c:
      if c == ' ':
        c = self.getc()
      elif c == '\n':
        c = self.getc()
      elif c == ';':
        c = self.getc()
        while c and c != '\n':
          c = self.getc()
        self.ungetc(c)
      else:
        self.ungetc(c)
        break
</pre>
<p>You may notice that there is also a function: remove_whitespace.  This simply reads and discards any characters which are whitespace (space and newline) and discards comments ;starting at the semicolon and continuing until a newline is reached.</p>
<p>With that we have the tools we need to get started building the read level.</p>
<p><a name="1">[1]</a> In theory, in practice we also define &#8220;load&#8221; to avoid the necessity of redefining it every time we restart the interpreter.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python">Checkout this project on GitHub</a></p>
<p><a href="http://nickzarr.com/blog4/2011/09/scheme-in-python-numbers/" title="Scheme in Python – Numbers">GOTO Part 1 | Numbers</a></p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/09/scheme-in-python-reading-from-stdin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Load and Refactor</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-load-and-refactor</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 18:05:06 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1454</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. The scheme-syntax macro adds a lot of power to our language, however the way we&#8217;ve been defining special forms so far does not use that power. To take full [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>The scheme-syntax macro adds a lot of power to our language, however the way we&#8217;ve been defining special forms so far does not use that power.  To take full advantage of scheme-syntax we need to implement a function that will allow us to load a file with syntax definitions into our interpreter.</p>
<p>The load function will work in the same way as all the other special forms, however this will be the only special form that is defined without using scheme-syntax.  All the other special forms will use load combined with scheme-syntax.</p>
<p>First we&#8217;ll define a procedure called load that will take a filename and execute all the expressions in that file.  We will also create a file named scheme_syntax.scm that will hold some test code to make sure the load function works.</p>
<pre class="brush: python; highlight: [180,181,182,183,184,185,186,187,188]; title: ; notranslate">
&quot;&quot;&quot;
scheme.py
(c)2011 Nick Zarczynski
version 0.1
&quot;&quot;&quot;
import sys
from buffered_input import Buff

#############################################################################
## Data Types
#############################################################################

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

#############################################################################
## Environments
#############################################################################

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

#############################################################################
## Read
#############################################################################

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return (c == ' ' or c == '(' or c == ')' or c == '\&quot;'
          or c == ';' or c == '\n' or not c)

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return (c.isalpha() or c == '*' or c == '/' or c == '&gt;' or c == '&lt;'
          or c == '=' or c == '?' or c == '!' or c == '-' or c == '&amp;')

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  if '.' in buf:
    return float(''.join(buf))
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(''.join(buf))

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  &quot;&quot;&quot;Read a character literal including #\space and #\newline&quot;&quot;&quot;
  c = f.getc()
  if c == 's':
    if f.peek() == 'p':
      read_expected_string(f, &quot;pace&quot;)
      return ' '
    else:
      return 's'
  elif c == 'n':
    if f.peek() == 'e':
      read_expected_string(f, 'ewline')
      return '\n'
    else:
      return 'n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while c != '\&quot;':
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
  elif is_initial(c) or ((c == '+' or c == '-') and is_delimiter(f.peek())):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;not implemented (read)&quot;

#############################################################################
## Eval
#############################################################################

def self_evaluating(expr):
  t = type(expr)
  return (t is int or t is float or t is bool
          or t is str or expr == the_empty_list)

special_forms = {}

def apply_define(expr):
  global_environment[expr.car] = scheme_eval(expr.cdr.car)

special_forms['define'] = apply_define

def apply_if(expr):
  pred = scheme_eval(expr.car)
  if pred:
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)

special_forms['if'] = apply_if

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

special_forms['scheme-syntax'] = special_form_handler

def load(expr):
  f = open(expr.car, 'r')
  b = Buff(f)
  while b.peek():
    scheme_print(scheme_eval(scheme_read(b)))
    b.remove_whitespace()
  f.close()

special_forms['load'] = load

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == Pair:
    sym = expr.car
    func = special_forms[sym]
    return func(expr.cdr)
  else:
    return &quot;not implemented (eval)&quot;

#############################################################################
## Print
#############################################################################

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  elif expr is None:
    pass
  else:
    sys.stdout.write(str(expr))

#############################################################################
## REPL
#############################################################################

def repl():
  while 1:
    sys.stdout.write('&gt; ')
    scheme_print(scheme_eval(scheme_read(Buff(sys.stdin))))
    print

if __name__ == &quot;__main__&quot;:
  repl()
</pre>
<p>And here is the scheme_syntax.scm file with the test definitions add and sub.</p>
<pre class="brush: plain; title: ; notranslate">
(scheme-syntax add &quot;
def f(expr):
  return expr.car + expr.cdr.car&quot;)

(scheme-syntax sub &quot;
def f(expr):
  return expr.car - expr.cdr.car&quot;)
</pre>
<p>When you run the interpreter you can load scheme_syntax as follows and <em>add</em> and <em>sub</em> should both work.</p>
<pre class="brush: plain; title: ; notranslate">
&gt; (load &quot;scheme_syntax.scm&quot;)
&gt; (add 3 4)
7
&gt; (sub 3 4)
-1
</pre>
<p>Now that we can define special forms with scheme-syntax and load arbitrary files with the load form we can move our scheme-syntax macros over to the new scheme_syntax.scm file.  This allows us the flexibility to play around with different methods of implementing language features from within our interpreter.</p>
<p>We&#8217;re going to move define and if over to scheme_syntax.scm for now.  Because we still have to implement procedures and environments, I&#8217;ll wait to add more special forms for now, but you can add as many as you like (use <a href="http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-2.html#%_toc_start">R5RS</a> for a guide if you need).  The code for define and if was removed from scheme.py though I won&#8217;t paste the new file as there&#8217;s no changes to highlight.  I also removed the add and sub forms as they&#8217;re no longer needed.</p>
<pre class="brush: plain; title: ; notranslate">
(scheme-syntax define &quot;
def f(expr):
  global_environment[expr.car] = scheme_eval(expr.cdr.car)&quot;)

(scheme-syntax if &quot;
def f(expr):
  pred = scheme_eval(expr.car)
  if pred:
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)&quot;)
</pre>
<p>We&#8217;re not far from having all the basics of a Scheme implementation.  The next few parts will focus on creating primitive procedures, environments and compound procedures.</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; scheme-syntax macro</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-scheme-syntax-macro</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 00:30:00 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1446</guid>
		<description><![CDATA[GOTO Part 6 &#124; Define and If In the last post we briefly discussed how using if/elif/else in scheme_eval could become cumbersome. There is another problem with this approach as well. In order to add new special forms to the language we need to directly modify the source code of the interpreter. Instead of dispatching [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/08/scheme-in-python-define-and-if/" title="Scheme in Python | Define and If">GOTO Part 6 | Define and If</a></p>
<p>In the last post we briefly discussed how using if/elif/else in scheme_eval could become cumbersome.  There is another problem with this approach as well.  In order to add new special forms to the language we need to directly modify the source code of the interpreter.</p>
<p>Instead of dispatching with the if/else construct we can use another means of dispatching that will allow runtime modification by using a dictionary (or hash table).  With this method we use the symbol (so far define and if) as the key for a dictionary lookup.</p>
<p>With this method the symbol (so far define and if) is used as the key and a function that takes the rest of the expression and returns a result is stored in the dictionary.  Let&#8217;s take a look at how this is implemented.</p>
<pre class="brush: python; highlight: [157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,179,180,181]; title: ; notranslate">
&quot;&quot;&quot;
scheme.py
(c)2011 Nick Zarczynski
version 0.1
&quot;&quot;&quot;
import sys
from buffered_input import Buff

#############################################################################
## Data Types
#############################################################################

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

#############################################################################
## Environments
#############################################################################

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

#############################################################################
## Read
#############################################################################

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return (c == ' ' or c == '(' or c == ')' or c == '\&quot;'
          or c == ';' or c == '\n' or not c)

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return (c.isalpha() or c == '*' or c == '/' or c == '&gt;' or c == '&lt;'
          or c == '=' or c == '?' or c == '!' or c == '-' or c == '&amp;')

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  if '.' in buf:
    return float(''.join(buf))
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(''.join(buf))

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  &quot;&quot;&quot;Read a character literal including #\space and #\newline&quot;&quot;&quot;
  c = f.getc()
  if c == 's':
    if f.peek() == 'p':
      read_expected_string(f, &quot;pace&quot;)
      return ' '
    else:
      return 's'
  elif c == 'n':
    if f.peek() == 'e':
      read_expected_string(f, 'ewline')
      return '\n'
    else:
      return 'n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while c != '\&quot;':
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
  elif is_initial(c) or ((c == '+' or c == '-') and is_delimiter(f.peek())):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;not implemented (read)&quot;

#############################################################################
## Eval
#############################################################################

def self_evaluating(expr):
  t = type(expr)
  return (t is int or t is float or t is bool
          or t is str or expr == the_empty_list)

special_forms = {}

def apply_define(expr):
  global_environment[expr.car] = scheme_eval(expr.cdr.car)

special_forms['define'] = apply_define

def apply_if(expr):
  pred = scheme_eval(expr.car)
  if pred:
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)

special_forms['if'] = apply_if

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == Pair:
    sym = expr.car
    func = special_forms[sym]
    return func(expr.cdr)
  else:
    return &quot;not implemented (eval)&quot;

#############################################################################
## Print
#############################################################################

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  else:
    sys.stdout.write(str(expr))

#############################################################################
## REPL
#############################################################################

def repl():
  while 1:
    sys.stdout.write('&gt; ')
    scheme_print(scheme_eval(scheme_read(Buff(sys.stdin))))
    print

if __name__ == &quot;__main__&quot;:
  repl()
</pre>
<p>With this method dispatching is simply retrieving the correct function with special_forms[symbol] and calling it with the rest of the expression.  This also allows us to add special forms directly from our interpreter without having to modify the source code.  Before I get into the implementation in Python, here&#8217;s how this functionality is implemented in <a href="http://nickzarr.com/blog4/2011/02/scheme-syntax/" title="Lispy in Scheme | scheme-syntax macro">Lispy in Scheme&#8217;s scheme-syntax</a> macro.</p>
<pre class="brush: plain; title: ; notranslate">
(define (scheme-syntax expr)
  (hash-table-set! global-syntax-definitions (car expr) (eval (cadr expr))))

;; And it is called like so
(scheme-syntax 'if
  (lambda (expr)
    ;; code to implement if
</pre>
<p>First the symbol <em>if</em> is used as the key in global-syntax-definitions which is Lispy&#8217;s version of global_environment.  Then the lambda expression (written in Scheme) is evaluated and set as the value associated with the symbol.</p>
<p>Unfortunately this cannot be a straightforward port into Python for a couple of reasons.  First lambdas in Python are very limited and are not equivalent to named function definition.  For instance you are not allowed to use statements (such as if, for, etc.) and you are also not allowed to use more than one expression.  This rules out using lambda and means that we have to allow the user to define a regular Python function.</p>
<p>To eval the code now we must use the exec statement, because function definition is a statement and not an expression.  However the exec statement does not allow a return value from the executed code.  For example:</p>
<pre class="brush: plain; title: ; notranslate">
a = exec(&quot;&quot;&quot;
def double(x):
  return x * 2
double
&quot;&quot;&quot;)
</pre>
<p>Will not set <em>a</em> to the function <em>double</em>, rather it will halt with a SyntaxError.  To get around this limitation we will require that the supplied function be named &#8220;f&#8221; using code equivalent to this:</p>
<pre class="brush: python; title: ; notranslate">
def exec_definition(s):
  exec(s)
  return f
</pre>
<p>This creates a new function from the string s.  Hopefully the user follows the convention of naming the function f, otherwise this implementation will fail miserably.</p>
<pre class="brush: python; highlight: [173,174,175,176,177,178]; title: ; notranslate">
&quot;&quot;&quot;
scheme.py
(c)2011 Nick Zarczynski
version 0.1
&quot;&quot;&quot;
import sys
from buffered_input import Buff

#############################################################################
## Data Types
#############################################################################

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

#############################################################################
## Environments
#############################################################################

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

#############################################################################
## Read
#############################################################################

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return (c == ' ' or c == '(' or c == ')' or c == '\&quot;'
          or c == ';' or c == '\n' or not c)

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return (c.isalpha() or c == '*' or c == '/' or c == '&gt;' or c == '&lt;'
          or c == '=' or c == '?' or c == '!' or c == '-' or c == '&amp;')

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  if '.' in buf:
    return float(''.join(buf))
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(''.join(buf))

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  &quot;&quot;&quot;Read a character literal including #\space and #\newline&quot;&quot;&quot;
  c = f.getc()
  if c == 's':
    if f.peek() == 'p':
      read_expected_string(f, &quot;pace&quot;)
      return ' '
    else:
      return 's'
  elif c == 'n':
    if f.peek() == 'e':
      read_expected_string(f, 'ewline')
      return '\n'
    else:
      return 'n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while c != '\&quot;':
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
  elif is_initial(c) or ((c == '+' or c == '-') and is_delimiter(f.peek())):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;not implemented (read)&quot;

#############################################################################
## Eval
#############################################################################

def self_evaluating(expr):
  t = type(expr)
  return (t is int or t is float or t is bool
          or t is str or expr == the_empty_list)

special_forms = {}

def apply_define(expr):
  global_environment[expr.car] = scheme_eval(expr.cdr.car)

special_forms['define'] = apply_define

def apply_if(expr):
  pred = scheme_eval(expr.car)
  if pred:
    return scheme_eval(expr.cdr.car)
  else:
    return scheme_eval(expr.cdr.cdr.car)

special_forms['if'] = apply_if

def special_form_handler(expr):
  &quot;&quot;&quot;Register a symbol with a Python function named &quot;f&quot; that implements a special form&quot;&quot;&quot;
  exec(expr.cdr.car)
  special_forms[expr.car] = f

special_forms['scheme-syntax'] = special_form_handler

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == Pair:
    sym = expr.car
    func = special_forms[sym]
    return func(expr.cdr)
  else:
    return &quot;not implemented (eval)&quot;

#############################################################################
## Print
#############################################################################

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  else:
    sys.stdout.write(str(expr))

#############################################################################
## REPL
#############################################################################

def repl():
  while 1:
    sys.stdout.write('&gt; ')
    scheme_print(scheme_eval(scheme_read(Buff(sys.stdin))))
    print

if __name__ == &quot;__main__&quot;:
  repl()
</pre>
<p>scheme-syntax has become a foreign function interface (or FFI) of sorts, allowing us to write Python functions directly within our interpreter.  For instance, instead of writing define out as:</p>
<pre class="brush: python; title: ; notranslate">
def apply_define(expr):
  global_environment[expr.car] = scheme_eval(expr.cdr.car)

special_forms['define'] = apply_define
</pre>
<p>We can instead write it within our interpreter as:</p>
<pre class="brush: plain; title: ; notranslate">
(scheme-syntax define &quot;
def f(expr):
  global_environment[expr.car] = scheme_eval(expr.cdr.car)&quot;)
</pre>
<p>The scheme-syntax macro adds a considerable amount of power to our interpreter.  Now we can define new primitives and special forms without touching the source code of the interpreter at all.  In fact, we can use scheme-syntax to write both define and if in Scheme, but before we do that we should implement a way to load a Scheme source file so we&#8217;re not mixing Scheme code with Python.  The next part will focus on implementing load, moving our current definitions out of the core interpreter and adding some new ones.</p>
<p>* This implementation of scheme-syntax leaves a lot to be desired, but it works for now.  If you have any suggestions on how to implement this functionality more cleanly, please let me know.</p>
<p><a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.07">Checkout this version on github – v0.07</a></p>
<p>GOTO Part 8 | Refactor and Load</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Define and If</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-define-and-if</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 15:30:49 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1422</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. In the last part we did a pretty major refactoring of the read layer. With that out of the way we can move on to the eval layer. In [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>In the last part we did a pretty major refactoring of the read layer.  With that out of the way we can move on to the eval layer.  In this part we will implement define which has the syntax:</p>
<p>(define identifier value)</p>
<p>Since we have already implemented pairs we simply have to check if the expression is a pair in the eval layer and perform the appropriate action.</p>
<pre class="brush: python; highlight: [163,164,165,166]; title: ; notranslate">
&quot;&quot;&quot;
scheme.py
(c)2011 Nick Zarczynski
version 0.1
&quot;&quot;&quot;
import sys
from buffered_input import Buff

#############################################################################
## Data Types
#############################################################################

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

#############################################################################
## Environments
#############################################################################

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

#############################################################################
## Read
#############################################################################

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return (c == ' ' or c == '(' or c == ')' or c == '\&quot;'
          or c == ';' or c == '\n' or not c)

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return (c.isalpha() or c == '*' or c == '/' or c == '&gt;' or c == '&lt;'
          or c == '=' or c == '?' or c == '!' or c == '-' or c == '&amp;')

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  if '.' in buf:
    return float(''.join(buf))
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(''.join(buf))

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  &quot;&quot;&quot;Read a character literal including #\space and #\newline&quot;&quot;&quot;
  c = f.getc()
  if c == 's':
    if f.peek() == 'p':
      read_expected_string(f, &quot;pace&quot;)
      return ' '
    else:
      return 's'
  elif c == 'n':
    if f.peek() == 'e':
      read_expected_string(f, 'ewline')
      return '\n'
    else:
      return 'n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
  elif is_initial(c) or ((c == '+' or c == '-') and is_delimiter(f.peek())):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;not implemented (read)&quot;

#############################################################################
## Eval
#############################################################################

def self_evaluating(expr):
  t = type(expr)
  return (t is int or t is float or t is bool
          or t is str or expr == the_empty_list)

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == Pair:
    sym = expr.car
    if sym == 'define':
      global_environment[expr.cdr.car] = expr.cdr.cdr.car
      return None
  else:
    return &quot;not implemented (eval)&quot;

#############################################################################
## Print
#############################################################################

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  else:
    sys.stdout.write(str(expr))

#############################################################################
## REPL
#############################################################################

def repl():
  while 1:
    sys.stdout.write('&gt; ')
    scheme_print(scheme_eval(scheme_read(Buff(sys.stdin))))
    print

if __name__ == &quot;__main__&quot;:
  repl()
</pre>
<p>If an expression is a pair we check the value of the car and perform the appropriate action.  In this case we add an entry into the global_environment that maps the symbol &#8220;a&#8221; to the value 42.  We need to be sure to call scheme_eval on the value as it might be an expression such as (+ 40 2).</p>
<p>After we determine that this expression will be setting a variable we need to get that variable and evaluate the value.  Then we create a new entry in the global_environment (or modify an existing entry) with the evaluated value.</p>
<p>The next primitive we will implement is <em>if</em>, the syntax for which is (if predicate consequent alternate).  <em>if</em> has to be implemented as a special form because only one branch is evaluated based on the outcome of the predicate test.  So here are the steps that must be taken with <em>if</em>.</p>
<p>1) Evaluate the predicate<br />
2.a) If the predicate evaluates to true; evaluate the consequent branch<br />
2.b) If the predicate evaluates to false; evaluate the alternate branch<br />
3) Return the result of evaluating the appropriate expression.</p>
<p>Like <em>define</em> we will check the first value of the pair to see if the symbol is <em>if</em>.  We&#8217;ll implement this in a similar way to define for the moment.  In the next post we&#8217;ll look at a better way to do this kind of dispatching.</p>
<pre class="brush: python; highlight: [167,168,169,170,171,172]; title: ; notranslate">
&quot;&quot;&quot;
scheme.py
(c)2011 Nick Zarczynski
version 0.1
&quot;&quot;&quot;
import sys
from buffered_input import Buff

#############################################################################
## Data Types
#############################################################################

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

#############################################################################
## Environments
#############################################################################

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

#############################################################################
## Read
#############################################################################

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return (c == ' ' or c == '(' or c == ')' or c == '\&quot;'
          or c == ';' or c == '\n' or not c)

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return (c.isalpha() or c == '*' or c == '/' or c == '&gt;' or c == '&lt;'
          or c == '=' or c == '?' or c == '!' or c == '-' or c == '&amp;')

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  if '.' in buf:
    return float(''.join(buf))
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(''.join(buf))

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  &quot;&quot;&quot;Read a character literal including #\space and #\newline&quot;&quot;&quot;
  c = f.getc()
  if c == 's':
    if f.peek() == 'p':
      read_expected_string(f, &quot;pace&quot;)
      return ' '
    else:
      return 's'
  elif c == 'n':
    if f.peek() == 'e':
      read_expected_string(f, 'ewline')
      return '\n'
    else:
      return 'n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
  elif is_initial(c) or ((c == '+' or c == '-') and is_delimiter(f.peek())):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '\&quot;':
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;not implemented (read)&quot;

#############################################################################
## Eval
#############################################################################

def self_evaluating(expr):
  t = type(expr)
  return (t is int or t is float or t is bool
          or t is str or expr == the_empty_list)

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == Pair:
    sym = expr.car
    if sym == 'define':
      global_environment[expr.cdr.car] = scheme_eval(expr.cdr.cdr.car)
      return None
    elif sym == 'if':
      pred = scheme_eval(expr.cdr.car)
      if pred:
        return scheme_eval(expr.cdr.cdr.car)
      else:
        return scheme_eval(expr.cdr.cdr.cdr.car)
  else:
    return &quot;not implemented (eval)&quot;

#############################################################################
## Print
#############################################################################

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  else:
    sys.stdout.write(str(expr))

#############################################################################
## REPL
#############################################################################

def repl():
  while 1:
    sys.stdout.write('&gt; ')
    scheme_print(scheme_eval(scheme_read(Buff(sys.stdin))))
    print

if __name__ == &quot;__main__&quot;:
  repl()
</pre>
<pre class="brush: plain; title: ; notranslate">
(if 1 1 2)
;===&gt; 1
(if #f 1 2)
;===&gt; 2
</pre>
<p>The only value in Scheme that evaluates to false is the symbol #f all other Scheme values evaluate to true.  The test case above shows that this version of if works as expected.  We&#8217;re pretty limited for now on what we can test because we can&#8217;t yet define procedures or use much beyond self-evaluating values here.</p>
<p>There are a number of special forms that need to be implemented for Scheme.  You might be thinking that it will eventually become cumbersome to check all the values using if/elif/else.  We could break out the code for handling <em>if</em> and <em>define</em> into separate functions, but in the next part we&#8217;ll take a different approach to dispatching that is much easier to extend.</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Refactoring Read</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-refactoring-read</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 06:30:40 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1407</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. This article will describe some of the changes that have been made to the read layer of the Scheme in Python interpreter. The biggest conceptual change is that the [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>This article will describe some of the changes that have been made to the read layer of the Scheme in Python interpreter.</p>
<p>The biggest conceptual change is that the read layer no longer deals with strings.  Instead the read layer now processes streams of characters.  This change will not only simplify the implementation, it will also allow the read function to easily work on files as well.</p>
<p>The implementation of scheme_read is a port of the read function from <a href="http://michaux.ca/articles/scheme-from-scratch-introduction">Bootstrap Scheme by Peter Michaux</a>.  Peter&#8217;s implementation makes heavy use of the getc and ungetc functions in C.  Python does not support these functions and using them is more than a bit unpythonic.</p>
<p>Writing a parser by hand is probably the wrong way to go about this from the beginning.  However this is supposed to be a learning exercise and I think it aids in understanding the system from the bottom up.</p>
<p>This implementation depends on a class I wrote to do buffered input (the only way ungetc will work in Python).  This is found in the file buffered_input.py and you use it as follows:</p>
<pre class="brush: python; title: ; notranslate">
from buffered_input import Buff
f = Buff(file_like_object)

# To read a single character
c = f.getc()

# To peek at the next character without removing it from the buffer
c = f.peek()

# To place a character back on the buffer
f.ungetc(c)

# To remove leading whitespace
f.remove_whitespace()

# To read from stdin
import sys
f = Buff(sys.stdin)
</pre>
<p>And here&#8217;s the sourcecode that implements the Buff class.</p>
<pre class="brush: python; title: ; notranslate">
class Buff:
  def __init__(self, f):
    self.f = f
    self.last = []

  def getc(self):
    if self.last:
      return self.last.pop(0)
    else:
      return self.f.read(1)

  def ungetc(self, c):
    self.last.insert(0, c)

  def peek(self):
    if self.last:
      return self.last[0]
    else:
      c = self.f.read(1)
      self.last.append(c)
      return c

  def remove_comment(self):
    c = self.getc()
    while c and c != '\n':
      c = self.getc()
    self.ungetc(c)  

  def remove_whitespace(self):
    c = self.getc()
    while c:
      if c == ' ':
        c = self.getc()
      elif c == '\n':
        c = self.getc()
      elif c == ';':
        self.remove_comment()
      else:
        self.ungetc(c)
        break
</pre>
<p>Even though a lot of the code has changed, most of the concepts have not.  We still look at the first character in an expression to decide what to do with it.  Some of the code has not changed at all.  </p>
<p>Handling different types has been broken out into helper functions to keep the scheme_read function clean.  There are 5 main helper functions read_number, read_character, read_string, read_symbol and read_pair.  Each of the first 4 performs the same basic task.  First it reads from the input file, character by character, accumulating each character into a buffer until a delimiter is reached.  Then it joins the buffer and returns the correct type.  read_pair is implemented close to the same way it was in v0.04 except it now handles many more valid lists.</p>
<p>I also added a few helper functions such as is_delimiter, is_initial and self_evaluating to make the code easier to read and extend.  Finally I added some docstrings to functions which are not obvious and some block comments to visually separate sections of code.  Without further ado here&#8217;s the new code for scheme.py.</p>
<pre class="brush: python; title: ; notranslate">
import sys
from buffered_input import Buff

#############################################################################
## Data Types
#############################################################################

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

#############################################################################
## Environments
#############################################################################

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

#############################################################################
## Read
#############################################################################

def is_delimiter(c):
  &quot;&quot;&quot;Is c a valid expression delimiter?&quot;&quot;&quot;
  return (c == ' ' or c == '(' or c == ')' or c == '&quot;' or c == '&quot;'
          or c == ';' or c == '\n' or not c)

def is_initial(c):
  &quot;&quot;&quot;Is c a valid initial character for an identifier?&quot;&quot;&quot;
  return (c.isalpha() or c == '*' or c == '/' or c == '&gt;' or c == '&lt;'
          or c == '=' or c == '?' or c == '!' or c == '-' or c == '&amp;')

def read_number(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  if '.' in buf:
    return float(''.join(buf))
  elif '/' in buf:
    return &quot;rationals not implemented&quot;
  else:
    return int(''.join(buf))

def read_expected_string(f, s):
  &quot;&quot;&quot;Consume expected characters from the input buffer.&quot;&quot;&quot;
  expected_chars = list(s)
  c = f.getc()
  while expected_chars:
    if c == expected_chars[0]:
      expected_chars.pop(0)
      c = f.getc()
    else:
      return &quot;unexpected character&quot;

def read_character(f):
  &quot;&quot;&quot;Read a character literal including #\space and #\newline&quot;&quot;&quot;
  c = f.getc()
  if c == 's':
    if f.peek() == 'p':
      read_expected_string(f, &quot;pace&quot;)
      return ' '
    else:
      return 's'
  elif c == 'n':
    if f.peek() == 'e':
      read_expected_string(f, 'ewline')
      return '\n'
    else:
      return 'n'
  else:
    return c

def read_symbol(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  f.ungetc(c)
  return ''.join(buf)

def read_string(f):
  buf = []
  c = f.getc()
  while not is_delimiter(c):
    buf.append(c)
    c = f.getc()
  return ''.join(buf)

def read_pair(f):
  f.remove_whitespace()
  c = f.getc()
  if c == ')':
    return the_empty_list
  f.ungetc(c)
  car = scheme_read(f)
  f.remove_whitespace()
  cdr = read_pair(f)
  return Pair(car, cdr)

def scheme_read(f):
  f.remove_whitespace()
  c = f.getc()
  if (c.isdigit() or (c == '-' and f.peek().isdigit() or f.peek() == '.')
      or (c == '.' and f.peek().isdigit())):
    f.ungetc(c)
    return read_number(f)
  elif c == '#':
    c = f.getc()
    if c == 't':
      return True
    elif c == 'f':
      return False
    elif c == '\\':
      return read_character(f)
  elif is_initial(c) or ((c == '+' or c == '-') and is_delimiter(f.peek())):
    f.ungetc(c)
    return Symbol(read_symbol(f))
  elif c == '&quot;' or c == '&quot;': # single &quot; breaks wordpress highlighting
    return read_string(f)
  elif c == '(':
    return read_pair(f)
  else:
    return &quot;not implemented (read)&quot;

#############################################################################
## Eval
#############################################################################

def self_evaluating(expr):
  t = type(expr)
  return (t is int or t is float or t is bool
          or t is str or expr == the_empty_list)

def scheme_eval(expr):
  if self_evaluating(expr):
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == Pair:
    return expr
  else:
    return &quot;not implemented (eval)&quot;

#############################################################################
## Print
#############################################################################

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  else:
    sys.stdout.write(str(expr))

#############################################################################
## REPL
#############################################################################

def repl():
  while 1:
    sys.stdout.write('&gt; ')
    scheme_print(scheme_eval(scheme_read(Buff(sys.stdin))))
    print

if __name__ == &quot;__main__&quot;:
  repl()
</pre>
<p>* In lines 39 and 136 I had to repeat the &#8221; because a single &#8221; broke the wordpress highlighting.</p>
<p>In addition to those changes the scheme_test.py file also underwent some changes to accommodate the new buffered_input.</p>
<p>If you have any questions about the refactoring that I did not address, please post them in the comments here.  Though the implementation of the read layer has changed pretty drastically, the output has not changed at all.  Also, since the string type is so similar to the symbol type I added it in this version as well.</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Pairs and Lists</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-pairs-and-lists</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 01:00:08 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1376</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. This article will focus on implementing lists. Lists in Scheme are an extension of the pair type. A pair is a structure which contains 2 elements normally referred to [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>This article will focus on implementing lists.  Lists in Scheme are an extension of the pair type.</p>
<p>A pair is a structure which contains 2 elements normally referred to as the <strong>car</strong> and <strong>cdr</strong> in Scheme.  Lists are built on top of pairs where the car is some value and the cdr is another pair or the empty list.  In a <em>proper list</em> the cdr of the last pair must be the empty list.</p>
<p>To illustrate this concept a bit more clearly here is a diagram of a list in Scheme:</p>
<p><img src="http://docs.google.com/drawings/pub?id=1D5UHl9anYnTkiFgjCKYt14-MTUnCa4oXYiqGQkL6NpM&amp;w=354&amp;h=55"></p>
<p>This list is constructed out of 3 pairs.  The car of the first pair is the value 1 and the cdr is the second pair.  The car second pair has the value 2 and the cdr is the third pair.  The car of the third pair has the value 3 and the cdr contains the empty list (Nil in the diagram).</p>
<pre class="brush: python; title: ; notranslate">
class Pair:
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr
</pre>
<p>Above is the class definition for a very simple Pair object in Python.  We can construct the above list using the Pair class as follows:</p>
<pre class="brush: python; title: ; notranslate">
lst = Pair(1, Pair(2, Pair(3, None)))
</pre>
<p>This implementation of a list is called a linked list and you can find a more detailed description in my article <a href="http://nickzarr.com/blog4/2011/02/what-in-the-hell-are-linked-lists/" title="What In The Hell Are Linked Lists">WITH Linked Lists</a>.  Python does not have an implementation of a list in the core language, the list data type in Python is called an array in most other languages.</p>
<p>Scheme sourcecode is written using the list data type.  This is one of the most powerful features of the language as the sourcecode is just a regular Scheme data type.  This allows some really interesting features such as macros, but we won&#8217;t get into that just yet.</p>
<p>In Scheme sourcecode a pair is started by an open parenthesis and closed by a matching closing parenthesis.  Let&#8217;s take a look at an expression that defines the identifier number to be 42 and its internal representation.</p>
<pre class="brush: plain; title: ; notranslate">
(define number 42)
Pair(Symbol(&quot;define&quot;), Pair(Symbol(&quot;number&quot;), Pair(42, None)))
</pre>
<p>To start with we&#8217;ll implement the empty list.  Since this is a distinct object in Scheme we&#8217;ll make a new type called The_Empty_List and since we only need one empty list we&#8217;ll also make a global variable to refer to it called the_empty_list.</p>
<pre class="brush: python; highlight: [4,5,6,7,28,29,30,31,32,58,59,74,75]; title: ; notranslate">
class Symbol(str):
  pass

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def read_pair(s):
  if s[0] == ')':
    return the_empty_list
  else:
    return &quot;Pairs not implemented yet&quot;

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
    elif s[1] == '\\':
      if s == '#\space':
        return ' '
      elif s == r'#\newline':
        return '\n'
      else:
        return s[2]
  elif c.isalpha() or c in ('!', '-', '+', '*', '/', '@', '$'):
    return Symbol(s)
  elif c == '(':
    return read_pair(s[1:])
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  elif type(expr) == str:
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == The_Empty_List:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<p>As you can see when the first character of an expression is &#8220;(&#8221; read_pair is called with the remaining expression.  When it is the empty list, read_pair simply returns the_empty_list.  What happens when there is something else there?</p>
<p>To construct a list we need to evaluate the expressions within that list and build up a chain of Pairs.  To do that we make scheme_read and read_pair mutually recursive.  This means that we take the first expression up to a delimiter (we&#8217;ll only deal with spaces for now) and call scheme_read on it.  Then we assign the value that scheme_read returns to the car of a new Pair and call read_pair on the remaining expression, assigning the return value from that to the cdr of the new Pair.</p>
<pre class="brush: python; highlight: [1,6,7,8,9,36,39,40,41,42,86,87,92,93,94,95,96,97,98,99,100,102]; title: ; notranslate">
import sys

class Symbol(str):
  pass

class Pair(object):
  def __init__(self, car, cdr):
    self.car = car
    self.cdr = cdr

class The_Empty_List(object):
  def __repr__(self):
    return &quot;()&quot;
the_empty_list = The_Empty_List()

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def read_pair(s):
  s = s.lstrip()
  if s[0] == ')':
    return the_empty_list
  sp = s.split(' ', 1)
  car_obj = scheme_read(sp[0])
  cdr_obj = read_pair(sp[1])
  return Pair(car_obj, cdr_obj)

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
    elif s[1] == '\\':
      if s == '#\space':
        return ' '
      elif s == r'#\newline':
        return '\n'
      else:
        return s[2]
  elif c.isalpha() or c in ('!', '-', '+', '*', '/', '@', '$'):
    return Symbol(s)
  elif c == '(':
    return read_pair(s[1:])
  else:
    return &quot;not implemented (read)&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  elif type(expr) == str:
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  elif type(expr) == The_Empty_List:
    return expr
  elif type(expr) == Pair:
    return expr
  else:
    return &quot;not implemented (eval)&quot;

def scheme_print(expr):
  if type(expr) == Pair:
    sys.stdout.write('(')
    p = expr
    while p.cdr != the_empty_list:
      scheme_print(p.car)
      sys.stdout.write(' ')
      p = p.cdr
    scheme_print(p.car)
    sys.stdout.write(')')
  else:
    sys.stdout.write(str(expr))

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
    print
</pre>
<p>This version of read_pair and scheme_read is incredibly naive.  In fact it only works on a very limited subset of valid pairs.  The reason for this is the use of strings as arguments to read_pair and scheme_read.  For instance this version cannot read nested lists and it is also necessary to put a space before the closing &#8216;)&#8217;.  I included this version only to demonstrate the mutually recursive nature of read_pair and scheme_read in the simplest way I could think of.</p>
<p>We could continue to use strings as we were doing, but eventually this will get too complicated.  To fix this properly we need to treat the input expression as a stream of characters.  This is going to require a decent amount of refactoring to the read and read_pair functions.</p>
<p>I probably won&#8217;t go into detail with the changes made to scheme_read and read_pair.  The important part is that you understand that the purpose of the read function is to translate a series of characters into an abstract syntax tree (AST) of the appropriate data structures.  From this point on we will be focusing mainly on the evaluation of this AST.</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Symbols and Assignment</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-symbols-and-assignment</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 16:33:47 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1357</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. There are some self-evaluating values we didn&#8217;t implement in the last article. Vectors and hash tables are self-evaluating but were left out for simplicity. Strings have also been left [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>There are some self-evaluating values we didn&#8217;t implement in the last article.  Vectors and hash tables are self-evaluating but were left out for simplicity.  Strings have also been left out, though they are a pretty essential data type.  The reason for leaving them out is that embedded newlines are allowed in Scheme strings and the current implementation makes it difficult to handle this.</p>
<p>This post will focus on symbols (usually known as variables in other languages) and assignment.  For this we will need to start focusing on parts of the interpreter other than the reader.</p>
<p>According to R5RS a symbol (or identifier) is a sequence of letters, digits, and &#8220;extended alphabetic characters&#8221; that begins with a character but cannot begin with a number is an identifier.  To make things simple we will only allow (!, -, +, *, /, @, $) as valid initial characters for symbols.</p>
<p>We&#8217;ll start by identifying that an expression is a symbol in the reader and we&#8217;ll return the string representing the symbol.</p>
<pre class="brush: python; highlight: [34,35]; title: ; notranslate">
def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
    elif s[1] == '\\':
      if s == '#\space':
        return ' '
      elif s == r'#\newline':
        return '\n'
      else:
        return s[2]
  elif c.isalpha() or c in ('!', '-', '+', '*', '/', '@', '$'):
    return s
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  elif type(expr) == str:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<p>You may have noticed that we didn&#8217;t need to modify scheme_eval to allow symbols.  This is because both symbols and characters are represented by Python strings in this implementation.  This does not conform to the Scheme standard which requires strings and symbols to be distinct data types.</p>
<p>Since Python does not have a symbol type, or even a comparable type we can use as a substitute, we will have to make one.  To do this we&#8217;ll make a new class &#8220;Symbol&#8221; to represent symbols and modify eval to check for that.  Since we don&#8217;t need any additional functionality over a basic string the implementation is very simple.</p>
<pre class="brush: python; highlight: [1,2,38,51,52]; title: ; notranslate">
class Symbol(str):
  pass

def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
    elif s[1] == '\\':
      if s == '#\space':
        return ' '
      elif s == r'#\newline':
        return '\n'
      else:
        return s[2]
  elif c.isalpha() or c in ('!', '-', '+', '*', '/', '@', '$'):
    return Symbol(s)
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  elif type(expr) == str:
    return expr
  elif type(expr) == Symbol:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<p>Symbols are different from the other types we have implemented so far, they are the first type that is not self-evaluating.  To make symbols behave the way they should we have to introduce an environment that stores symbol names and their associated values, as well as modify eval to lookup those values.</p>
<p>We&#8217;ll start by creating a new global variable that will hold the environment, which will be called global_environment.  This will be a dictionary that holds (name, value) pairs.  We also need a function to lookup symbol names in that environment, which we&#8217;ll call lookup_symbol_value.  Since we don&#8217;t have any mechanism for adding new symbols to the global_environment yet, we&#8217;ll populate it with a few symbols to use for testing purposes.</p>
<pre class="brush: python; highlight: [4,5,6,7,8,9,10,60]; title: ; notranslate">
class Symbol(str):
  pass

global_environment = {&quot;hello&quot;:&quot;world&quot;, &quot;number&quot;:42}

def lookup_symbol_value(symbol):
  try:
    return global_environment[symbol]
  except KeyError:
    return &quot;symbol not found&quot;

def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
    elif s[1] == '\\':
      if s == '#\space':
        return ' '
      elif s == r'#\newline':
        return '\n'
      else:
        return s[2]
  elif c.isalpha() or c in ('!', '-', '+', '*', '/', '@', '$'):
    return Symbol(s)
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  elif type(expr) == str:
    return expr
  elif type(expr) == Symbol:
    return lookup_symbol_value(expr)
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<p>That will be all for this post.  Setting a symbol in Scheme uses the syntax: (define symbol value).  This requires that we have implemented lists, which we haven&#8217;t done yet.  The next article will most likely be about implementing lists so we can add this functionality.  </p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Self-Evaluating Values</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-self-evaluating-vals</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Sat, 20 Aug 2011 15:28:21 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1327</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. In this part we will implement a few more self-evaluating values, namely floating point numbers, booleans, and characters. To implement these we will mainly be modifying the read function. [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>In this part we will implement a few more self-evaluating values, namely floating point numbers, booleans, and characters.  To implement these we will mainly be modifying the read function.</p>
<p>In the previous post I mentioned that the logic behind recognizing integers was a bit too simple.  First in Scheme the &#8220;-&#8221; character is a legal character in identifiers (unlike most other languages).  For this reason we can&#8217;t assume that an expression that starts with a &#8220;-&#8221; is a number.  So if the first character is &#8220;-&#8221; we have to check that the second character is a digit.  But that&#8217;s still a bit too simple because -.3 is also a number.</p>
<p>After we identify that the expression is a number, all we have to do is figure out if it is a float or integer.  This is simple to achieve by testing if &#8220;.&#8221; is in the number.  The difficulty here comes in identifying the number in the first place.  Here are some numbers that we have to identify.</p>
<p>42<br />
-42<br />
.42<br />
42.<br />
-.42<br />
0.42<br />
-0.42<br />
4/2</p>
<p>To identify a number we&#8217;ll create a function is_number that takes an expression as a string and returns True if the expression is a number or False if it is not.  We&#8217;ll remove some of the logic from scheme_read and move it into the is_number function.  For now we won&#8217;t implement rational numbers (4/2) however we should recognize them and return &#8220;not implemented&#8221;.</p>
<p>Beyond that we only have to modify eval to recognize floats as well.  Since they&#8217;re also self-evaluating we only have to return the value the same as an integer.</p>
<pre class="brush: python; highlight: [0,1,2,3,4,5,6,7,8,9,10,15,16,17,18,19,20,21,28,29]; title: ; notranslate">
def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<p>There are some things that are not covered by this implementation, for instance the expression &#8220;-.&#8221; will cause the interpreter to crash.  This is caused by checking s[2] in line 7 without first verifying that this is a valid index (which, in the case of &#8220;-.&#8221; it isn&#8217;t).  This should signal a syntax error, however since this project is focused on simplicity and not robustness I&#8217;ll leave that as an exercise to the reader.</p>
<p>Also you will notice that I have left out test cases in this post.  Mostly this is because the number of tests are becoming quite large.  I have created another file which I called scheme_test.py where the tests for the interpreter are located.  Checkout the <a href="https://github.com/jacktrades/Scheme-in-Python/tree/v0.02">git repo</a> for the test suite as well as the full sourcecode for the interpreter.</p>
<h3>Booleans</h3>
<p>Booleans are relatively straightforward to implement.  The syntax for true and false is #t and #f respectively.  Like integers and floats, we&#8217;ll use Python&#8217;s native boolean type to represent booleans for now.</p>
<pre class="brush: python; highlight: [22,23,24,25,26,35,36]; title: ; notranslate">
def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<h3>Characters</h3>
<p>The syntax for characters is similar to booleans, characters start with #\ and are followed by, of all things, a character.  Since we&#8217;re already testing for the # character for booleans we can recognize characters in the same conditional.  </p>
<p>There are only a few things to note about characters in Scheme, for the most part characters are of the form #\x where x is any character a-Z or special characters.  However there are two special characters that we also need to recognize #\space and #\newline.  </p>
<p>The only thing left is to decide how to represent a character.  There are two obvious choices here, we could create a character type or we could just use strings.  Since Python does not have a separate character type we&#8217;ll go the easier route and use strings.</p>
<pre class="brush: python; highlight: [27,28,29,30,31,32,33,44,45]; title: ; notranslate">
def is_number(s):
  c = s[0]
  if c.isdigit():
    return True
  elif c == '.' and s[1].isdigit():
    return True
  elif c == '-' and (s[1].isdigit() or (s[1] == '.' and s[2].isdigit())):
    return True
  else:
    return False

def scheme_read(s):
  s.lstrip()
  c = s[0]
  if is_number(s):
    if '.' in s:
      return float(s)
    elif '/' in s:
      return &quot;not implemented&quot;
    else:
      return int(s)
  elif c == '#':
    if s[1] == 't':
      return True
    elif s[1] == 'f':
      return False
    elif s[1] == '\\':
      if s == '#\space':
        return ' '
      elif s == r'#\newline':
        return '\n'
      else:
        return s[2]
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  elif type(expr) == float:
    return expr
  elif type(expr) == bool:
    return expr
  elif type(expr) == str:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<p>Once again there are some problems with this implementation, mostly the same as before.  #\ will crash the interpreter, also #\spcae should produce a syntax error but instead gives &#8216;s&#8217;.</p>
<p>You have probably noticed by now that the hardest part of writing a parser is not recognizing valid expressions, but dealing with invalid ones.  Most of the work in writing a language is dealing with corner cases.</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">GOTO | Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scheme in Python &#124; Integers</title>
		<link>http://nickzarr.com/blog4/series/scheme-in-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-in-python-integers</link>
		<comments>http://nickzarr.com/blog4/series/scheme-in-python/#comments</comments>
		<pubDate>Sat, 20 Aug 2011 04:46:25 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1304</guid>
		<description><![CDATA[This series has been rewritten. It has been kept here because Google Reader will not let these posts die. Visit the new Scheme in Python series. Unlike Lispy in Scheme the first article of this series will cover only a language of integers. This is because we will have to implement quite a bit more [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This series has been rewritten.  It has been kept here because Google Reader will not let these posts die.  <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Visit the new Scheme in Python series</a>.</strong></p>
<p>Unlike <a href="http://nickzarr.com/blog4/series/lispy-in-scheme/" title="Lispy in Scheme">Lispy in Scheme</a> the first article of this series will cover only a language of integers.  This is because we will have to implement quite a bit more to get the same features.</p>
<p>There&#8217;s 4 layers to a basic Scheme referred to as the REPL.  REPL stands for Read, Evaluate, Print and Loop.  The REPL is more commonly referred to as an interpreter outside the Lisp community.</p>
<p>Most Scheme expressions are evaluated in the same way<a href="#foot_1">*</a>.  First we read the input from stdin or a source file and construct the appropriate data.  Then we evaluate the data to get a result and print that result to stdout.  Finally we loop and do it all again until the EOF is reached or there is no more input.</p>
<p>We&#8217;ll start by implementing each of these layers one-by-one for a language of integers.  This will allow us to understand the basic structure of the interpreter without complicating things too much.</p>
<p>We&#8217;ll start with the read layer, which we&#8217;ll call scheme_read to avoid any name clashes.  The purpose of the scheme_read function will be to analyze a string and return a representation of an integer.  One of the decisions we will have to make will be how to represent the integers.  There are two obvious choices here, we could make an integer object or we can use regular Python integers.  In this implementation we&#8217;ll use standard Python types wherever possible.</p>
<pre class="brush: python; title: ; notranslate">
def scheme_read(s):
  s.lstrip()
  c = s[0]
  if c == '-' or c.isdigit() and '.' not in s:
    return int(s)
  else:
    return &quot;not implemented&quot;
</pre>
<pre class="brush: python; gutter: false; title: ; notranslate">
scheme_read(&quot;42&quot;)
#===&gt; 42
scheme_read(&quot;-35&quot;)
#===&gt; -35
scheme_read(&quot;7.5&quot;)
#===&gt; &quot;not implemented&quot;
</pre>
<p>Let&#8217;s take a moment to break down the scheme_read function line by line.  </p>
<pre class="brush: python; first-line: 2; title: ; notranslate">
  s.lstrip()
</pre>
<p>The first thing we do is remove any whitespace on the left-hand side of the expression.  This makes the expression &#8221;  42&#8243; equivalent to the expression &#8220;42&#8243; as it should be since whitespace is only significant in Scheme as a delimiter.</p>
<pre class="brush: python; first-line: 3; title: ; notranslate">
  c = s[0]
</pre>
<p>Next we set a variable <strong>c</strong> to the first character in the string.  This is not strictly necessary but it makes the code a bit cleaner.</p>
<pre class="brush: python; first-line: 4; title: ; notranslate">
  if c == '-' or c.isdigit() and '.' not in s:
</pre>
<p>Then we use the first character to decide what type the expression is.  An integer can only start with &#8220;-&#8221; or a digit and cannot contain the &#8220;.&#8221; character.  This logic is actually a bit too simple, but for now it works as expected.</p>
<pre class="brush: python; first-line: 5; title: ; notranslate">
    return int(s)
</pre>
<p>After recognizing that the input is an integer we construct a representation of that integer in Python and return it.</p>
<pre class="brush: python; first-line: 6; title: ; notranslate">
  else:
    return &quot;not implemented&quot;
</pre>
<p>If the expression is not an integer we will simply return the string &#8220;not implemented&#8221; for now.  This is a very simplistic version of a syntax error and is good enough for now.</p>
<p>The read layer of our language of integers is now complete.  Next we&#8217;ll move on to the eval layer.</p>
<pre class="brush: python; highlight: [9,10,11,12,13]; title: ; notranslate">
def scheme_read(s):
  s.lstrip()
  c = s[0]
  if c == '-' or c.isdigit() and '.' not in s:
    return int(s)
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  else:
    return &quot;not implemented&quot;
</pre>
<pre class="brush: python; gutter: false; title: ; notranslate">
scheme_eval(scheme_read(&quot;42&quot;))
#===&gt; 42
scheme_eval(scheme_read(&quot;-35&quot;))
#===&gt; -35
scheme_eval(scheme_read(&quot;7.5&quot;))
#===&gt; &quot;not implemented&quot;
</pre>
<p>Integers are self-evaluating in Scheme, therefore all we need to do is return the expression if the expression is an integer and return &#8220;not implemented&#8221; if it is not.  At this point all eval does is echo the input back and I think it&#8217;s simple enough to warrant skipping the line-by-line explanation.</p>
<p>The print layer is next and since we&#8217;re using Python&#8217;s integer type to represent the integers it is even more simple than eval.  All we have to do is print the expression to the screen.</p>
<pre class="brush: python; highlight: [15,16]; title: ; notranslate">
def scheme_read(s):
  s.lstrip()
  c = s[0]
  if c == '-' or c.isdigit() and '.' not in s:
    return int(s)
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr
</pre>
<pre class="brush: python; gutter: false; title: ; notranslate">
scheme_print(scheme_eval(scheme_read(&quot;42&quot;)))
#===&gt; 42
scheme_print(scheme_eval(scheme_read(&quot;-35&quot;)))
#===&gt; -35
scheme_print(scheme_eval(scheme_read(&quot;7.5&quot;)))
#===&gt; not implemented
</pre>
<p>Technically both scheme_eval and scheme_print don&#8217;t really add anything to this interpreter.  However we will need them very soon and they form the basis for just about everything else, so it&#8217;s important to understand the layout of the interpreter now.</p>
<p>The only thing left for our extraordinarily simple interpreter is the loop layer.  You&#8217;ve already seen what it will do on each iteration in the scheme_print tests so I won&#8217;t delay any further.</p>
<pre class="brush: python; highlight: [18,19,20]; title: ; notranslate">
def scheme_read(s):
  s.lstrip()
  c = s[0]
  if c == '-' or c.isdigit() and '.' not in s:
    return int(s)
  else:
    return &quot;not implemented&quot;

def scheme_eval(expr):
  if type(expr) == int:
    return expr
  else:
    return &quot;not implemented&quot;

def scheme_print(expr):
  print expr

def repl():
  while 1:
    scheme_print(scheme_eval(scheme_read(raw_input(&quot;&gt; &quot;))))
</pre>
<pre class="brush: python; gutter: false; title: ; notranslate">
repl()
&gt; 42
42
&gt; -35
-35
&gt; 7.5
not implemented
</pre>
<p>With the REPL completed we have finished our language of integers.  In the next post we&#8217;ll continue expanding our language with other self-evaluating values by adding floats, characters and booleans.</p>
<p><a href="http://nickzarr.com/blog4/series/scheme-in-python/">GOTO | Table of Contents</a></p>
<p><a title="foot_1" name="foot_1">*</a> With the exception of macros, which I&#8217;ll hopefully get into later on in this series.  However the process for evaluating macros is very similar.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/series/scheme-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Branching, Merging and Other Useful Commands in Git</title>
		<link>http://nickzarr.com/blog4/2011/08/branching-merging-and-other-useful-commands-in-git/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=branching-merging-and-other-useful-commands-in-git</link>
		<comments>http://nickzarr.com/blog4/2011/08/branching-merging-and-other-useful-commands-in-git/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 11:26:25 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1289</guid>
		<description><![CDATA[I recently started a new series called Scheme in Python mainly to teach myself a bit about branching and merging in git. This post is simply a reference for some of the git commands I regularly use, as well as some explanation about branching and merging. I&#8217;ll start with some of the most basic git [...]]]></description>
			<content:encoded><![CDATA[<p>I recently started a new series called <a href="http://nickzarr.com/blog4/series/scheme-in-python/" title="Scheme in Python">Scheme in Python</a> mainly to teach myself a bit about branching and merging in git.  This post is simply a reference for some of the git commands I regularly use, as well as some explanation about branching and merging.</p>
<p>I&#8217;ll start with some of the most basic git commands for creating a repo, adding files and commiting changes to those files.</p>
<h3>Create a new repo</h3>
<p>To create a new repo, first create a new directory and name it whatever you like.  Then from the command line <em>cd</em> into that directory and use the following command.</p>
<pre class="brush: plain; title: ; notranslate">
$ git init
</pre>
<p>This will create a new repo in that directory.  If you already had files in that directory, the <em>git init</em> command will not automatically add those files to the repo.  To add a file use the <em>add</em> command.</p>
<h3>Add files to repo</h3>
<pre class="brush: plain; title: ; notranslate">
$ git add filename
</pre>
<p>Where <em>filename</em> is the name of the file you want to add.  However this is not enough to add the file to the repo, it simply stages the file to be added in the next commit.  To commit your changes to the repo you need to use the <em>commit</em> command.</p>
<h3>Commit changes</h3>
<pre class="brush: plain; title: ; notranslate">
$ git commit -a -m &quot;Type your commit message here&quot;
</pre>
<p>The <em>-m</em> option allows you to write a commit message that describes the changes you made.  If this option is not present the default editor will be opened for you to write a commit message, they are mandatory.  The <em>-a</em> tells git to commit all the changes from every file.  If you only want to commit changes from a specific file, you can specify that file instead of <em>-a</em>.</p>
<pre class="brush: plain; title: ; notranslate">
$ git commit filename -m &quot;Only changes in filename are committed.&quot;
</pre>
<h3>Push changes to remote repo</h3>
<p>So far all of the changes and commits have been done locally.  If you want to upload your changes to a server such as github you would use the <em>push</em> command.  However before you can do this you need to tell git where that remote repository is.  Your source code hosting site should give you instructions on how to do this.  Here&#8217;s an example of the command I needed to run to upload to github for Scheme in Python.</p>
<pre class="brush: plain; title: ; notranslate">
git remote add origin git@github.com:jacktrades/Scheme-in-Python.git
</pre>
<p>You will only need to do this once.  Afterward you can just use the <em>push</em> command.</p>
<pre class="brush: plain; title: ; notranslate">
$ git push -u origin master
</pre>
<p>This will upload the <em>master</em> branch to the server.  If you don&#8217;t do any branching <em>master</em> will be the only branch you have.</p>
<h3>Creating and changing branches</h3>
<p>Creating a new branch in git is simple, just use the <em>branch</em> command.</p>
<pre class="brush: plain; title: ; notranslate">
$ git branch v0.01
</pre>
<p>Here a new branch was created and named v0.01.  You could choose any name you want for the branch, though I&#8217;m not sure exactly what characters are allowed.</p>
<p>Even though the v0.01 branch was created, git does not automatically switch you into it.  To find out what branch you are in you can use the branch command without any other arguments.</p>
<pre class="brush: plain; title: ; notranslate">
$ git branch
* master
  v0.01
</pre>
<p>The branch name with the asterisk(*) next to it is the branch you are currently in.  To change to another branch use the <em>checkout</em> command.</p>
<pre class="brush: plain; title: ; notranslate">
$ git checkout v0.01
</pre>
<p>This changes the current branch to v0.01, to verify this you can use the branch command again.</p>
<pre class="brush: plain; title: ; notranslate">
$ git branch
  master
* v0.01
</pre>
<p>When you make changes and commit them you will be commiting to the current branch (in this instance the v0.01 branch).  If you make some changes, commit them then switch back to the master branch, you&#8217;ll find that the commits are not there.</p>
<h3>Pushing branches to a remote repo</h3>
<p>To upload the new branch to the server you need to tell the push command which branch you want to push.  So for the v0.01 branch you would need to do this.</p>
<pre class="brush: plain; title: ; notranslate">
$ git push origin v0.01
</pre>
<p>To push changes made in multiple branches you can leave off the branch at the end of the push command.  </p>
<blockquote><p><strong>git push origin</strong> will push all changes on the local branches that have matching remote branches at origin.<br />
- <a href="http://stackoverflow.com/questions/948354/git-push-current-branch">docgnome from stackoverflow</a></p></blockquote>
<h3>Merging</h3>
<p>To merge one branch into another first checkout the branch that you want to merge into.  For this example we&#8217;ll merge the v0.01 branch into master.  So first we checkout the master branch then do a merge command.</p>
<pre class="brush: plain; title: ; notranslate">
$ git checkout master
$ git merge v0.01
</pre>
<h3>Links</h3>
<p><a href="http://book.git-scm.com/3_basic_branching_and_merging.html">Git Book &#8211; Basic Branching and Merging</a></p>
<p><a href="http://stackoverflow.com/questions/161813/how-do-i-fix-merge-conflicts-in-git">StackOverflow &#8211; How do I fix merge conflicts in Git</a></p>
<p>&nbsp;</p>
<p>* That&#8217;s all for now, but I&#8217;ll come back and add commands for merging and how to resolve conflicts once I get the chance to use those features.  This page will likely be updated a number of times as I learn more about git.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/08/branching-merging-and-other-useful-commands-in-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Which programming language should I learn?</title>
		<link>http://nickzarr.com/blog4/2011/07/which-programming-language-should-i-learn/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=which-programming-language-should-i-learn</link>
		<comments>http://nickzarr.com/blog4/2011/07/which-programming-language-should-i-learn/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 16:44:09 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[learning programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=11</guid>
		<description><![CDATA[The most difficult choice for someone who is new to programming is what language to learn. You are in the worst position to choose for yourself because you don&#8217;t have enough knowledge yet to assess the pros and cons. If you ask people that do know, you will get tons of different responses. Most important [...]]]></description>
			<content:encoded><![CDATA[<p>The most difficult choice for someone who is new to programming is what language to learn.</p>
<p>You are in the worst position to choose for yourself because you don&#8217;t have enough knowledge yet to assess the pros and cons.</p>
<p>If you ask people that do know, you will get tons of different responses.</p>
<p><strong>Most important things:</strong></p>
<ul>
<li>There are enough learning materials.</li>
<li>The community is active and helpful to newcomers.</li>
<li>The language is difficult enough to challenge you, but easy enough not to discourage you.</li>
</ul>
<p><strong>Why it doesn&#8217;t matter:</strong></p>
<ul>
<li>Over the course of the next few years you will learn many languages (if you plan on being any good).</li>
<li>People say that if you pick an easy language (Python or Javascript) you will not learn the important concepts.  This can be true, but only if you stop learning a few months in.</li>
<li>You&#8217;re going to do it wrong in the beginning no matter what language you pick.</li>
<li>Read <a href="http://prog21.dadgum.com/51.html">How Did Things Ever Get This Good?</a> by James Hague.  The language you pick really doesn&#8217;t matter one bit.</li>
</ul>
<p>The most important thing when learning to program is staying motivated.  The easiest way to stay motivated is to work on projects that you think are cool and actually complete them.  If you pick a language that is too hard, you are likely to give up in frustration.  Nothing is stopping you from learning the harder languages after you pick up the basics of the easier ones.</p>
<h3>Pros and Cons of Specific Languages</h3>
<p>In order of best to worst languages to learn as your first IMHO.</p>
<p><strong><a href="http://wiki.python.org/moin/BeginnersGuide">Python</a></strong><br />
Pros: Beginner friendly, lots of community support for newbies, lots of libraries to get you going quickly<br />
Cons: If you don&#8217;t continually push yourself to learn, you can miss out on a lot of important computer science concepts that Python abstracts away for you.</p>
<p><strong><a href="http://stackoverflow.com/questions/646032/whats-the-best-javascript-tutorial">Javascript</a></strong><br />
Pros: Very easy to start with, lots of libraries and code in the wild for you to study.<br />
Cons: Community is full of non-programmers, you will pick up bad habits, </p>
<p><strong><a href="http://www.call-cc.org/">Scheme</a></strong><br />
Pros: Beautiful language, great books for intermediate level study<br />
Cons: Small community, not very beginner friendly, few books that start at the ultra-noob level.</p>
<p><strong><a href="http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list">C</a></strong><br />
Pros:  Will force you to learn all of the difficult concepts.<br />
Cons:  It will be hard.  There are many traps and pitfalls that await you.</p>
<p><strong>Java</strong><br />
Pros: Huge community and libraries<br />
Cons: A sizable portion of people who only know Java (<a href="http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html">The perils of Java schools</a>), forces you into a single way of thinking about programming.  I strongly recommend staying away from Java as a first language.</p>
<h3>More Tips</h3>
<p>You should spend about a year getting to know your first language.  After that you will want to start learning other languages.  In my opinion you can&#8217;t call yourself a programmer until you are at least familiar with 3 languages.  Meaning that you have written a small/medium sized program in each (~3,000 lines each).</p>
<p>But that&#8217;s not all.  Programming isn&#8217;t really about languages at all!  Programming is about being familiar with data structures, algorithms and other fundamental computer science concepts and how they apply to solving real problems.  In the end it&#8217;s all about experience, build applications and solve problems and eventually you will look back on what you have done and say, &#8220;Now I think I&#8217;m a programmer&#8221;.  </p>
<p>But wait!  That&#8217;s not all!  Next year you will look back on the year before and say, &#8220;I had absolutely no idea what I was doing last year.&#8221;  The year after you&#8217;ll say the same, and the year after that, and the year after that, and so on.  Learning to program is a never-ending process that will keep challenging you until you decide to hang up your hat.</p>
<p>Also read <a href="http://nickzarr.com/blog4/2011/03/tips-for-a-new-programmer/" title="Tips for a New Programmer">Tips for a New Programmer</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/07/which-programming-language-should-i-learn/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Classes and Instances in Javascript Using the Closure Method</title>
		<link>http://nickzarr.com/blog4/2011/07/classes-and-instances-in-javascript-using-the-closure-method/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=classes-and-instances-in-javascript-using-the-closure-method</link>
		<comments>http://nickzarr.com/blog4/2011/07/classes-and-instances-in-javascript-using-the-closure-method/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 13:15:07 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1236</guid>
		<description><![CDATA[I was reading a question about what every Javascript programmer should know on StackOverflow and found this useful pattern for using the more classic class/instance pattern instead of Javascript&#8217;s standard prototype method. I found the last example to be quite elegant and want to preserve it here for reference. With this pattern you have to [...]]]></description>
			<content:encoded><![CDATA[<p>I was reading a question about <a href="http://stackoverflow.com/questions/2628672/what-should-every-javascript-programmer-know/2629004#2629004">what every Javascript programmer should know</a> on StackOverflow and found this <a href="http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript/1598077#1598077">useful pattern for using the more classic class/instance pattern</a> instead of Javascript&#8217;s standard prototype method.  I found the last example to be quite elegant and want to preserve it here for reference.</p>
<pre class="brush: jscript; title: ; notranslate">
function Shape(x, y) {
    var self = {};

    self.x = x;
    self.y = y;

    self.toString = function() {
        return 'Shape at ' + self.x + ', ' + self.y;
    };

    return self;
}

function Circle(x, y, r) {
  var self = Shape(x, y);

  self.r = r;

  var _baseToString = self.toString;
  self.toString = function() {
    return 'Circular ' + _baseToString(self) + ' with radius ' + r;
  };

  return self;
};

var mycircle = Circle(2, 3, 5);
console.log(mycircle.x === 2);
console.log(mycircle.y === 3);
console.log(mycircle.r === 5);
console.log(mycircle.toString());
</pre>
<p>With this pattern you have to use the &#8216;self&#8217; variable (which you can name anything you wish, the original was named &#8216;that&#8217;) to access and modify attributes of the class just like in Python.  Unlike Python you must explicitly declare the self variable at the beginning of the class and return it at the end.  Also if you are going to override an attribute in the parent class, but still need to access the parent attribute, you must rename it before overriding it, otherwise the reference to self.toString will end up in an infinite recursive loop.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/07/classes-and-instances-in-javascript-using-the-closure-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting WordPress SyntaxHighlighter Evolved to Validate</title>
		<link>http://nickzarr.com/blog4/2011/06/getting-wordpress-syntaxhighlighter-evolved-to-validate/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-wordpress-syntaxhighlighter-evolved-to-validate</link>
		<comments>http://nickzarr.com/blog4/2011/06/getting-wordpress-syntaxhighlighter-evolved-to-validate/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 18:34:54 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1197</guid>
		<description><![CDATA[I&#8217;ve been using Alex Gorbatchev&#8217;s SyntaxHighlighter Evolved to post code to my blog since early this year. I&#8217;ve recently moved to self-hosting my blog and it was one of the first plugins I installed. I can&#8217;t say enough good things about it. It is a great plugin for simple syntax highlighting of anything from html [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using Alex Gorbatchev&#8217;s <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a> to post code to my blog since early this year.  I&#8217;ve recently moved to self-hosting my blog and it was one of the first plugins I installed.  I can&#8217;t say enough good things about it.  It is a great plugin for simple syntax highlighting of anything from html to C to Python (though unfortunately not Scheme, maybe I should write a brush for that).</p>
<p>When I ran my blog through the validator at <a href="http://validator.w3.org/">w3c</a> I noticed two problems.  The first was with the Page Links To plugin using target=&#8221;_blank&#8221;.  This was simple enough to fix, just uncheck the &#8220;Open this link in a new window&#8221; box.  It&#8217;s probably better to let your visitors choose where they want their links to open, after all they can always middle click to open in a new tab.</p>
<p>The second problem was with SyntaxHighlighter Evolved&#8217;s use of &lt;meta id=&#8221;syntaxhighlighteranchor&#8221; &#8230;&gt; in the head tag.  This is not valid html and was a bit harder to fix.  I came across <a href="http://wordpress.org/support/topic/plugin-syntaxhighlighter-evolved-html-validation-fails">this post explaining the problem and rational behind the design</a> while Googling for a solution.  It seems that the id tag was used to provide a method for users to customize the plugin without editing the source files.  Since I quite enjoy digging into the source files, this wasn&#8217;t a show stopper for me.  In the end my solution was simple.  Remove the <em>feature</em> and get on with my life.</p>
<p>The first thing to do is to locate this line&#8230;</p>
<pre class="brush: jscript; title: ; notranslate">
		echo '&lt;meta id=&quot;syntaxhighlighteranchor&quot; name=&quot;syntaxhighlighter-version&quot; content=&quot;' . esc_attr( $this-&gt;pluginver ) . '&quot; /&gt;' . &quot;\n&quot;;
</pre>
<p>and remove the id=&#8221;syntaxhighlighteranchor&#8221; tag.</p>
<p>The plugin uses document.getElementById(&#8220;syntaxhighlighteranchor&#8221;) twice so you have to make two changes.  Instead of using the .insertBefore method to inject the css into the head element, use the .appendChild method.</p>
<pre class="brush: jscript; title: ; notranslate">
		document.getElementsByTagName(&quot;head&quot;)[0].insertBefore( corecss, document.getElementById(&quot;syntaxhighlighteranchor&quot;) );
// becomes
		document.getElementsByTagName(&quot;head&quot;)[0].appendChild( corecss );
</pre>
<p>and</p>
<pre class="brush: jscript; title: ; notranslate">
		document.getElementsByTagName(&quot;head&quot;)[0].insertBefore( themecss, document.getElementById(&quot;syntaxhighlighteranchor&quot;) );
// becomes
		document.getElementsByTagName(&quot;head&quot;)[0].appendChild( themecss );
</pre>
<p>You might want to put a comment in the sourcecode describing your change so you know what you did in the future in case it breaks.  If you really think you&#8217;re going to forget, you can always write a blog post about it too.</p>
<p>Again I can&#8217;t say enough good things about <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a>.  If you have an idea for a fix for this that preserves the original feature of being able to customize the plugin through css without delving into the sourcecode, please leave it in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/06/getting-wordpress-syntaxhighlighter-evolved-to-validate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Drawing JSONP Data on the Canvas</title>
		<link>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-drawing-jsonp-data-on-the-canvas</link>
		<comments>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 06:57:38 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[charting]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1033</guid>
		<description><![CDATA[The last article in this series was a bit of a digression into the module pattern and namespaces in Javascript. This article will focus on a very simple charting algorithm. Now that we have the data to draw and know how to move things on the canvas, we need to focus on making the chart [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://nickzarr.com/blog4/2011/04/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/">last article</a> in this series was a bit of a digression into the module pattern and namespaces in Javascript.  This article will focus on a very simple charting algorithm.</p>
<p>Now that we have the data to draw and know how to move things on the canvas, we need to focus on making the chart look more like a normal chart.  This post will focus on the drawing algorithms that will turn our data into a nice display and redrawing that same chart at different time periods/scales.  Here&#8217;s the screenshot representing our progress from last time.</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_014.png" alt="No Modifications" /></p>
<p>The first step is to find out the lowest value that will have to be drawn on the chart.  We can align all the rest of the values with the bottom of the chart if we subtract the lowest value from each value on the chart.  To do this we first have to traverse the sequence of data that will be shown and look for the lowest value.</p>
<pre class="brush: jscript; highlight: [25,26,27,28,29,30,31,32,33,34,35,36]; title: ; wrap-lines: false; notranslate">
var width = 600, height = 500
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
chart.width = width; chart.height = height

//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//

function getUrl(symbol) {
  return &quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D&quot; + symbol + &quot;%26d%3D2%26e%3D27%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&amp;amp;format=json&amp;amp;callback=?&quot;;
}

$.getJSON(getUrl(&quot;ibm&quot;), init);

function init(result) {
  var data = result.query.results.row;
  drawRects(data, 1);
}

//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//

function drawRects(d, s) {
  var e = s + 30;
  var low = d[s].col3;

  for (var i = s; i &lt; e; i++) {
    if (d[i].col3 &lt; low) { low = d[i].col3 }
  }

  for (var i = s; i &lt; e; i++) {
    c.fillRect(i*30, height-(d[i].col1-low), 20, d[i].col1 - d[i].col4);
  }
}
</pre>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_015.png" alt="Align at Bottom" /></p>
<p>The next thing to do is scale up the bar heights to match the height of the chart.  For this we also have to determine the highest high.  Then we take the difference between the highest high and the lowest low and divide the chart height by that number, this gives us our multiple.  Then we take the multiple and use it to compute the lower starting position as well as the height of each bar.</p>
<p>Before we were using the open data, however this won&#8217;t always give the lowest price.  On any day the stock price fell, the open will represent the highest price.  We don&#8217;t have to compute if the open is lower or higher than the close because our data gives us the low and high prices for the day.  This is also beneficial as the low or high from the day could be significantly lower/higher than the open or close.</p>
<p>Also we&#8217;ve been drawing our chart backward, to flip it we need to subtract the offset from the width of the chart.  In addition we should put in some color to tell what days are up or down.  Since code is probably the best description of this formula I&#8217;ll stop trying to explain it and just show you the algorithm.  I&#8217;m sure there is a cleaner/simpler solution (or maybe this solution is even too simple) however this can be updated a bit later down the road.</p>
<pre class="brush: jscript; highlight: [31,35,38,40,41,42,43,44,45,46]; title: ; wrap-lines: false; notranslate">
var width = 600, height = 500
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
chart.width = width; chart.height = height

//chart.onclick = moveRects;

//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//

function getUrl(symbol) {
  return &quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D&quot; + symbol + &quot;%26d%3D2%26e%4D04%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&amp;amp;format=json&amp;amp;callback=?&quot;;
}

$.getJSON(getUrl(&quot;ibm&quot;), init);

function init(result) {
  var data = result.query.results.row;
  console.log(data[1].col0);
  drawRects(data, 1);
}

//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//

function drawRects(d, s) {
  var e = s + 15;
  var low = d[s].col3;
  var high = d[s].col2;

  for (var i = s; i &lt; e; i++) {
    if (d[i].col3 &lt; low) { low = d[i].col3 }
    if (d[i].col2 &gt; high) { high = d[i].col2 }
  }

  var mul = height / (high - low);

  for (var i = e; i &gt; s; i--) {
    if (d[i].col1 &lt; d[i].col4) { c.fillStyle = &quot;#00f&quot;; }
    else { c.fillStyle = &quot;#f00&quot;; }
    c.fillRect(width - (i*30),
               height - (mul * (d[i].col1-low)),
               20,
               (mul * (d[i].col1 - d[i].col4)));
  }
}
</pre>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_017.png" alt="Simple Chart" /></p>
<p>And here&#8217;s the Yahoo Finance chart as comparison&#8230;</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_018.png" alt="Yahoo Finance Chart" /></p>
<p>Finally here&#8217;s a snapshot of pyTrade, the father of JamochaTrade.  Something similar to this is the ultimate goal of JamochaTrade.</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_019.png" alt="pyTrade" /></p>
<p>As you can see our chart now looks a lot more like a stock chart!  However, we still have a long way to go.  Wicks, labeled axes, hover tags and much more need to be added, not to mention different styles of charts (line, mountain, dot, etc.).  There are also a few bugs with our current implementation that need to be worked out.</p>
<p>The next article will concentrate on refactoring and debugging.  Notably we&#8217;ll move our code into a namespace, as was discussed in the previous article.  We&#8217;ll also rip out the drawing logic and put it into a function so we can make a more general drawing procedure that can handle different types of bar charts (Candlestick, OHLC, HLC).</p>
<p><a href="http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/" title="Jumping into Javascript – Good news and bad news">GOTO Part 7 | Good news and bad news</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Namespaces, we should have more of these</title>
		<link>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-namespaces-we-should-have-more-of-these</link>
		<comments>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 20:52:31 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[module pattern]]></category>
		<category><![CDATA[namespaces]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1011</guid>
		<description><![CDATA[The last article dealt with cross-domain data retrieval. This article will be a short discussion about namespaces and the module pattern in Javascript. Here&#8217;s a snippet from the Zen of Python that I think should be included in some theoretical incantation of the Zen of Javascript: Namespaces are one honking great idea &#8212; let&#8217;s do [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://nickzarr.com/blog4/2011/03/27/jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery/">last article</a> dealt with cross-domain data retrieval.  This article will be a short discussion about namespaces and the module pattern in Javascript.</p>
<p>Here&#8217;s a snippet from the Zen of Python that I think should be included in some theoretical incantation of the Zen of Javascript:</p>
<blockquote><p>Namespaces are one honking great idea &#8212; let&#8217;s do more of those!</p></blockquote>
<p>Namespaces are an important concept in any programming language.  Programming without them is inevitably an exercise in tracking down hard-to-find bugs that occur when a definition is clobbered by an unrelated assignment.</p>
<p>Here&#8217;s the problem:  There is a single global namespace for all the scripts running in a page!</p>
<p>This means that defining: a = 42 in the file display.js will clobber the: a = 7 definition in database.js!  Let me restate that.  When you are creating global variables in a Javascript file, you must know about ALL the global variables created in ALL the other script files.</p>
<p>This may be possible for small apps that you write by yourself.  However for large apps and/or when multiple programmers are working on the same project, this is a nightmare.  Luckily there is a solution and it&#8217;s called the namespace pattern.</p>
<p>The namespace pattern is very similar to, but not quite the same as, the module pattern.  The module pattern is designed to allow private/public attributes of an object, which has benefits and drawbacks that are outside the scope of this article.</p>
<p>Links that describe these patterns can be found at the bottom of this page.  It is not within the scope of this series to describe all the aspects of the module pattern.  I will, however, give a short overview of the two approaches that I think are worthy of consideration.  The first is the module pattern and the second doesn&#8217;t have a name that I have found, so I&#8217;ll call it the Prototype Pattern.</p>
<p><strong>Module Pattern</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var MODULE = (function () {
  // all code here
  return {
    // return everything you want to be public
  }
}());
</pre>
<p><strong>Prototype Pattern</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var MODULE = {};
MODULE.variable = 42;
MODULE.fn = function (x) {return x*x};
</pre>
<p>With the module pattern you must declare everything you want to be public.  With the prototype approach you must prefix every attribute creation/access with the namespace.  I have read some articles that suggest that prototypes are more efficient than constructor functions.  I simply don&#8217;t know enough about Javascript at the moment to make that claim.  Please research this yourself if it is important to you, don&#8217;t take my word for it.</p>
<p>You may come across some &#8220;Module Pattern Considered Harmful&#8221; type articles when researching.  To save you some time here&#8217;s the argument: the module pattern is not a solution for every conceivable problem, therefore it should be avoided.  Some of these articles do raise valid use cases where the module pattern is not applicable, if you&#8217;re interested in that they are a good read.  Just don&#8217;t drink the kool-aid and believe that they are always useless/harmful.</p>
<p>Most of the issues with the module pattern revolve around private attributes.  I have spent most of my time programming in Python and Scheme and, in the general case, I haven&#8217;t had a need for private attributes.  However the real benefit of the module pattern (IMHO) is not private attributes, but avoiding the global namespace problem.  A problem for which the module pattern is an adequate solution.</p>
<p><a href="http://nickzarr.com/blog4/2011/04/05/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/">GOTO Part 6 &#8211; Drawing JSONP Data on the Canvas</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
<p>&nbsp;</p>
<h2>Links</h2>
<p><a href="http://www.youtube.com/watch?v=hQVTIJBZook">JavaScript: The Good Parts</a><br />
A Google Tech Talk given by Doug Crockford.  This talk is a great overview of the good and the bad of Javascript for experienced programmers.</p>
<p><a href="http://www.klauskomenda.com/code/javascript-programming-patterns/">Javascript Programming Patterns</a><br />
A good article that covers a number of methods of tackling the namespace problem.</p>
<p><a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">JavaScript Module Pattern: In-Depth</a><br />
More information about the module pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Koding in Kate</title>
		<link>http://nickzarr.com/blog4/2011/04/koding-in-kate/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=koding-in-kate</link>
		<comments>http://nickzarr.com/blog4/2011/04/koding-in-kate/#comments</comments>
		<pubDate>Sat, 02 Apr 2011 07:47:36 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[chicken scheme]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[text editor]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=993</guid>
		<description><![CDATA[I&#8217;ve recently been preparing to begin looking for my first programming job. As such I&#8217;ve been reading a number of &#8220;what employers are looking for&#8221; type posts. A while ago I read a comment that one interviewer asks candidates what IDE(ditor) they use and uses that information, along with some other things I consider just [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently been preparing to begin looking for my first programming job.  As such I&#8217;ve been reading a number of &#8220;what employers are looking for&#8221; type posts.  A while ago I read a comment that one interviewer asks candidates what IDE(ditor) they use and uses that information, along with some other things I consider just as trivial to judge candidates.  Remembering that post (I think it was in comments on a reddit submission, but I&#8217;m not sure) led me to write this one.</p>
<p><strong>I use Kate and I&#8217;m proud of it.</strong></p>
<p>Yes Kate, the KDE Advanced Text Editor.  Kate is more than a text editor but not quite an IDE, yet is very versatile.  From what I&#8217;ve read Kate is not used very much by developers, I personally love it and here&#8217;s a few reasons why&#8230;</p>
<h2>Kate works with just about anything I&#8217;ve thrown at it:</h2>
<p>I do a decent amount of Scheme development and Kate does a surprisingly good job at both highlighting and indenting Scheme.  Parenthesis are colored at all times and are highlighted as a matching set when the cursor is over them.  It is one of the few editors that I have used that not only works adequately well with Scheme but also has a modern interface and handles other languages very well.</p>
<p>I also do a lot of Python, and Kate has phenomenal support for that.  When I did projects in C, Javascript, HTML and even plain text files, Kate supported them well.  Kate might not be the best at any one thing, but since it&#8217;s usually close to the top, I don&#8217;t have to waste any time learning yet another editor/IDE just because I&#8217;m doing a project in a new language.  Even though it doesn&#8217;t take that long, I&#8217;d rather focus on developing (and writing blog posts about my editor).</p>
<h2>Sessions</h2>
<p>Kate has really good support for sessions.  You can choose to have your last session open automatically, or use a Kate launcher that lets you choose sessions.  Any files you open will be automatically saved to the current session (unless you&#8217;re using the anonymous session feature).  I rarely &#8220;use&#8221; sessions in Kate they just do their thing with little interference from me, except for the occasional &#8220;Sessions&#8221; -&gt; &#8220;Quick Open Session&#8221;.</p>
<h2>Tabs, Documents and the File Manager</h2>
<p>Managing the documents in your current session is both easy and customizable.  There is a toolbar on the left hand side that has both an open documents manager and a filesystem browser.  Both are easy and intuitive to use, but if that&#8217;s not enough there are extensions that offer tabs as well.  In fact there are two, an older extension &#8220;Tab Bar&#8221; and a newer and sleeker looking &#8220;Tabify&#8221;. </p>
<h2>Terminal and External Tools</h2>
<p>Most of the languages that I use have some sort of REPL.  In almost all these cases using the REPL from the command line is not only easy, but is &#8220;the way to do it&#8221;.  Kate offers an embedded terminal that allows quick testing of code snippets in a REPL<a href="http://bugs.kde.org/show_bug.cgi?id=157523">*</a>.  In addition the terminal can be set to auto-sync with the current document, which comes in handy in a number of situations.</p>
<p>With <a href="http://www.tuxmachines.org/node/13762">External Tools</a>, Kate can be set up to compile/execute your files just about any way you see fit.  External tools can be used for lots of other scripting tasks too, though I haven&#8217;t played with it much and can&#8217;t comment further.</p>
<h2>Find and Regular Expressions</h2>
<p>Kate has a pretty powerful search/replace feature including highlighting of all found terms.  It&#8217;s not just for the document you have open though, Kate can search through multiple files or the entire hard drive if you want.  You can also type your query as a regular expression giving you that much more power to find what you&#8217;re looking for.</p>
<h2>Code Folding, Bookmarking and Split Views</h2>
<p>Common IDE features such as code folding and bookmarking are also present in Kate.  You can also split the view pane of the editor, horizontally or vertically, allowing multiple documents to be viewed and edited at once.  </p>
<h2>Shortcuts and VI mode</h2>
<p>Just about every command in Kate can be set as a keyboard shortcut.  This makes things like the terminal plugin feel right at home.  In addition there is also a VI mode that provides Vi(m) like editing.  Though not 100% compatible with VI(m) commands, it is an interesting feature.  Unfortunately not one that I have any experience using yet, so you can check <a href="http://kate-editor.org/kate-vi-mode/">here</a> and <a href="http://hamberg.no/erlend/2011/01/19/visual-block-mode-for-kate%E2%80%99s-vi-mode/">here</a> for more info.</p>
<h2>Word/Code Completion and Auto-Braces</h2>
<p>One of the things I really like in Kate is word completion.  It&#8217;s a bit different from the code completion that is commonly found in IDEs.  The word completion in Kate is based off other words that are present in the file.  This means that you won&#8217;t be able to do someObject.met and see all the attributes/methods of that object that start with &#8220;met&#8221;.  However you can use auto-completion when you&#8217;re writing anything from C to Scheme to HTML to README files.  </p>
<h2>Code Tools</h2>
<p>Kate also comes with a number of tools for working with code.  A comment/uncomment command that works with just about any language and style of comment.  Indent/Dedent, support for Unix, Windows and Mac newlines and tons of character encodings, word wrap and spell checking are available and that just barely scratches the surface.</p>
<h2>Plugins, Extensions and Scripting</h2>
<p>Over 20 plugins and extensions are available (some for KatePart and some for Kate) that add more functionality.  Plus you can write <a href="http://milianw.de/blog/spotlight-kate-scripting">KatePart scripts</a> <a href="http://docs.kde.org/stable/en/kdesdk/kate/advanced-editing-tools-scripting.html">in JavaScript</a> that can add tons of features or just implement a quick hack to get things done.</p>
<p>&nbsp;</p>
<p><strong>There are many good things that coding in Kate brings.<br />
These are but a few of my favorite things!</strong></p>
<p>&nbsp;</p>
<h2>Links</h2>
<p><a href="http://kate-editor.org/">The Kate Editor Homepage</a></p>
<p><a href="http://maketecheasier.com/using-kate-as-a-web-editor/2009/11/09">Using Kate As a Web Editor</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/04/koding-in-kate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

