Monthly Archives: August 2011

AjLisp in Javascript (Part 2) List Evaluation, Forms and Special Forms

Previous Post
Next Post

In the previous post I presented the structure and creation of atoms and list. But, how a list is evaluated in AjLisp? As in other lisp implementation, the head of the list points to something (form or special form) to apply to the rest of the elements. This is the initial code in list evaluation:

List.prototype.evaluate = function(environment) 
    var form = this.first().evaluate(environment);		
    return form.apply(this, environment);

The head should be an element with .apply as method. There are two kinds of form: normal form and special forms. The form implementation:

function Form() {
Form.prototype.evaluate = function(environment) { return this; }
Form.prototype.apply = function(list, environment) 
    if (isNil(list)) return this.eval(list, environment);
    var rest =;
    if (rest != null)
        rest = rest.evaluateList(environment);
    return this.eval(rest, environment); 

The special form implementation:

function SpecialForm() {
SpecialForm.prototype.evaluate = function(environment) { return this; }
SpecialForm.prototype.apply = function(list, environment) 
    if (isNil(list)) return this.eval(list, environment);
    return this.eval(, environment);

The difference? The elements of the rest of the list ARE EVALUATED in a normal form. An special form doesn’t evaluate them. Why? Because the special form are “primitives” like (if <cond> <then> <else>…) where the <then> <else>… parts should be evaluated under control of the special form. See:

Special Forms in Lisp

Special forms are those expressions in the Lisp language which do not follow normal rules for evaluation. Some such forms are necessary as primitives of the language, while others may be desirable in order to improve readability, control the evaluation environment, implement abstraction and modularity, affect the flow of control, allow extended scoping mechanisms, define functions which accept a variable number of arguments, or achieve greater efficiency. There exist several long-standing mechanisms for specifying the definition of special forms: FEXPR’s, NLAMBDA’s, and MACRO’s.

Form examples? I wrote new forms using instances, overriding their eval method:

var listForm = new Form();
listForm.eval = function eval(list) 
	return list;
var nilpForm = new Form();
nilpForm.eval = function eval(list) 
	if (isNil(list))
		return true;
	return isNil(list.first());
var listpForm = new Form();
listpForm.eval = function eval(list) 
	if (isNil(list))
		return true;
	return isList(list.first());

An special form example, the ‘if’:

var ifForm = new SpecialForm();
ifForm.eval = function eval(list, env)
	var cond = evaluate(list.first(), env);
	var then =;
	var elsebody =;
	if (!isNil(cond) && cond != false)
		return evaluate(then, env);
	while (!isNil(elsebody)) 
		result = evaluate(elsebody.first(), env);
		elsebody =;
	return result;			

They are exposed in the global environment:

// Environment
var environment = new Environment();
environment.list = listForm;
environment.first = firstForm; = restForm;
environment.cons = consForm;
environment['do'] = doForm;
environment['if'] = ifForm;
// more settings in environment

Topics for upcoming posts: environments, closures, lambdas, macros.

Keep tuned!

Angel “Java” Lopez

Lambda Calculus: Links, News and Resources (1)

"Everything is a lambda in the end" ajlopez (past century)

In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion. The portion of lambda calculus relevant to computation is now called the untyped lambda calculus. In both typed and untyped versions, ideas from lambda calculus have found application in the fields of logic, recursion theory (computability), and linguistics, and have played an important role in the development of the theory of programming languages (with untyped lambda calculus being the original inspiration for functional programming, in particular Lisp, and typed lambda calculi serving as the foundation for modern type systems).

Closures + Lambda = The key to OOP in Lisp « Learning Lisp

Papers | Lambda the Ultimate

Notas sobre el Cálculo Lambda

Presenting AjLambda, lambda calculus in C#

Funarg problem

The lambda calculus

Fixed point combinator

Introducction to Lambda Calculus

Introduction to Lambda Calculus

Lambda Calculus

A Tutorial Introduction to the Lambda Calculus

Knights of the Lambda Calculus

A Hacker’s Introduction to Partial Evaluation | The Lambda meme – all things Lisp, and more

To Dissect a Mockingbird: A Graphical Notation for the Lambda Calculus with Animated Reduction

λProlog Home Page

Church’s Type Theory

Lambda Calculus Schemata

Lambda Animator : animated reduction of the lambda calculus

Peter Selinger: Papers

Mike Taulty’s Blog : Anonymous Methods, Lambdas, Confusion

Lecture Notes on the Lambda Calculus (pdf)

A Security Kernel Based on the Lambda-Calculus

System F: Second-order lambda calculus

(Mis)using C# 4.0 Dynamic – Type-Free Lambda Calculus, Church Numerals, and more

Type-Free Lambda Calculus in C#, Pre-4.0 – Defining the Lambda Language Runtime (LLR)

Jim McBeath: Practical Church Numerals in Scala

My Links

Angel "AjLambda" Lopez

AjFabriq on NodeJs (Part 1) Introduction

Next Post

Some years ago I discovered Fabriq project (thanks @asehmi!):

Remember Fabriq
FABRIQ has gone public!
Arvindra Shemi Fabriq Articles
Clemens Vasters Fabriq Articles

Key points:

FABRIQ is an infrastructure for constructing networks of nodes processing and relaying messages. These nodes are hosted in machines running into a serviced application.

You can have multiple machines running the same or different applications. The “network” is the application, “node” is a collection of “actions”, and each action process a message. More doc:

These nodes can be hosted in any distribution on several machines according to a defined configuration, so there may be machines running a single node or several nodes, this association are made by specifying the host-name or machine identification associated with each node in the network.

Each of these machines is running a serviced application responsible for starting and stopping its Host and Nodes which are the application main components. The host is responsible for handling the configuration, loading and unloading nodes and receives the messages and delivers them to the appropriate Node.

Past weekend, I started a Javascript project to run on NodeJs, based on Fabriq ideas:

A Distributed Application Framework for NodeJs

Simple one file implementation. Four Javascript “Classes”.

I want to run many NodeJs servers that hosts AjFabriq applications, sending messages across their network:

Original Fabriq had application, nodes, configuration. I simplified it and now I have a simple Processor that accepts messages. It can produce 0, 1 or more messages:

Messages are schema-less JSON objects that contains its own routing information:

A Processor could handle all the messages containing the key/value application: “webcrawler”. Some processors are composites: they have another processors. Then, the webcrawler processor could have a child processor specialized in handle message with key/value node:”downloader”. See the picture? But the key/values and the deep of processor trees ARE DECIDED by the developer. You decide to have “applications”, “actions”, “nodes”, or whatever you want.

A host can have many processor defined. When message is posted, a simple local method decides where to send it. It could be locally processed or it could be send to a remote host. The host network is dynamic: a new host can be added at any time, then it can collaborate with the current messages processing.

Pending topics for upcoming blog posts: implementation details, the simplest application, using net (plain) sockets, my failure with Socket.IO. Work in progress: make AjFabriq more NodeJs friendly using EventEmitter in key points, host info (hosted application) better dissemination, more robust implementation; rename Socket to Channel, a better description word.

My previous work on distributed application samples:


Keep tuned!

Angel “Java” Lopez

Erlang: Links, News and Resources (1)

Next Post

Recently I published a post about Haskell. Now, it’s time to visit Erlang programming languages. My links and discoveries:

Erlang is a general-purpose concurrent, garbage-collected programming language and runtime system. The sequential subset of Erlang is a functional language, with strict evaluation, single assignment, and dynamic typing. For concurrency it follows the Actor model. It was designed by Ericsson to support distributed, fault-tolerant, soft-real-time, non-stop applications. It supports hot swapping, so that code can be changed without stopping a system.[1]

While threads are considered a complicated and error-prone topic in most languages, Erlang provides language-level features for creating and managing processes with the aim of simplifying concurrent programming. Though all concurrency is explicit in Erlang, processes communicate using message passing instead of shared variables, which removes the need for locks.

The first version was developed by Joe Armstrong in 1986.[2] It was originally a proprietary language within Ericsson, but was released as open source in 1998.

Erlang Programming Language

YouTube – Erlang: The Movie

Invited Tutorial Erlang

Brief History of Erlang

Notes on A History of Erlang

HOPL-III: A History of Erlang

A history of Erlang

CiteSeerX — Use of Prolog for developing a new programming language
This paper describes how Prolog was used for the development of a new concurrent realtime symbolic programming language called Erlang.

Welcome to Erjang! – GitHub
Erjang is a virtual machine for Erlang, which runs on Java(tm).

InfoQ: Beam.js: Erlang Meets JavaScript

Erlang User Group Argentina

LangDay – ErlangAr

InfoQ: Testing for the Unexpected

InfoQ: Ville Tuulos on Big Data and Map/Reduce in Erlang and Python with Disco

Functional Languages will Rule (but not this year) – Good Stuff

InfoQ: Francesco Cesarini and Simon Thompson on Erlang

Table of Contents | Learn You Some Erlang for Great Good!

The Next Drupal? Zotonic: A Modern CMS Written in Erlang

Computer Language Design: What’s List Comprehension and Why is It Harmful?

Node.js vs Erlang: SyncPad’s Experience

Hacker News | They’re so different and yet so similar it’s probably best taking them one topic…

9 Programming Languages To Watch In 2011 | Regular Geek

InfoQ: Scala, Erlang, F# Creators Discuss Functional Languages

InfoQ: Computation Abstraction: Going Beyond Programming Language Glue

Write A Template Compiler For Erlang

Erlang | September 2010 | Communications of the ACM

Ebot | Matteo Redaelli
Erlang Bot (Ebot) is an opensource web crawler written on top of Erlang,

The Lisp Before the End of My Lifetime
Networked & Concurrent Programming: Leaders in this area: Erlang

InfoQ: Steve Vinoski on Erlang and Rest

Try Erlang

String Calculator – Erlang » Software Craftsmanship – Katas

InfoQ: Kresten Krab Thorup on Erjang, JVM Languages, Kilim

Avoiding Erlang deadlocks – Embrace change

InfoQ: Horizontal Scalability via Transient, Shardable, and Share-Nothing Resources

Tidier: A refactoring tool for Erlang

The Pragmatic Bookshelf | Seven Languages in Seven Weeks

Parsing SPARQL in Erlang with a monadic combinatory parser

Lisp Flavored Erlang

InfoQ: RPC and its Offspring: Convenient, Yet Fundamentally Flawed

10 programming languages worth checking out – H3RALD

The Pragmatic Bookshelf | What’s all this fuss about Erlang?

Jim McBeath: Actor Exceptions

InfoQ: John Hughes Contrasts Erlang and Haskell

InfoQ: Systems that Never Stop (and Erlang)

The “Anti-For” Campaign – Matthew Podwysocki – CodeBetter.Com – Stuff you need to Code Better!

Luke Galea on Ruby and Erlang

Functional programming in the Java language

Contrasting Performance : Languages, styles and VMs – Java, Scala, Python, Erlang, Clojure, Ruby, Groovy, Javascript

State You are doing wrong

Erlang vs. Scala – PlanetErlang

Minimal Erlang SMTP, POP3 server code « LShift Ltd.

PubSub is taking off – ProcessOne

Humanist → Scalable Web Apps: Erlang + Python

InfoQ: CouchDB From 10,000 Feet

Erlang Factory London 2009

InfoQ: Domain Specific Languages in Erlang

Tic-tac-toe in Erlang — smart game space

The State of Axum
How new C# features were influenced by Erlang
“I see axum as erlang done right and for the CLR, coouldnt be better!”

My links:

More links about functional programming are coming.

Keep tuned!

Angel “Java” Lopez

Node.Js: Links, news, Resources (2)

Previous post
Next post

Since my previous post, I was playing a bit with Node.Js, on Ubuntu and Windows (now, there is a Windows precompiled version, ready to download and run, see I’m working on rewriting Fabriq ideas from @asehmi to run on pure NodeJs (check my progress at; for Fabriq, check

Node.js is an event-driven I/O server-side JavaScript environment based on V8. It is intended for writing scalable network programs such as web servers.[1] It was created by Ryan Dahl in 2009, and its growth is sponsored by Joyent, which employs Dahl.[2] [3]

Similar environments written in other programming languages include Twisted for Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby. Unlike most JavaScript, it is not executed in a web browser, but is instead a form of server-side JavaScript. Node.js implements some CommonJS specifications.[4] Node.js includes a REPL environment for interactive testing.

Deploying Node.js With Upstart and Monit – How To Node – NodeJS

Custom Node.js Modules «

Writing Node.js Native Extensions | Cloudkick, manage servers better

How To Module – How To Node – NodeJS

Installing Node.js and NPM on Ubuntu 10.04 and try a simple chat application

Installing node.js on ubuntu 10.04

BDD and TDD for node.js? – Stack Overflow

Ubuntu 11.10 to support the Cloud Foundry Platform-as-a-Service

TJ Holowaychuk • commander.js – nodejs command-line interfaces made easy

nodechat.js – Using node.js, backbone.js,, and redis to make a real time chat app

Node.js on Windows: Who Needs NPM? « ICED IN CODE

node.js & fun – till’s blog

Adam Coffman – Getting your feet wet with node.js and – Part 1

node.js: Building a graph of build times using the Go API at Mark Needham

Episode 10: Sprite 3D, Candy, NodeJS discussion, jQuery plugins | The Javascript Show

Nodejs – A quick tour (v4)

NodeSocket to launch hosting for Node.js apps

Dear PHP, I’m leaving and yes, she’s sexier

InfoQ: Ephemeralization or Heroku’s Evolution to a Polyglot Cloud OS

Understanding node.js » Debuggable Ltd

The Node.js Philosophy – – scaling node.js applications one callback at a time.

Using node.js async library reminds me of continuations and monads – The Web and all that Jazz

Real time online activity monitor example with node.js and WebSocket

Windows Azure Storage for Node.js

Step by step instructions to install NodeJS on Windows

Easy Node.js Apps With Lisp

LearnBoost/tobi – GitHub

NodeJS is easy, just ask her out

npm – Node Package Manager

nowjs for Node – Directly call remote functions in Javascript

Websockets everywhere with Socket.IO

Running the “Express” web development framework on Node for Windows

Orkis – online web based multiplayer tetris

node.js – A giant step backwards – Fenn’s Thoughts

Learning Javascript with Object Graphs

Bricks.js – Documentation

Node.js Beginner Book

The Node Beginner Book » A comprehensive Node.js tutorial

Node.js Creator Ryan Dahl’s Keynote from NodeConf

Node.js, Ruby, and Python in Windows Azure

Reactor pattern

The New Heroku (Part 2 of 4): Node.js & New HTTP Capabilities

Microsoft working with Joyent and the Node community to bring Node.js to Windows

Porting Node to Windows With Microsoft’s Help

Do I need a server to use HTML5’s WebSockets? – Stack Overflow

Single Page Apps with Node.js. – – scaling node.js applications one callback at a time.

Node Inspector – Node.js Debugger

Where does node.js fit in a Microsoft / Azure / WCF / MVC project? – Stack Overflow

NodeJS Tutorial with CouchDB and Haml – ErdNodeFlips

isaacs/nave – GitHub
Virtual Environments for Node

Comparing clojure and node.js for speed

node core vs userland – GitHub

Calipso – A Node CMS

My links:

Haskell: Links, News and resources (1)

I’m interested in programming languages and in functional programming. Haskell study and practice is a good step towards grasping functional ideas. These are my links about this language:

Haskell (pronounced /ˈhæskəl/)[3][4] is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing.[5] It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language.[6] As a functional programming language, the primary control construct is the function. The language is rooted in the observations of Haskell Curry and his intellectual descendants, that "a proof is a program; the formula it proves is a type for the program".

Learn You a Haskell for Great Good! – Higher Order Functions

Haskell :: Functional Programming with Types

How to learn Haskell – Stack Overflow

Try Haskell! An interactive tutorial in your browser

A Neighborhood of Infinity: The Infinitude of the Primes

InfoQ: Multicore Programming in Haskell

Yesod :: Enumerator Package

The implementation of the Gofer functional programming system

I1M2010: Operaciones con el TAD de los polinomios en Haskell | Vestigium

Un problema de las olimpiadas rusas en Haskell | Vestigium

Applicative Programming with Effects

Arrows: A General Interface to Computation

Haskell/Understanding arrows – Wikibooks, open books for an open world

Haskell :: Functional Programming with Types

Functional Languages will Rule (but not this year) – Good Stuff

Ruminations of a Programmer: Combinators as the sublanguage of DSL syntax

The Algebra of Data, and the Calculus of Mutation » Lab49 Blog

Type inference – Wikipedia, the free encyclopedia

The Joy of Haskell, parte 1 – Introdução « Ars Physica

A Neighborhood of Infinity: Generalising Gödel’s Theorem with Multiple Worlds. Part II.

The Arrows Calculus

Wadler’s Blog: The Arrow Calculus

Program Haskell with Lisp Syntax Using Liskell or Lisk

Lisk – Lisp and Haskell

johang88’s haskellinjavascript at master – GitHub

Conal Elliott » “Everything is a function” in Haskell?

Haskell: The Confusing Parts

Video presentations – HaskellWiki

A Neighborhood of Infinity: Products, Limits and Parametric Polymorphism

My Links

Angel “Java” Lopez

AjLisp in Javascript (Part 1) Atoms, Lists and TDD

Next Post

I’m rewriting my AjLisp interpreter using Javascript. I think that a Lisp interpreter is a good project to learn a language: simple, bounded but not trivial. I would never have begun this project without TDD (Test-Driven Development): Javascript is so dynamic and the tools I’m using (the browser, plain text editors) are so limited, that this project have been hard without the help of TDD. The practice of TDD gives me fun, doing baby steps and it helps me to explore good design.

The code (with parser, many primitive forms, some macro procession, work in progress) is at GitHub:

The code is in one file:

I’m using QUnit for tests:

The implementation uses the namespace pattern:

AjLisp = function() {
// ...

The namespace is the result of evaluate a function. This function returns an object with the public members of the namespace:

return {
	// Classes
	List: List,
	Environment: Environment,
	Atom: Atom,
	Closure: Closure,
	Lexer: Lexer,
	TokenType: TokenType,
	Parser: Parser,
	// Functions
	makeList: makeList,
	isAtom: isAtom,
	isList: isList,
	isNil: isNil,
	asString: asString,
	evaluate: evaluate,
	// Top Environment
	environment: environment

As usual, a Lisp interpreter should support lists and atoms. Partial code:

function List(first, rest) {
	function getFirst() {
		return first;
	function getRest() {
		return rest;
	this.first = getFirst; = getRest;
List.prototype.isAtom = function() { return false; }
List.prototype.isList = function() { return true; }
List.prototype.evaluate = function(environment) 
	var form = this.first().evaluate(environment);		
	return form.apply(this, environment);
// ...

Note that the first and rest part of a list are encapsulated in the constructor closure. They are inmutable, and can be accesed by functions aList.first(), I should evaluate the impact of all those closure at list construction. But they are relative light.

Atom implementation is simple:

function Atom(name) {
	this.evaluate = function(environment) {
		return environment.getValue(name);
	}; = function() { return name; };
Atom.prototype.isAtom = function() { return true; }
Atom.prototype.isList = function() { return false; }
Atom.prototype.asString = function() { return; }
Atom.prototype.equals = function(atom)
	if (isNil(atom) || !isAtom(atom))
		return false;
	return ==;

The atom evaluation is based in an enviroment (association of names to values) and the atom name. Numbers, strings are direct Javascript objects and they don’t need to be implemented as atoms. In a “classical” Lisp implementation, all elements are SExpressions (symbolic expressions) capable of being evaluated. Now, I have AjLisp.evaluate that accepts any Javascript object and detect if it can be evaluated in an environment:

function evaluate(x, environment)
	if (x === null || x === undefined)
		return x;
	if (x.evaluate != undefined && typeof(x.evaluate) == "function")
		return x.evaluate(environment);
	return x;

Atom tests:

test("Atom", function() {
	var environment = new AjLisp.Environment();
	environment.setValue("one", 1);
	var one = new AjLisp.Atom("one");
	equal(one.evaluate(environment), 1);
	equal(one.isList(), false);
	equal(AjLisp.isList(one), false);
	equal(one.asString(), "one");
	equal(one.equals(one), true);
	var one2 = new AjLisp.Atom("one");
	equal(one.equals(one2), true);

Test exercising list behavior:

test("List", function() {
	var list = new AjLisp.List(1,2);
	equals(list.first(), 1);
	equals(, 2);
	equal(AjLisp.isAtom(list), false);
	equal(AjLisp.isList(list), true);
	equal(list.asString(), "(1.2)");
	equal(list.equals(list), true);
	var list2 = new AjLisp.List(1,2);
	equal(list.equals(list2), true);
	equal(list2.equals(list), true);
	var list3 = AjLisp.makeList(1,2,3);
	equal(list.equals(list3), false);
	equal(list3.equals(list), false);
	list = AjLisp.makeList(null, null);
	ok(list.first() === null);
	ok( === null);

Pending topics: environment implementation, list evaluation, forms and special forms, parser, lambda, mlambda, flambda. Lot of fun! 😉

Keep tuned!

Angel “Java” Lopez