μLithp reader
μLithp - a Lisp in 27 lines of Ruby source
Primordial ooze | A reader | REPL | A compiler | Ruby interop
Extending μLithp with a reader
You can, if you choose, write μLithp code directly using Ruby arrays and symbols. However, writing a reader that reads in a more traditional textual Lisp-like syntax and converts it into the Ruby data structures. My friend Russ Olsen wrote a little reader, that I present below:
Reader
class Reader def initialize(expression) @tokens = expression.scan /[()]|\w+|".*?"|'.*?'/ end def peek @tokens.first end def next_token @tokens.shift end def read return :"no more forms" if @tokens.empty? if (token = next_token) == '(' read_list elsif token =~ /['"].*/ token[1..-2] elsif token =~ /\d+/ token.to_i else token.to_sym end end def read_list list = [] list << read until peek == ')' next_token list end end
Usage
Using the Reader
class is simple as the following:
require 'lithp' require 'reader' Reader.new("(quote (1 2 3))").read #=> [:quote, [1, 2, 3]] l.eval Reader.new("(quote (1 2 3))").read #=> [1, 2, 3]
And that's it.