<?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; Scheme</title>
	<atom:link href="http://nickzarr.com/blog4/category/programming-2/scheme/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>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 Macros, syntax-rules, Explicit Renaming and Links to More Insanity</title>
		<link>http://nickzarr.com/blog4/2011/03/scheme-macros-syntax-rules-explicit-renaming-and-links-to-more-insanity/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scheme-macros-syntax-rules-explicit-renaming-and-links-to-more-insanity</link>
		<comments>http://nickzarr.com/blog4/2011/03/scheme-macros-syntax-rules-explicit-renaming-and-links-to-more-insanity/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 05:44:31 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[chicken scheme]]></category>
		<category><![CDATA[explicit renaming]]></category>
		<category><![CDATA[macros]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[syntax-rules]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=968</guid>
		<description><![CDATA[This is a response to a question on Yahoo Answers about macros in Scheme. Apparently this was too long for YA, so I decided to post it here. Eventually I&#8217;ll rewrite this and make it more coherent, for now please bear with me. Note that there may be some errors here so please point them [...]]]></description>
			<content:encoded><![CDATA[<p>This is a response to a question on Yahoo Answers about macros in Scheme.  Apparently this was too long for YA, so I decided to post it here.  Eventually I&#8217;ll rewrite this and make it more coherent, for now please bear with me.  Note that there may be some errors here so please point them out if you find them.  I am not an expert macrologist </p>
<p>Here&#8217;s the <a href="http://answers.yahoo.com/question/index?qid=20110327140756AA1XBnb">original question</a>&#8230;</p>
<blockquote><p>I&#8217;m new to scheme/racket macros and here is a simplified version of the problem I&#8217;m having:</p>
<p>> (define-syntax let-five<br />
(syntax-rules ()<br />
[(let-five expr ...)<br />
(let ((five 5)) expr ...)]))<br />
> (let-five (+ five 2))</p>
<p>This should return 7 but instead I get an error saying that the identifier &#8220;five&#8221; is unbound.<br />
All I want let-five to do is to bind the identifier &#8220;five&#8221; to the number 5 so that I can use &#8220;five&#8221; within let-five. The reason I want to do this is more complicated than this example so don&#8217;t tell me that this macro is doesn&#8217;t do anything useful.<br />
I am fairly sure that I know what is wrong, but my question is what would be the correct way to write this code so that it does what I intend?<br />
Additional Details<br />
Jack Trades, I don&#8217;t understand what x, r, and c are and what the % and @ are. It would be nice if you could explain that.</p></blockquote>
<p>And here&#8217;s my response&#8230;</p>
<p>I don&#8217;t use Racket, but Chicken gives the same error (but probably a different error message).</p>
<p>The problem here is that syntax-rules is a hygienic macro transformer.  Which basically means that the symbol five is being renamed by syntax-rules to avoid name clashes during expansion.  You can see this clearly by looking at the error message (like I said they&#8217;re probably different from yours)&#8230;</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
    &lt;syntax&gt;          (##core#let ((five119 5)) (+ five 2))
</pre>
<p>As you can see syntax-rules renames five to five119 (or something completely different).  So when you try to use five it is unbound.</p>
<p>In Chicken I would use explicit renaming macros which preserve hygiene but allow you to break it where necessary.  I&#8217;m not sure if Racket has this option (check into an implementation of syntax-case, that will allow you to do something similar).</p>
<pre class="brush: plain; title: ; notranslate">
(define-syntax (let-five x r c)
  (let ((%let (r 'let)))
    `(,%let ((five 5)) ,@(cdr x))))

(let-five (+ five 2))
;===&gt; 7
</pre>
<p>***** EDIT *****</p>
<p>As I already said I don&#8217;t think Racket has explicit renaming macros so this probably won&#8217;t work for you in that case.  You need to look into an implementation of syntax-case for Racket.  This will provide you with the ability to do what you want.  To the best of my knowledge this is not possible with syntax-rules.</p>
<p>That being said here&#8217;s the explanation you asked for&#8230;</p>
<p>x, r and c are parameter names the same as if you defined a function (lambda (x r c) &#8230;).  </p>
<p>The x parameter is the expression, which would be (let-five (+ five 2)) in your example.</p>
<p>The r parameter is a renaming procedure.  This is the &#8220;explicit renaming&#8221; part of the explicit renaming macro.  To maintain hygiene you must use this procedure to rename every symbol that you use (except for the ones you don&#8217;t want renamed).  You do this by calling (r &#8216;let) for example.</p>
<p>The c parameter is a comparison function that can compare renamed symbols for equality.</p>
<p>You do not provide any of those parameters.  Rather the implementation of ER macros does that for you.  All you need to do is provide a function that accepts 3 parameters.  Another equivalent way to write the ER macro above would be this&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
(define-syntax let-five
  (lambda (expression rename compare)
    (let ((%let (r 'let)))
      `(,%let ((five 5)) ,@(cdr x))))
</pre>
<p>The % sign is just an ordinary character no different from the #l #e or #t.  The reason I use that is to remind the reader that &#8220;%let&#8221; is the renamed symbol &#8220;let&#8221;.  You could use (renamed-let (r &#8216;let)) if you want instead of (%let (r &#8216;let)).</p>
<p>The @ is the syntax for unquote-splicing.  If you look at the last line in the ER macro above you&#8217;ll notice three forms of symbols (` , @).</p>
<p>` the backquote is syntax for (quasiquote (expression)).  quasiquote is similar to the regular quote, except that instead of simply returning the whole expression unevaluated, it allows you to evaluate some things using the (,) syntax.</p>
<p>, the comma is syntax for (unquote expression) this tells Scheme to evaluate the expression that immediately follows it.  So if we had the list `(1 (+ 1 1) ,(+ 1 2)) when it is evaluated it would return the list (1 (+ 1 1) 3).  The expression (+ 1 1) was not evaluated because it was never unquoted, however the expression (+ 1 2) was unquoted and so it was evaluated and returned 3.</p>
<p>@ is syntax for splicing which is a way to evaluate an expression that returns a list and then put that list into the quasiquoted list.  In other words it weaves a list into the quasiquoted list.</p>
<p>Here is some more information on Scheme macro systems.  I read each of these articles at least a dozen times and eventually it started to come together.  Even now though, I&#8217;d say that I only really understand about 10-20% of it.</p>
<p>Scheme macros are difficult to understand, but coming to that understanding (even if it is limited) is incredibly rewarding.  It will definitely make you a better Scheme programmer and will probably help you to realize why the vast majority of other languages are simply inadequate.</p>
<p>This is the easiest read and the highest level overview.<br />
<a href="http://blog.willdonnelly.net/2008/09/04/a-scheme-syntax-rules-primer/">A Scheme Syntax Rules Primer</a></p>
<p>This is probably the most complete approach to macros from the relatively simple to the complex.  Read this until you don&#8217;t understand what it&#8217;s talking about, then play around with some of the things you learned.  Then read it again from the beginning until you don&#8217;t know what it&#8217;s talking about, then play around.  Then read it again&#8230;  Eventually you&#8217;ll make it at least half way through and by then you&#8217;ll know more about macros than you ever thought possible.<br />
<a href="http://www.xs4all.nl/~hipster/lib/scheme/gauche/define-syntax-primer.txt">define-syntax Primer</a></p>
<p>Here&#8217;s an interesting (and long) post on Chicken&#8217;s macro system.  This covers ER macros.<br />
<a href="http://lists.gnu.org/archive/html/chicken-users/2008-04/msg00013.html">Macro Systems and Chicken (long)</a></p>
<p>And finally here&#8217;s an advanced discussion of macros that may just leave you without hair.<br />
<a href="http://groups.google.com/group/comp.lang.scheme/msg/eb6cc6e11775b619">An Advanced Syntax-Rules Primer for the Mildly Insane</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/03/scheme-macros-syntax-rules-explicit-renaming-and-links-to-more-insanity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Evo: The Original Purpose of Lispy</title>
		<link>http://nickzarr.com/blog4/2011/03/introducing-evo-the-original-purpose-of-lispy/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introducing-evo-the-original-purpose-of-lispy</link>
		<comments>http://nickzarr.com/blog4/2011/03/introducing-evo-the-original-purpose-of-lispy/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 22:36:38 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Lispy]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[artificial intelligence]]></category>
		<category><![CDATA[evolutionary programming]]></category>
		<category><![CDATA[genetic programming]]></category>
		<category><![CDATA[Language Design]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=880</guid>
		<description><![CDATA[When I first envisioned the Lispy project I had only one goal in mind, which I&#8217;ll get to soon. As I started writing code, first in Scheme, then C then again in Scheme, the Lispy project evolved into something else. It changed into a platform for me to learn more about programming and the implementation [...]]]></description>
			<content:encoded><![CDATA[<p>When I first envisioned the Lispy project I had only one goal in mind, which I&#8217;ll get to soon.  As I started writing code, first in Scheme, then C then again in Scheme, the Lispy project evolved into something else.  It changed into a platform for me to learn more about programming and the implementation of language features.  Writing Lispy, in all its variations, has been a very educational and rewarding experience, so much so that I consider the project an overwhelming success, even though I didn&#8217;t realize the original purpose.</p>
<p>So what was the original purpose of Lispy?  I&#8217;ll give you the tag line that I wrote when Lispy was nothing but an idea&#8230;  <strong>Lispy is a distributed self-optimizing program by example language</strong>.</p>
<p>What does that mean?  When I first became interested in programming I had 2 goals; to create a program like MetaStock (I&#8217;ve since written <a href="https://github.com/jacktrades/pyTrade">pyTrade</a>) and to create Artificial Intelligence.  Modest goals, I know.  In my AI research I came across genetic programming and immediately took a liking to it, probably because I was still new to writing code and the idea that I could write code that wrote code fascinated me.</p>
<p>The main problem with genetic programming is that it is often difficult to write fitness tests for your problems.  Somewhere along the way I noticed that programmers were writing fitness tests all the time in the form of unit tests for their code.  In addition, the fact that 99% of the time the CPU sits idle while we browse reddit, kept rattling around in my head.  Why not take advantage of those wasted cycles by using a programming language that used those cycles to optimize the code you just wrote?</p>
<p>Then I had another idea.  Why write code at all?  Why not just write the unit tests and let the code evolve on its own?  It took me about an hour to realize that this wasn&#8217;t going to work on anything but the smallest applications.  However another few weeks and I realized that, maybe it could work, given enough computers were running Lispy.</p>
<p>Anyway I have about 25 half-finished papers on Evo which I might get around to finishing and posting here.  I&#8217;ll give the highlights and post a link to the github account where you can find more info.  Evo is meant to be integrated with Lispy (though I don&#8217;t know when I&#8217;ll get around to that).</p>
<p>Evo is an evolutionary search based function optimizer.  It provides an interface for defining new modules and functions as well as an evolutionary programming based method for optimizing those functions.  Evo does not use the standard generational approach to GP, rather it uses &#8220;gene pools&#8221;, that contain functions of indefinite life, from which new functions can be evolved and tested one at a time.</p>
<p>When defining an Evo function you can choose to optimize it for speed, space or code length.  Each function can have multiple gene pools that are each optimized for a different purpose.  Using gene pools instead of a single population generational approach helps to avoid stagnation within the population as is a common occurrence with the standard generational model.</p>
<p>Evo is very much unfinished, however it can successfully run on its own and evolve solutions to problems.  Because of this I am going to put the code out there in case anyone wishes to contribute.  I used the implementation of Evo as an excuse to firm up my understanding of closures, as a result the majority of the program is written in a slightly OOP fashion.  There is also a Tk based GUI for browsing modules and adding new functions and fitness tests, though its use is completely optional.</p>
<p>Without further ado, <a href="https://github.com/jacktrades/Evo">here&#8217;s the link to the Evo repo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/03/introducing-evo-the-original-purpose-of-lispy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Chicken Scheme Documentation, Reference and Resources</title>
		<link>http://nickzarr.com/blog4/2011/02/chicken-scheme-documentation-reference-and-resources/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=chicken-scheme-documentation-reference-and-resources</link>
		<comments>http://nickzarr.com/blog4/2011/02/chicken-scheme-documentation-reference-and-resources/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 04:21:42 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Chicken]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=37</guid>
		<description><![CDATA[This page contains links to Chicken Scheme documentation and resources. &#160; Command Line or REPL chicken-doc Explore Chicken documentation from the command line or in the REPL grep The documentation for Chicken is bundled with the source.  You may use a tool such as grep to search these files. &#160; Online Chicken User’s Manual The [...]]]></description>
			<content:encoded><![CDATA[<p>This page contains links to Chicken Scheme documentation and resources.</p>
<p>&nbsp;</p>
<h2>Command Line or REPL</h2>
<p><a href="http://3e8.org/chickadee/chicken-doc">chicken-doc</a><br />
Explore Chicken documentation from the command line or in the REPL</p>
<p><a href="http://www.panix.com/%7Eelflord/unix/grep.html">grep</a><br />
The documentation for Chicken is bundled with the source.  You may use a tool such as grep to search these files.</p>
<p>&nbsp;</p>
<h2>Online</h2>
<p><a href="http://wiki.call-cc.org/man/4/The%20User%27s%20Manual">Chicken User’s Manual</a><br />
The “Official Chicken User’s Manual”.  Hosted on the Chicken Wiki.</p>
<p><a href="http://api.call-cc.org">Chickadee</a><br />
Search Chicken documentation by keyword or function name.</p>
<p><a href="http://wiki.call-cc.org/chicken-projects/egg-index-4.html">Egg Index</a><br />
A list of eggs available for Chicken.  Many have documentation available when you click on their name.</p>
<p><a href="http://paste.call-cc.org/">Paste</a><br />
The Chicken paste service provides a method of sharing code snippets.</p>
<p><a href="http://bugs.call-cc.org/">Chicken Trac</a><br />
Bug tracker for Chicken, also has a source code browser.</p>
<p>&nbsp;</p>
<h2>Mailing Lists and Forums</h2>
<p><a href="http://lists.nongnu.org/mailman/listinfo/chicken-users">chicken-users Mailing List</a><br />
<a href="http://lists.nongnu.org/archive/html/chicken-users/">chicken-users Archive</a><br />
Mailing list for users of Chicken.</p>
<p><a href="http://lists.nongnu.org/mailman/listinfo/chicken-hackers">chicken-hackers Mailing List</a><br />
<a href="http://lists.nongnu.org/archive/html/chicken-hackers/">chicken-hackers Archive</a><br />
Mailing list for developers working on Chicken itself.</p>
<p>&nbsp;</p>
<h2>Chat</h2>
<p><a href="">IRC on Freenode:  Channel #Chicken</a><br />
Chicken’s chat channel</p>
<p>&nbsp;</p>
<h2>Blogs</h2>
<p><a href="http://4.flowsnake.org/">Drinkable Chicken</a><br />
Though  not focusing as much on Chicken anymore, Drinkable Chicken is host to a  bunch of great articles for someone new to Scheme.  Many of the  articles compare Chicken to Python code snippets.</p>
<p><a href="http://schemely.blogspot.com/">Schemely Blog</a><br />
A few articles about Chicken and Scheme in general.</p>
<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=251474">The Adventures of a Pythonista in Schemeland</a><br />
A good series for an introduction to Scheme from a Python background.</p>
<p>&nbsp;</p>
<h2>Chicken for Blub Programmers</h2>
<h3>Python</h3>
<p><a href="http://plr.sourceforge.net/">Pointless Programming Language Reference</a><br />
Pointless Programming&#8217;s language comparison database has comparisons between many languages including Chicken Scheme.</p>
<p><a href="http://4.flowsnake.org/">Drinkable Chicken</a><br />
Though  not focusing as much on Chicken anymore, Drinkable Chicken is host to a  bunch of great articles for someone new to Scheme.  Many of the  articles compare Chicken to Python code snippets.</p>
<p><a href="http://wiki.call-cc.org/chicken-for-python-programmers">Chicken Wiki &#8211; Chicken-for-Python-Programmers</a><br />
A quick overview of common operations and their solutions in Python and Chicken.</p>
<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=251474">The Adventures of a Pythonista in Schemeland</a><br />
A good series for an introduction to Scheme from a Python background.</p>
<p>&nbsp;</p>
<h3>Other Languages</h3>
<p><a href="http://wiki.call-cc.org/chicken-for-ruby-programmers">Chicken Wiki &#8211; Chicken-for-Ruby-Programmers</a><br />
A through overview of the concepts behind Scheme from the prospective of a Ruby programmer.</p>
<p><a href="http://wiki.call-cc.org/language-comparison">Chicken Wiki &#8211; Chicken-for-C-Programmers</a><br />
A very brief overview of Chicken and the equivalent programs in C.</p>
<p><a href="http://wiki.call-cc.org/chicken-for-php-programmers">Chicken Wiki &#8211; Chicken-for-PHP-Programmers</a><br />
A very brief overview of Chicken and the equivalent programs in PHP.</p>
<p>&nbsp;</p>
<h2>Online Chicken Source Browsing</h2>
<p><a href="http://code.call-cc.org/">Chicken Source Code</a><br />
This page provides links to releases, repos and news.</p>
<p><a href="http://code.call-cc.org/cgi-bin/gitweb.cgi?p=chicken-core.git;a=tree">Chicken core git repository</a><br />
Access and browse Chicken source online.</p>
<p><a href="http://code.call-cc.org/svn/chicken-eggs/release/4/">Egg Subversion Repository</a><br />
Access and browse Egg sources online.  This link goes directly to eggs compatible with Chicken version 4.x or higher.</p>
<p><a href="http://bugs.call-cc.org/">Chicken Trac</a><br />
Bug tracker for Chicken, also has a source code browser.</p>
<p>&nbsp;</p>
<h2>General Scheme Documentation</h2>
<p><a href="http://srfi.schemers.org/">SRFIs</a><br />
A  list of SRFIs (Scheme Request For Implementation) and their  documentation.  Chicken makes use of a number of these, however you  should check other Chicken-based sources first as they may be  implemented differently.</p>
<p><a href="http://www-mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs</a><br />
SICP is the canonical book on computer science.  It can be a difficult read depending upon your experience, but this book will teach you a lot about Scheme and computer science in general.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/02/chicken-scheme-documentation-reference-and-resources/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MIT 6.001 Structure and Interpretation of Computer Programs Videos</title>
		<link>http://nickzarr.com/blog4/2011/02/with-linked-lists/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=with-linked-lists</link>
		<comments>http://nickzarr.com/blog4/2011/02/with-linked-lists/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 04:08:42 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Computer Science]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=27</guid>
		<description><![CDATA[MIT 6.001 Structure and Interpretation of Computer Programs videos on YouTube.  Here&#8217;s a playlist of all 20 videos. And you can read the whole book online here.]]></description>
			<content:encoded><![CDATA[<p>MIT 6.001 Structure and Interpretation of Computer Programs videos on YouTube.  Here&#8217;s a <a href="http://www.youtube.com/view_play_list?p=B9F897E1FF93D409">playlist of all 20 videos</a>.</p>
<p>And you can read the whole book online <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-4.html#%_toc_start">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/02/with-linked-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

