<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Coding Ninja</title>
	<atom:link href="http://codingninja.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://codingninja.wordpress.com</link>
	<description></description>
	<lastBuildDate>Wed, 16 Nov 2011 07:16:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='codingninja.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Coding Ninja</title>
		<link>http://codingninja.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://codingninja.wordpress.com/osd.xml" title="Coding Ninja" />
	<atom:link rel='hub' href='http://codingninja.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Scheme in Scheme Part 4 &#8211; The Virtual Machine</title>
		<link>http://codingninja.wordpress.com/2011/04/09/scheme-in-scheme-part-4-the-virtual-machine/</link>
		<comments>http://codingninja.wordpress.com/2011/04/09/scheme-in-scheme-part-4-the-virtual-machine/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 19:45:04 +0000</pubDate>
		<dc:creator>Kris Healy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Scheme in Scheme]]></category>

		<guid isPermaLink="false">http://codingninja.wordpress.com/?p=250</guid>
		<description><![CDATA[This is Part 4 of Scheme In Scheme.  Part 1, Part 2 or Part 3 are also good reads. The next task I set out to complete for Scheme in Scheme was implement lambda.  I can&#8217;t really say that I got that far.  After wrestling with it for a while I realized that I didn&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=250&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>This is Part 4 of Scheme In Scheme.  <a title="Simple Scheme Part 1 – Introduction" href="http://codingninja.wordpress.com/2011/02/19/simple-scheme-part-1-introduction/">Part 1</a>, <a href="https://codingninja.wordpress.com/2011/02/26/scheme-in-scheme-part-2-simple-defines/">Part 2</a> or <a href="https://codingninja.wordpress.com/2011/03/19/scheme-in-scheme-part-3-arithmetic/">Part 3</a> are also good reads.</em></p>
<p>The next task I set out to complete for Scheme in Scheme was implement lambda.  I can&#8217;t really say that I got that far.  After wrestling with it for a while I realized that I didn&#8217;t have a good foundation and therefore implementing lambda was going to be difficult.  I had a quasi-virtual machine at that point.  I decided it would be better to convert the the current code into a more fully featured virtual machine instead of trying to retrofit lambda in what was there.  This update can really be split into two pieces &#8212; the execution of byte code and the compiler.</p>
<h2>Byte Code</h2>
<p>I&#8217;ve invented a byte code format for my project.  The virtual machine will execute the byte code in the order it&#8217;s given to it.  Here are some byte code examples:</p>
<p><pre class="brush: plain; highlight: [2,4,6,8];">
#;6&gt; (compile-form '(+ 1 2))
((push 1) (push 2) (add))
#;7&gt; (compile-form '(/ 5 x))
((push 5) (get x) (div))
#;8&gt; (compile-form '(+ 1 2 (- 5 3) (* 2 50)))
((push 1) (push 2) (add) (push 5) (push 3) (sub) (add) (push 2) (push 50) (mul) (add))
#;9&gt; (compile-form '(define x 3))
((push 3) (define x))
</pre></p>
<p>The function <tt>compile-form</tt> takes in a list and transforms it into a list of instructions.  The very simple list <tt>(+ 1 2)</tt> translates into <tt>((push 1) (push 2) (add))</tt>.   Since this is a stack machine the <tt>add</tt> instruction will pop two arguments off the stack, add them, and push them back onto the stack.  All of the arithmetic operations have implicit parameters which are pushed onto the stack.  A lot more logic has been transferred into the compilation step for arithmetic.</p>
<p><pre class="brush: plain; first-line: 87;">
(define (instruction/arithmetic env op)
 (let* ((num2   (env/pop! env))
        (num1   (env/pop! env))
        (result (case op
                  [(add) (+ num1 num2)]
                  [(sub) (- num1 num2)]
                  [(mul) (* num1 num2)]
                  [(div) (/ num1 num2)])))
  (env/push! env result))
 env)
</pre></p>
<p>All the instructions are pretty simple.  Push objects onto the stack, call the instruction, and then pop off the result.  There are only three instructions currently that take an argument: <tt>push</tt>, <tt>get</tt>, and <tt>define</tt>.  The <tt>get</tt> instruction pulls a value from a binding in the environment.  So if <tt>x</tt> was previously bound to 3 via <tt>(define x 3)</tt> then the byte code <tt>(get x)</tt> would push 3 onto the stack.  The <tt>define</tt> instruction operates in the same way except it pops the top off the stack and binds that object to it&#8217;s argument.  <tt>(define x 3)</tt> will produce <tt>((push 3) (define x))</tt> which binds <tt>x</tt> to 3.</p>
<h2>Compiling</h2>
<p>Here is the bulk of the code for the compiler:</p>
<p><pre class="brush: plain; first-line: 11;">
(define (compile-arg arg)
 (if (self-evaluating? arg)
     `((push ,arg))
     (if (symbol? arg)
         `((get ,arg))
         (compile-form arg))))

;; Compiles the pushes for arithemtic args.  This will, at most, push two
;; arguments onto the stack.  If arguments are lacking, depending on the
;; op, this will push an null-operator (0 for add, 1 for mul).
(define (compile-arithmetic op args)
 (case (length args)
   [(0) `((push ,(default-arithmetic-val op))
          (push ,(default-arithmetic-val op))
          (,op))]
   [(1) `(,@(compile-arg (car args))
          (push ,(default-arithmetic-val op))
          (,op))]
   [(2) `(,@(compile-arg (car args))
          ,@(compile-arg (cadr args))
          (,op))]
 [else (append (compile-arithmetic op (take args 2))
               (append-map (lambda (x) `(,@(compile-arg x) (,op)))
                           (drop args 2)))]))

(define (compile-define binding args)
 (if (symbol? binding)
     ; If the binding is a symbol there should only be one other element
     ; in the list (define binding arg)
     `(,@(compile-arg (car args)) (define ,binding))))

;; Takes in a Scheme form for input and returns a list of instructions.
(define (compile-form input)
  (let ((form-name (car input))
        (args      (cdr input)))
    (case form-name
       [(+) (compile-arithmetic 'add args)]
       [(-) (compile-arithmetic 'sub args)]
       [(*) (compile-arithmetic 'mul args)]
       [(/) (compile-arithmetic 'div args)]
       [(define) (compile-define (car args) (cdr args))]
       [else (list (car input))])))
</pre></p>
<p>The first thing to look at is <tt>compile-form</tt>.  This function is the main entry point into the compiler.  It destructures the list by pulling out the operation (<tt>form-name</tt> in the code) being performed and the arguments passed to the operation.  It then calls into specific compilation routines based on the operation.</p>
<p>Most of the compilation at this point just deals with a lot of list manipulation.  A list goes into to <tt>compile-form</tt> and a list comes out.  Each element in the output list is an instruction.  Instruction themselves are lists.  Usually the instructions are only one element long but those that take parameters are two elements long.</p>
<p>The most interesting function in the compiler is probably the arithmetic compiler.  If I open up a scheme interpreter and type <tt>(+)</tt> it gives me <tt>0</tt>.  <tt>(+ 1)</tt> gives me <tt>1</tt>.  I had to special case the zero, one and two argument cases because of this.  All of the arithmetic instructions will pop two objects off the stack and operate on them.  The simple way of handling this is to always generate dummy pushes for missing arguments.  Zero arguments generates two pushes with a default value (for add it&#8217;s 0).  One argument pushes a dummy argument and the parameter argument.  Two arguments just push the two parameters onto the stack.</p>
<p><pre class="brush: plain;">
#;2&gt; (compile-form '(+))
((push 0) (push 0) (add))
#;3&gt; (compile-form '(+ 1))
((push 1) (push 0) (add))
#;4&gt; (compile-form '(+ 1 2))
((push 1) (push 2) (add))
</pre></p>
<p>When dealing with 3 or more arguments the compiler will create byte code with two pushes, the arithmetic instruction and then interleaving pushes and instructions.</p>
<p><pre class="brush: plain;">
#;1&gt; (compile-form '(- 5 2 3))
((push 5) (push 2) (sub) (push 3) (sub))
#;2&gt; (compile-form '(- 5 2 3 4 1 2 3 5))
((push 5) (push 2) (sub) (push 3) (sub) (push 4) (sub) (push 1) (sub) (push 2) (sub) (push 3) (sub) (push 5) (sub))
</pre></p>
<p>The last little bit is the <tt>compile-arg</tt> function.  It is used to evaluate arguments that are not self-evaluation (simple).  This recursive compilation allows for nested lists.  If I pass the compiler <tt>(+ 5 2 (- 3 2))</tt> it will properly generate code to subtract and then add all the numbers up.</p>
<p><pre class="brush: plain;">
#;1&gt; (compile-form '(+ 5 2 (- 3 2)))
((push 5) (push 2) (add) (push 3) (push 2) (sub) (add))
#;2&gt; (repl)
-: (+ 5 2 (- 3 2))
8
-: quit
quit
</pre></p>
<p>As always, you can see the code for this part of Scheme In Scheme on my Git Hub account at <a href="https://github.com/healyk/Scheme-in-Scheme/tree/Part.4">Part 4</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codingninja.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codingninja.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codingninja.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codingninja.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codingninja.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codingninja.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codingninja.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codingninja.wordpress.com/250/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=250&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codingninja.wordpress.com/2011/04/09/scheme-in-scheme-part-4-the-virtual-machine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cbf2750b09fac1abb6721658070732a1?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">Kris</media:title>
		</media:content>
	</item>
		<item>
		<title>Scheme In Scheme Part 3 &#8211; Arithmetic</title>
		<link>http://codingninja.wordpress.com/2011/03/19/scheme-in-scheme-part-3-arithmetic/</link>
		<comments>http://codingninja.wordpress.com/2011/03/19/scheme-in-scheme-part-3-arithmetic/#comments</comments>
		<pubDate>Sat, 19 Mar 2011 21:13:19 +0000</pubDate>
		<dc:creator>Kris Healy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Scheme in Scheme]]></category>

		<guid isPermaLink="false">http://codingninja.wordpress.com/?p=181</guid>
		<description><![CDATA[This is Part 3 of Scheme In Scheme.  Part 1 can be found here.  The previous article is Part 2. I&#8217;ve been trying to figure out what part of Scheme to implementation next.  Most things that looks simple are actually complex.  I also want to choose forms that will give me a minimal Scheme.  Many [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=181&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>This is Part 3 of Scheme In Scheme.  <a href="https://codingninja.wordpress.com/2011/02/19/simple-scheme-part-1-introduction/">Part 1</a> can be found here.  The previous article is <a href="https://codingninja.wordpress.com/2011/02/26/scheme-in-scheme-part-2-simple-defines/">Part 2</a>.</em></p>
<p>I&#8217;ve been trying to figure out what part of Scheme to implementation next.  Most things that looks simple are actually complex.  I also want to choose forms that will give me a minimal Scheme.  Many things in the language can be written using a combination of other forms.  Looking at the <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29#Minimalism">Wikipedia article on Scheme</a> the following things are required to get the minimum Scheme:</p>
<ol>
<li>define</li>
<li>lambda</li>
<li>if</li>
<li>quote, unquote, unquote-splicing, quasiquote</li>
<li>define-syntax, let-syntax, letrec-syntax, syntax-rules (or another macro system)</li>
<li>set!</li>
</ol>
<p>Define has already been covered.  <tt>lambda</tt> seems like a good choice because it will give me a lot more of the language than some of the other forms.  I can write things like <tt>let</tt> using <tt>lambda</tt>.  Implementing <tt>lambda</tt> will also let me dive into implementing a virtual machine.</p>
<p>Scheme In Scheme is going to use a <a href="http://en.wikipedia.org/wiki/Stack_machine">stack based virtual machine</a>.  A stack based virtual machine is a natural fit for Scheme since it&#8217;s a functional language.  There are multiple pros and cons of using this type of virtual machine over other types.  I&#8217;m using a stack machine because it fits the problem well and will make implementation easier.</p>
<p>I&#8217;m going to start with execution of arithmetic forms.  This will allow me to work the code up to full <tt>lambda</tt> support by breaking the problem up into smaller pieces and building upon the solutions for those pieces.  For my virtual machine I want to turn this:</p>
<p><pre class="brush: plain;">
(+ 1 2)
</pre></p>
<p>into this:</p>
<p><pre class="brush: plain;">
(push 1)
(push 2)
(add)
(pop)
</pre></p>
<p>This will push the 1 and the 2 onto the stack where they can now be added by <tt>(+)</tt>.  The implied behavior of <tt>add</tt> is that it will pop the numbers off the stack, add them, and push the result back on the stack.  In scheme executing an add form will add all numbers following the <tt>+</tt>.  Scheme in Scheme, for now, I&#8217;ll only be dealing with executing two numbers.  Here is the actual code.</p>
<p><pre class="brush: plain; first-line: 20;">
(define (exec-form input env)
 (for-each (lambda (x) (exec-instruction! env 'push (vm-eval x env)))
           (cdr input))
 (exec-instruction! env (car input))
 (exec-instruction! env 'pop))
</pre></p>
<p>All arguments are pushed onto the stack through a push operation in a <tt>for-each</tt>.  Afterwards the instruction is executed and the result is popped off the environment stack and returned from <tt>exec-form</tt>.  There could have been a direct translation from the addition form to the individual instructions but at this point an intermediate byte code doesn&#8217;t really get us much.  I will keep it simple for now.</p>
<p>There is one important piece here that escaped me at first: each argument in the input list passed to <tt>vm-eval</tt> before it is pushed onto the stack.  This allows us to evaluate sub-lists within an expression.  I don&#8217;t know if this will be a good long term solution but it works for now.</p>
<p>Note that the second line just grabs the first element of the list and executes it using <tt>exec-instruction!</tt>.  This makes implementing all arithmetic operations easier.  <tt>exec-instruction!</tt> is just a big switch statement to execute arbitrary functions linked to a symbol.</p>
<p><pre class="brush: plain; first-line: 17;">
(define (exec-instruction! env instruction . arg)
 (case instruction
   [(+)    (instruction/arithmetic env instruction)]
   [(-)    (instruction/arithmetic env instruction)]
   [(*)    (instruction/arithmetic env instruction)]
   [(/)    (instruction/arithmetic env instruction)]
   [(push) (instruction/push env (car arg))]
   [(pop)  (instruction/pop env)]
   [else 'error]))
</pre></p>
<p>There are probably is a more dynamic way of doing this.  For now this works out really well and it&#8217;s easy to tell what is considered a native operation and what isn&#8217;t.  I don&#8217;t expect this to grow extremely large in the future since there are only a few more operations that will be added.</p>
<p>vm-eval had to be modified as well to execute arbitrary instructions.  Here is the new code.</p>
<p><pre class="brush: plain; first-line: 35; highlight: [49,50,51];">
(define (vm-eval input env)
 (cond
   ; Semi-hack used to exit the repl
   [(and (symbol? input)
         (equal? input 'quit)) (values 'quit env)]
   [(self-evaulating? input) (values input env)]
   [(symbol? input)  (values (env/get-def env input) env)]

   ; Process define forms
   [(and (list? input)
         (define-form? input))
    (define-form input env)]

   ; Process execution of lists
   [(and (list? input)
         (instruction? (car input)))
    (values (exec-form input env) env)]
   [else 'error]))
</pre></p>
<p>Here is a test run of the arithmetic:</p>
<pre>#;1&gt; (repl)
-: (+ 1 2)
3
-: (- 4 3)
1
-: (* 5 (+ 1 2))
15
-: (define a 5)
(define a 5)
-: (define x 3)
(define x 3)
-: (/ a x)
1.66666666666667
-: quit
quit</pre>
<h2>Additional Resources</h2>
<p>I&#8217;ve had a few people tell me that this project has been useful to them.  Here are some additional resources that might be useful if you plan on implementing your own interpreter.</p>
<ol>
<li><a href="http://pointlessprogramming.wordpress.com/lispy-in-scheme/">Lispy in Scheme</a> &#8211; Another project to implement a Lisp-like language in Scheme.</li>
<li><a href="http://michaux.ca/articles/scheme-from-scratch-introduction">Scheme From Scratch</a> &#8211; Series of articles on writing a Scheme interpreter in C.</li>
<li><a href="http://www.lua.org/download.html">Lua Source Code</a> &#8211; Lua isn&#8217;t Scheme, but the Lua VM is small and clean.  Poking around this code gave me a lot of insight into how virtual machines operate.</li>
<li><a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29#Minimalism">Wikipedia Article on Scheme</a> &#8211; This link specifically goes to the part of the article about Scheme minimalism.  It&#8217;s useful because it outlines exactly what you need to implement a standard Scheme.  It&#8217;s pretty amazing that so little needs to be implemented to get so much.</li>
</ol>
<p>As always, you can see the code for this part of Scheme In Scheme on my Git Hub account at <a href="https://github.com/healyk/Scheme-in-Scheme/tree/Part.3">Part 3</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codingninja.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codingninja.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codingninja.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codingninja.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codingninja.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codingninja.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codingninja.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codingninja.wordpress.com/181/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=181&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codingninja.wordpress.com/2011/03/19/scheme-in-scheme-part-3-arithmetic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cbf2750b09fac1abb6721658070732a1?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">Kris</media:title>
		</media:content>
	</item>
		<item>
		<title>Tic Tac Toe as Hello World</title>
		<link>http://codingninja.wordpress.com/2011/03/13/tic-tac-toe-as-hello-world/</link>
		<comments>http://codingninja.wordpress.com/2011/03/13/tic-tac-toe-as-hello-world/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 22:18:27 +0000</pubDate>
		<dc:creator>Kris Healy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://codingninja.wordpress.com/?p=170</guid>
		<description><![CDATA[I&#8217;ve started to write Tic Tac Toe games in new languages when I&#8217;m learning them.  I&#8217;ll still write the classic &#8220;Hello, World!&#8221; program just to get something running on my system.  &#8220;Hello, World&#8221; is more of a sanity check to see if I have files in the right place and the compiler works.  Tic Tac [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=170&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve started to write Tic Tac Toe games in new languages when I&#8217;m learning them.  I&#8217;ll still write the classic &#8220;Hello, World!&#8221; program just to get something running on my system.  &#8220;Hello, World&#8221; is more of a sanity check to see if I have files in the right place and the compiler works.  Tic Tac Toe is complex enough that I&#8217;ll actually learn something about the language when writing it.</p>
<h2>Simple yet Complex</h2>
<p>Tic Tac Toe is extremely simple.  Everyone knows how to play it.  This makes it an ideal candidate when learning a new language.  It&#8217;s simple enough that it can be implemented in a weekend.  It doesn&#8217;t require many complex libraries since text output and input is sufficient to play the game.</p>
<p>The game is open ended enough that it can be written in a way that allows someone to learn specific aspects of a language.  Want to build server-ware with the language?  Write a client-server based Tic Tac Toe game.  The goal is to build GUI applications?  Implement the game with GUI elements and graphics.</p>
<h2>Requires both Behavior and State</h2>
<p>Tic Tac Toe is good because it involves non-trivial state and behavior.  At any given point in the game, you have to track the state of the board.  This seems simple but because it involves 2 dimensional space it&#8217;s complex enough that more complex data structures can be used.  A dictionary that maps positions to pieces; a multi-dimensional array; or just a list of position and piece pairs are all different ways the board state can be modeled.</p>
<p>The behavior is simple enough to be easily written but complex enough to require more than one if statement.  Try thinking about checking a Tic Tac Toe board for a win.  It can be a horizontal or a vertical win.  But it can also be a diagonal win.  There are games where there is no win but the board is full.  All of these conditions must be considered after each piece placement.</p>
<h2>Beyond Tic Tac Toe</h2>
<p>Got a simple Tic Tac Toe but want to add more features?  Want something harder to tackle?</p>
<p>In college for a Java project I had to write a 4x4x4 Tic Tac Toe game.  It&#8217;s a 3 dimensional board with 4 squares in each dimension (for a total of 64 squares).  It plays just like standard Tic Tac Toe but 4 in a row is required to win.  Now there are multiple diagonals and more complex rules.  Regular Tic Tac Toe doesn&#8217;t get beyond a simple AI whereas 4x4x4 requires much more complexity.</p>
<p>If that&#8217;s too much you can always just increase the number of squares in the 2 dimensional space.  Use a 4&#215;4 or 5&#215;5 game board instead.  Let the player enter an arbitrary number of squares.</p>
<p>Here are some additional ideas.</p>
<ol>
<li>Add an Undo/Redo</li>
<li>Allow the player to pick different difficulties.</li>
<li>Keep score of the Wins, Loses and Ties.</li>
<li>Allow the player to pick different pieces for their moves.</li>
<li>Allow saving and loading games.</li>
<li>2 player mode.</li>
</ol>
<p>I used this technique when learning Android programming.  If you want to see an example of Tic Tac Toe you can look at the <a href="https://github.com/healyk/TicTacToeAndroid">Tic Tac Toe in my GitHub account</a>.  Note that it isn&#8217;t the best code in the world!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codingninja.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codingninja.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codingninja.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codingninja.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codingninja.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codingninja.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codingninja.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codingninja.wordpress.com/170/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=170&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codingninja.wordpress.com/2011/03/13/tic-tac-toe-as-hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cbf2750b09fac1abb6721658070732a1?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">Kris</media:title>
		</media:content>
	</item>
		<item>
		<title>Scheme In Scheme Part 2 &#8211; Simple defines</title>
		<link>http://codingninja.wordpress.com/2011/02/26/scheme-in-scheme-part-2-simple-defines/</link>
		<comments>http://codingninja.wordpress.com/2011/02/26/scheme-in-scheme-part-2-simple-defines/#comments</comments>
		<pubDate>Sat, 26 Feb 2011 18:02:54 +0000</pubDate>
		<dc:creator>Kris Healy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Scheme in Scheme]]></category>

		<guid isPermaLink="false">http://codingninja.wordpress.com/?p=117</guid>
		<description><![CDATA[This is Part 2 of Scheme In Scheme.  Go back to Part 1 if you haven&#8217;t read it yet. Since we have a nice repl at our disposal we can start focusing on defining an environment using the define form.  There is two different ways of calling define: The first define form simply binds a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=117&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>This is Part 2 of Scheme In Scheme.  Go back to <a title="Simple Scheme Part 1 – Introduction" href="http://codingninja.wordpress.com/2011/02/19/simple-scheme-part-1-introduction/">Part 1</a> if you haven&#8217;t read it yet.</em></p>
<p>Since we have a nice repl at our disposal we can start focusing on defining an environment using the define form.  There is two different ways of calling define:</p>
<p><pre class="brush: plain;">
(define symbol-name value...)
(define (symbol-name params...) values)
</pre></p>
<p>The first define form simply binds a symbol to evaluate to a value.  The second define form binds a lambda to a symbol, so you can do the standard function call.  I&#8217;m just going to tackle the first define form for now; it&#8217;s a lot more involved than it looks.</p>
<h2>Scheme Environment</h2>
<p>To have defines in an environment we must first create an environment.</p>
<p><pre class="brush: plain; first-line: 16;">
(define (make-env)
 '((defs ((placeholder 123)))))
</pre></p>
<p>The environment right now is just a list of defines.  This list consists of only a place holder right now.  The place holder allows us to remove a lot of code that would usually be required to special case <tt>defs</tt> being keyed to an empty list.  Since eventually top level bindings such as arithmetic operations (+, -, /, *) and list manipulation (<tt>car</tt>, <tt>cons</tt>, <tt>cdr</tt>, &#8230;) will exist in a newly created environment this is normal.</p>
<p>Now that we have the environment, we need some ways to manipulate the environment.  Specially, we need functions to get a define from the environment and add a define to the environment.</p>
<p><pre class="brush: plain; first-line: 19;">
;; Adds a new symbol to the environment with the given form.
(define (env-add-def env symbol form)
 (replace env 'defs
          (append
           (cdr (assq 'defs env))
           (list (list symbol form)))))

;; Gets the define for symbol in environment env
(define (env-get-def env symbol)
 (let ((form (assq symbol (cadr (assq 'defs env)))))
   (if form
       (cadr form)
       'error)))
</pre></p>
<p>All these do is use a liberal amount of <tt>assq</tt>&#8216;s to treat the environment like a dictionary.  The symbol <tt>defs</tt> gets us a dictionary of the defines within the environment.  Each entry in that dictionary uses the symbol name as the dictionary key and the form or evaluated value as the dictionary value.</p>
<p>I&#8217;m using the symbol <tt>error</tt> to signify undefined values.  This is a little messy right now but it works for the time being.  Refactoring will come later.</p>
<h2>Repl Evolution</h2>
<p>The repl has to be changed to accommodate the new environment.  Specifically, we need to keep the state around from call to call.  Since we&#8217;re treating the environment as an immutable data structure we&#8217;ll have to capture outputs of <tt>vm-eval</tt>.</p>
<p><pre class="brush: plain; first-line: 58; highlight: [61,63,64];">
(define (repl)
 (define (repl-inner env)
   (display prompt)
   (let-values (((result new-env) (vm-eval (read-input) env)))
     (print-obj result)
     (repl-inner new-env)))
 (repl-inner (make-env)))
</pre></p>
<p>Now <tt>vm-eval</tt> is returning a result object (from the evaluation) and a new environment (since evaluations may result in modifying the environment).  <tt>repl-inner</tt> is used to recursively call into our repl and it persists the environments state.  <tt>vm-eval</tt> and print-object must be changed to use the environment.</p>
<p><pre class="brush: plain; first-line: 15; highlight: [39,40,41,42,43,44,53];">
;; Checks a list to see if the first symbol is define
(define (define-form? input)
 (and (not (null? input))
      (equal? (car input) (string-&gt;symbol &quot;define&quot;))
      (&gt;= (length input) 2)))

;; Takes in a define and adds it to the environment
(define (define-form input env)
 (let ((form (if (&gt; (length input) 2)
                 (vm-eval (caddr input) env)
                 '())))

       (if (not (equal? form 'error))
           (values input (env-add-def env (cadr input) form))
           (values 'error env))))

;; Evaluates an input string
(define (vm-eval input env)
 (cond
  [(string? input)  (values input env)]
  [(number? input)  (values input env)]
  [(null? input)    (values input env)]
  [(char? input)    (values input env)]
  [(boolean? input) (values input env)]
  [(symbol? input)  (values (env-get-def env input) env)]

  ; Process define forms
  [(and (list? input)
        (define-form? input))
    (define-form input env)]
  [else 'error]))

;; Prints objects out to stdout
(define (print-obj obj)
 (cond
  [(string? obj) (display
                 (string-append doublequote-char obj doublequote-char))]
  [(char? obj)   (display (string-append &quot;#\\&quot; (string obj)))]
  [(equal? obj 'error)  (display &quot;ERROR!&quot;)]
  [else          (display obj)])
                 (newline))
</pre></p>
<p>Now we have a couple new functions that will let us work with defines easily.  They&#8217;re pretty self-explanatory.  The real interesting thing is the way the define is parsed and processed.  Since the third element in the define can itself be something already in the environment it gets passed through <tt>vm-eval</tt>.  This allows us to follow <tt>(define test1 123)</tt> with <tt>(define test2 test1)</tt> and have <tt>test2</tt> evaluate to 123.</p>
<p><tt>vm-eval</tt> has now changed to handle symbols.  It looks them up in the environment and displays their values if found.  If not our old friend <tt>error</tt> shows up and <tt>print-object</tt> handles that by printing and error string.</p>
<p>Let us test it out!</p>
<pre>#;1&gt; ,l repl
; loading repl.scm ...
; loading env.scm ...
; loading library srfi-1 ...
#;1&gt; (repl)
-: "123"
"123"
-: 1234
1234
-: (define test 123)
(define test 123)
-: test         
123
-: (define abc test)
(define abc test)
-: abc
123</pre>
<p>I successfully define <tt>test</tt> and get 123 back when evaluating it.  Then I define <tt>abc</tt> to be test and get 123 back when evaluating <tt>abc</tt>.</p>
<p>The code for this iteration of Scheme in Scheme can be found at <a href="https://github.com/healyk/Scheme-in-Scheme/tree/Part.2">GitHub</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codingninja.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codingninja.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codingninja.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codingninja.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codingninja.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codingninja.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codingninja.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codingninja.wordpress.com/117/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=117&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codingninja.wordpress.com/2011/02/26/scheme-in-scheme-part-2-simple-defines/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cbf2750b09fac1abb6721658070732a1?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">Kris</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple Scheme Part 1 &#8211; Introduction</title>
		<link>http://codingninja.wordpress.com/2011/02/19/simple-scheme-part-1-introduction/</link>
		<comments>http://codingninja.wordpress.com/2011/02/19/simple-scheme-part-1-introduction/#comments</comments>
		<pubDate>Sat, 19 Feb 2011 19:58:49 +0000</pubDate>
		<dc:creator>Kris Healy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[Scheme in Scheme]]></category>

		<guid isPermaLink="false">http://codingninja.wordpress.com/?p=77</guid>
		<description><![CDATA[A very early exercise for those who wish to write an interpreter is to write a Scheme interpreter in Scheme.  At first this sound counter-intuitive and slightly crazy.  Why would we re-write a language in itself?  If we wanted to write a Scheme interpreter, why not use a language that other Scheme interpreters are written [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=77&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A very early exercise for those who wish to write an interpreter is to write a Scheme interpreter in Scheme.  At first this sound counter-intuitive and slightly crazy.  Why would we re-write a language in itself?  If we wanted to write a Scheme interpreter, why not use a language that other Scheme interpreters are written in &#8211; like C or C++?</p>
<p>I thought many of the same things.  The idea did seem crazy at first, but there are quite a few good reasons to write a Scheme interpreter in Scheme.</p>
<ol>
<li>You already have a perfectly good Scheme implementation at your fingertips.  This means it&#8217;s less inventing and more replacing parts of the language.</li>
<li>Just replacing pieces creates a quicker feedback loop.  You don&#8217;t have to spend days writing code to see results.</li>
<li>Scheme is a language written to process lists.  Scheme is written in lists.  That makes it a natural choice for this exercise.</li>
<li>Writing a Scheme interpreter in a lower level or more verbose language, such as C or C++, is time consuming.</li>
<li>It is more of a learning exercise.  Using Scheme keeps it simple.</li>
<li>If you want to take it to the next level, you can always <a href="http://www.cs.indiana.edu/~jsobel/c455-c511.updated.txt">translate your Scheme code into a statically typed language for awesomeness</a>.</li>
</ol>
<p>Another question is why Scheme and not another language?  Scheme is an extremely basic and simple language.  Since it&#8217;s simple there is less to implement and therefore our goal is easier to achieve.  According to the <a title="Wikipedia Scheme" href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29#Review_of_standard_forms_and_procedures">Wikipedia Article on Scheme</a> you don&#8217;t need to implement a lot of things underneath the hood to get a basic but complete Scheme-like language.  Since it has a powerful macro system, you can write many of the Scheme forms in Scheme itself.  There are a few other languages that writing an interpreter for Scheme can be done in, such as Common Lisp, Clojure, Ruby, Python, and so forth.  The further you get from a Lisp language though the more code you are going to write.</p>
<h2>Starting With a Repl</h2>
<p>The first thing to hack together is a simple Read Evaluate Print Loop or Repl.  A Repl gives instant gratification &#8211; you type something in and the interpreter evaluates it.  Here is an extremely naïve and simple version of what we&#8217;ll need.</p>
<p><pre class="brush: plain;">
(define (repl)
  (read-input)
  (vm-eval)
  (print-obj)
  (repl))
</pre></p>
<p>This is pretty straight forward.  It reads the input, evaluates it, and prints the result.  To evaluate input and print a result the Repl needs to capture information.  Here is version 1 of the Repl algorithm.</p>
<p><pre class="brush: plain;">
(define (repl)
 (display prompt)
 (print-obj (vm-eval (read-input)))
 (repl))
</pre></p>
<p>This captures input from the user, evaluates it and prints it out.  Lather, rinse, repeat!  It&#8217;s also a lot more functional than our previous example.</p>
<h2>The Bits and Pieces</h2>
<p>Now to move on to the actual read, print and evaluate pieces.  Right now the read is extremely simple.</p>
<p><pre class="brush: plain;">
(define (read-input)
  (read))
</pre></p>
<p>This code is using the underlying Scheme system.  Second function and I&#8217;m already cheating.   (read) will not only read input from the user, but it also parses it and returns an appropriate Scheme value.  If I enter a number then (read) returns a Scheme number; (number? (read)) evaluates to #t.  This is fine for now since parsing is complex.  I don&#8217;t want to get into having to parse input at this point.</p>
<p>Here is the evaluation function.</p>
<p><pre class="brush: plain;">
(define (vm-eval input)
  (cond
   [(string? input)  input]
   [(number? input)  input]
   [(null? input)    input]
   [(char? input)    input]
   [(boolean? input) input]
   [else &quot;Error!&quot;]))
</pre></p>
<p>This isn&#8217;t much right now.  It just patriots the input depending on the input&#8217;s type.  Given a number, string, character etcetera it will return that same object.  Symbols will drop down to the else cause.  That&#8217;s fine for now.  We can work on evaluating symbols in the future.  It&#8217;s called (vm-eval) because (eval) is already claimed by the underlying Scheme system.</p>
<p>After evaluating we need to prints results.</p>
<p><pre class="brush: plain;">
(define (print-obj obj)
  (cond
   [(string? obj) (display
                   (string-append doublequote-char obj doublequote-char))]
   [(char? obj)   (display (string-append &quot;#\\&quot; (string obj)))]
   [else          (display obj)])
  (newline))
</pre></p>
<p>This has some simple beautification functionality.   It will surround strings with double-quotes before printing.   It will also print characters as they are entered in Scheme, preceded by #\.  Note that doublequote-char is just a constant for &#8221; in string form.</p>
<p>Trying it out, it will print all the simple types back when reading them in.  If it encounters a symbol, a single quote, or anything with parenthesis it chokes and prints &#8220;Error!&#8221;.</p>
<pre>&gt; (load "repl.scm")
"/home/kris/projects/lisp/repl.scm"
&gt; (repl)
-: 1234
1234
-: 3-5i
3-5i
-: .1234123e12
1.234123e11
-: "abc 123"
"abc 123"
-: #\c
#\c
-: #t
#t
-: nil
"Error!"
-:</pre>
<p>And that&#8217;s how you write an extremely simple Repl in Scheme.  The code can be found at <a title="My Github account" href="https://github.com/healyk/Scheme-in-Scheme/tree/Part.1" target="_blank">GitHub</a> tagged as Part.1.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codingninja.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codingninja.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codingninja.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codingninja.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codingninja.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codingninja.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codingninja.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codingninja.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codingninja.wordpress.com&amp;blog=9210566&amp;post=77&amp;subd=codingninja&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codingninja.wordpress.com/2011/02/19/simple-scheme-part-1-introduction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cbf2750b09fac1abb6721658070732a1?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">Kris</media:title>
		</media:content>
	</item>
	</channel>
</rss>
