Monday, April 6, 2009

Building DSL with Scheme

I have listened a talk made by Shriram Krishnamurthi. It is called The Swine Before Perl . The talk is about using scheme to do heavy lifting which other languages can't handle. It is a great talk. It shows me the real amazing strength of Scheme programming language. Shriram centers his talk around an example of automaton. The Scheme source code is based on the old version of PLT Scheme. As a result, the source code can't run against the current implementation. I have made a little change to the source code. I post it here for reference.

The following source code is tested in DrScheme, version 4.1.4.
The first version of automaton.

#lang slideshow
(define b-machine-states
'((init (c more))
(more (a more)
(d more)
(r end))
(end (r end))))

(define (b-machine stream)
(letrec ([walker (lambda (state stream)
(or (empty? stream)
(let ([transitions
(cdr (assv state b-machine-states))])
(let ([1st (first stream)])
(let ([new-state (assv 1st transitions)])
(if new-state
(walker (cadr new-state) (rest stream))
false))))))])
(walker 'init stream)))

(b-machine '(c a r))
(b-machine '(c a d r))
(b-machine '(c a x))

The goto version of automaton.

#lang scheme
(define b-machine
(letrec ([init
(lambda (stream)
(or (empty? stream)
(case (first stream)
[(c) (more (rest stream))]
[else false])))]
[more
(lambda (stream)
(or (empty? stream)
(case (first stream)
[(a) (more (rest stream))]
[(d) (more (rest stream))]
[(r) (end (rest stream))]
[else false])))]
[end
(lambda (stream)
(or (empty? stream)
(case (first stream)
[(r) (end (rest stream))]
[else false])))])
init))

(b-machine '(c a r))
(b-machine '(c a d r))
(b-machine '(c a x))

The second version of automaton.

#lang scheme
(define-syntax automaton
(syntax-rules (-> :)
[(_ init-state
(state : (cndn -> new-state) ...)
...)
(letrec ([state
(lambda (stream)
(or (empty? stream)
(case (first stream)
[cndn (new-state (rest stream))]
...
[else false])))]
...)
init-state)]))

(define b-machine
(automaton init
(init : ((c) -> more))
(more : ((a) -> more)
((d) -> more)
((r) -> end))
(end : ((r) -> end))))



(b-machine '(c a r))
(b-machine '(c a d r))
(b-machine '(c a x))

The following code is really an elegant DSL for automaon.

(automaton init
(init : ((c) -> more))
(more : ((a) -> more)
((d) -> more)
((r) -> end))
(end : ((r) -> end)))


I have also implemented the first and goto version of automaton in Ruby.
The first version of automaton in Ruby

$b_machine_states = {
"init" => {"c" => "more"},
"more" => {"a" => "more",
"d" => "more",
"r" => "end"},
"end" => {"r" => "end"}}

def walker(state, stream)
if stream.empty?
return true
end
first = stream[0]
transitions = $b_machine_states[state]
new_state = transitions[first]
if new_state == nil
return false
else
rest = stream[1, stream.length()]
return walker(new_state, rest)
end
end

def b_machine(stream)
walker("init", stream)
end

print b_machine("car") , "\n"
print b_machine("cadr") , "\n"
print b_machine("cax") , "\n"

The goto version of automaton in Ruby

class Automaton

def accept(stream)
return init(stream)
end

private
def init(stream)
if stream.empty?
return true
end
first = stream[0]
case first
when "c"
return more(rest(stream))
else
false
end
end

def more(stream)
if stream.empty?
return true
end
first = stream[0]
case first
when "a"
return more(rest(stream))
when "d"
return more(rest(stream))
when "r"
return terminate(rest(stream))
else
return false
end
end

def terminate(stream)
if stream.empty?
return true
end
first = stream[0]
case first
when "r"
return terminate(rest(stream))
else
return false
end
end

def rest(stream)
return stream[1, stream.length()]
end
end

auto = Automaton.new()
print auto.accept("car") , "\n"
print auto.accept("cadr") , "\n"
print auto.accept("cax"), "\n"

For the second version of automaton, I can't find a way to implement it in Ruby because Ruby does not have a macro system similar to Scheme. I am happy to know if anyone has a solution.

Monday, March 16, 2009

Add Fonts to Windows Command Line Console

By default, the command line console only has two fonts for Windows XP Simple Chinese version. They are Roster Font and Lucida Console. I am unhappy with them. I like Consolas and Bitstream Vera Sans Mono for command line. So I decided to add these fonts to the command line console. I have done it following Necessary criteria for fonts to be available in a command window. I have added two registry values as shown in the following registry file.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont]
"00"="Consolas"
"000"="Bitstream Vera Sans Mono"

The machine needs to be restarted after adding these stuff to registry. And I need to set the current code page to 437 in Option tab of the command line console shortcut if I want to select Consolas and Bitstream Vesa Sans Mono. The code page 936 does not work for these 2 fonts.

Friday, February 27, 2009

Subroutine Pointer in C

C has subroutine pointers. It does not require closures because it does not have nested scopes and it is static scoped. Every subroutine is at global scope. As a result, the referencing environment for a subroutine is the same whether it is created when the subroutine is first passed a parameter or when the subroutine is finally called. In the following code, plus_one has the same referencing environment whether the referencing environment is created when it is passed as a parameter to caller or when it is called in caller.

#include
int plus_one(int n) {
return n + 1;
}
void caller(int (*f) (int)) {
int result = f(3);
printf("3 plus 1 is %d\n", result);
}
int main() {
caller(plus_one);
return 0;
}

For a language which supports nested scope, the situation is different. In the following Common Lisp code, a closure must be created for plus_2 to make it a function which addes 2 to its sole parameter.

(let ((one 1))
(defun plus_1 (x)
(+ x one)))

(let ((one 5))
(plus_1 3))

Thursday, February 26, 2009

Dynamic Scope in LISP

The following program will print (3 5) in newlisp which is dynamic scoped. But it will print (3 7) in CLISP which is static scoped.

(let ((y 7)) (define (scope-test x) (list x y)))
(let ((y 5)) (scope-test 3))

Sunday, February 22, 2009

Java's file.encoding property on Windows platfor

This property is used for the default encoding in Java, all readers and writers would default to using this property. file.encoding is set to the default locale of Windows operationg system since Java 1.4.2. System.getProperty("file.encoding") can be used to access this property. Code such as System.setProperty("file.encoding", "UTF-8") can be used to change this property. However, the default encoding can be not changed dynamically even this property can be changed. So the conclusion is that the default encoding can't change after JVM starts. java -dfile.encoding=UTF-8 can be used to set the default encoding when starting a JVM. I have searched for this option Java official documentation. But I can't find it.

Tuesday, February 17, 2009

Produce the "TeX: The Program" from tex.web

This is how I have produced the TeX: The Program from tex.web

The result is a PDF file program.pdf and CONTENTS.tex. These files are the book.

Monday, February 9, 2009

A Quick Start of SWI-Prolog for Windows

Recently, I have been reading chapter 12 of Programming Language Pragmatics. This chapter is about logic programming. So I need a prolog implementation to try the code in the book. I choose SWI-Prolog. SWI-Prolog has a thorough reference manual. But what I want is only some quick start. After searching on Google, I don't find a decent SWI-Prolog quick start. So I have to do my work by scanning the reference book. It is kind of painful. Here, I write down what I think it is enough to do some simple things with SWI-Prolog, hoping that it will help you if you only do some simple things with SWI-Prolog.

My platform is Windows. After the installation of SWI-Prolog, add the SWI-Prolog bin directory to PATH environment varialbe. In my case, the bin directory is C:\Program Files\pl\bin.

SWI-Prolog has a plwin.exe which is GUI environment for SWI-Prolog. I prefer to use the SWI-Prolog console environment which is plcon.

  • Open a command line

  • change to directory containing my prolog source code. In my case, it is D:\documents\Prolog.

  • type plcon to launch prolog


Now the command console looks as follows.

D:\Documents\Prolog>plcon
Welcome to SWI-Prolog (Multi-threaded, 32 bits, Version 5.6.64)
Copyright (c) 1990-2008 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

1 ?- consult(woman).
% woman compiled 0.00 sec, 1,060 bytes
true.

2 ?-

Type consult(women) to load D:\documents\Prolog\women.pro. It contains the following clauses.

:-dynamic pregnant/.
human(susan).
human(jane).
pregnant(susan).
woman(X) :- pregnant(X), human(X).

Assert can only be used to add facts to dynamic predicates in the prolog interpreter. I want to add facts for predicate pregnant. So I add the dynamic directive in the prolog source code. pregnant/1 is a predicator indicator. A predicate indicator is used to denote predicates. It's form is Name/Arity where Name is an atom denoting the name of a predicate and Arity is a integer denoting the number of its arguments. Add one fact to the prolog clause databse.

2 ?- assert(pregnant(jane)).
true.

Issue a query. Type ; to ask for more answers.

3 ?- woman(X).
X = susan ;
X = jane.

Type halt. to exit SWI-Prolog

4 ?- halt.