Angel \”Java\” Lopez on Blog

September 5, 2011

AjLisp in Javascript (Part 3) Define, Lambda and Closures

Previous Post

Lets review the new forms definition in AjLisp, my Lisp interpreter written in Javascript (github repository). A key special form in AjLispJs, is define form:

var defineForm = new SpecialForm();
defineForm.eval = function eval(list, env)
{
	var name = list.first().name();
	var value = list.rest().first();
	var body = list.rest().rest();
		
	if (isNil(body)) {
		value = evaluate(value, env);
	}
	else {
		value = new Closure(value, env, body);
	}		
		
	environment[name] = value;
	return value;
}

You can use to define simple global data. My initial tests:

test("Evaluate Simple Expression with Atoms", function() {
	eval("(define one 1)");
	eval("(define two 2)");
	eval("(define three 3)");
	equal(eval("one"), 1);
	equal(eval("(quote one)").asString(), "one");
	equal(eval("(list one two three)").asString(), "(1 2 3)");
	equal(eval("(first (list one two three))"), 1);
	equal(eval("(rest (list one two three))").asString(), "(2 3)");
	equal(eval("(cons one (list two three))").asString(), "(1 2 3)");
});
		

But define is prepared to accept three parameters:

(define mapfirst (fn lst)
  (if (nilp lst)
    nil
    (cons
      (fn (first lst))
      (mapfirst fn (rest lst))
    )
  )
)

The first parameter is the name of the global environment property. The second is a list of parameters. The third is the form to apply. Define is used to define new functions. It’s equivalent to

(define mapfirst (lambda (fn lst)
    (if (nilp lst)
      nil
      (cons
        (fn (first lst))
        (mapfirst fn (rest lst))
      )
    )
  )
)

Note the lambda. It is an special form:

var lambdaForm = new SpecialForm();
lambdaForm.eval = function eval(list, env)
{
    var argnames = list.first();
    var body = list.rest();
    return new Closure(argnames, env, body);
}

Both define (with three parameters) and lambda create a Closure. The closure receives a list of argument names, a closure environment and a body. Then, when a closure is evaluated:

function Closure(argnames, closureenv, body) {
	body = new List(doForm, body);
	
	this.eval = function(args, environment) {
		var newenv = makeEnvironment(argnames, args, closureenv);
		return evaluate(body, newenv);
	};
}
	
Closure.prototype.evaluate = Form.prototype.evaluate;
Closure.prototype.apply = Form.prototype.apply;

The key part is the .eval: closure evaluation employs a new environment, based not in the current environment, but in the closureenv, the environment received in the constructor when the closure was created. This is a typical implementation in Lisp interpreter.

Next topics to discuss in upcoming posts: flambda, mlambda, macro evaluation, parser.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

August 29, 2011

Lambda Calculus: Links, News and Resources (1)

Filed under: Functional Programming, Lambda Calculus, Links, Lisp, Programming — ajlopez @ 9:52 am

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

http://en.wikipedia.org/wiki/Lambda_calculus

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
http://lispy.wordpress.com/2007/07/18/closures-lambda-the-key-to-oop-in-lisp/

Papers | Lambda the Ultimate
http://lambda-the-ultimate.org/papers

Notas sobre el Cálculo Lambda
http://ajlopez.zoomblog.com/archivo/2009/04/14/notas-sobre-el-Calculo-Lambda.html

Presenting AjLambda, lambda calculus in C#
http://ajlopez.wordpress.com/2009/02/25/presenting-ajlambda-lambda-calculus-implementation-in-c/

Funarg problem
http://en.wikipedia.org/wiki/Funarg_problem

The lambda calculus
http://faculty.knox.edu/dblaheta/research/lambda.pdf

Fixed point combinator
http://en.wikipedia.org/wiki/Y-combinator

Introducction to Lambda Calculus
http://www.cs.chalmers.se/Cs/Research/Logic/TypesSS05/Extra/geuvers.pdf

Introduction to Lambda Calculus
http://citeseer.ist.psu.edu/barendregt94introduction.html

Lambda Calculus
http://www.cs.bham.ac.uk/~axj/pub/papers/lambda-calculus.pdf

A Tutorial Introduction to the Lambda Calculus
http://www.utdallas.edu/~gupta/courses/apl/lambda.pdf

Knights of the Lambda Calculus
http://en.wikipedia.org/wiki/Knights_of_the_Lambda_Calculus

A Hacker’s Introduction to Partial Evaluation | The Lambda meme – all things Lisp, and more
http://www.ymeme.com/hackers-introduction-partial-evaluation.html

To Dissect a Mockingbird: A Graphical Notation for the Lambda Calculus with Animated Reduction
http://users.bigpond.net.au/d.keenan/Lambda/index.htm

http://www.defmacro.org/

λProlog Home Page
http://www.lix.polytechnique.fr/Labo/Dale.Miller/lProlog/

Church’s Type Theory
http://plato.stanford.edu/entries/type-theory-church/

Lambda Calculus Schemata
http://cs-www.cs.yale.edu/homes/fischer/pubs/lambda.pdf

Lambda Animator : animated reduction of the lambda calculus
http://thyer.name/lambda-animator/

Peter Selinger: Papers
http://www.mscs.dal.ca/~selinger/papers.html

Mike Taulty’s Blog : Anonymous Methods, Lambdas, Confusion
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/01/28/anonymous-methods-lambdas-confusion.aspx

Lecture Notes on the Lambda Calculus (pdf)
http://www.mscs.dal.ca/~selinger/papers/lambdanotes.pdf

A Security Kernel Based on the Lambda-Calculus
http://mumble.net/~jar/pubs/secureos/

System F: Second-order lambda calculus
http://en.wikipedia.org/wiki/System_F

(Mis)using C# 4.0 Dynamic – Type-Free Lambda Calculus, Church Numerals, and more
http://community.bartdesmet.net/blogs/bart/archive/2009/08/17/mis-using-c-4-0-dynamic-type-free-lambda-calculus-church-numerals-and-more.aspx

Type-Free Lambda Calculus in C#, Pre-4.0 – Defining the Lambda Language Runtime (LLR)
http://community.bartdesmet.net/blogs/bart/archive/2009/08/30/type-free-lambda-calculus-in-c-pre-4-0-defining-the-lambda-language-runtime-llr.aspx

Jim McBeath: Practical Church Numerals in Scala
http://jim-mcbeath.blogspot.com/2008/11/practical-church-numerals-in-scala.html

My Links
http://www.delicious.com/ajlopez/lambda

Angel "AjLambda" Lopez

August 24, 2011

Erlang: Links, News and Resources (1)

Filed under: Erlang, Functional Programming, Links, Programming Languages — ajlopez @ 9:45 am

Next Post

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

http://en.wikipedia.org/wiki/Erlang_%28programming_language%29

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
http://www.erlang.org/

YouTube – Erlang: The Movie
http://www.youtube.com/watch?v=uKfKtXYLG78

Invited Tutorial Erlang
http://www.erlang.org/workshop/armstrong.pdf

Brief History of Erlang
http://www.erlang.org/course/history.html

Notes on A History of Erlang
http://www.sauria.com/blog/2008/05/28/notes-on-a-history-of-erlang/

HOPL-III: A History of Erlang
http://lambda-the-ultimate.org/node/2811

http://www.scribd.com/doc/3405806/Erlanghistory

A history of Erlang
http://dl.acm.org/citation.cfm?id=1238850

CiteSeerX — Use of Prolog for developing a new programming language
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.3972
This paper describes how Prolog was used for the development of a new concurrent realtime symbolic programming language called Erlang.

Welcome to Erjang! – GitHub
https://github.com/trifork/erjang/wiki
Erjang is a virtual machine for Erlang, which runs on Java(tm).

InfoQ: Beam.js: Erlang Meets JavaScript
http://www.infoq.com/presentations/Beamjs-Erlang-Meets-JavaScript

Erlang User Group Argentina
http://erlang.org.ar/P%C3%A1gina_Principal

LangDay – ErlangAr
http://erlang.org.ar/LangDay

InfoQ: Testing for the Unexpected
http://www.infoq.com/presentations/Testing-for-the-Unexpected

InfoQ: Ville Tuulos on Big Data and Map/Reduce in Erlang and Python with Disco
http://www.infoq.com/interviews/tuulos-erlang-mapreduce

Functional Languages will Rule (but not this year) – Good Stuff
http://goodstuff.im/functional-languages-will-rule-but-not-this-y

InfoQ: Francesco Cesarini and Simon Thompson on Erlang
http://www.infoq.com/interviews/cesarini-thompson-erlang

Table of Contents | Learn You Some Erlang for Great Good!
http://learnyousomeerlang.com/content

The Next Drupal? Zotonic: A Modern CMS Written in Erlang
http://www.readwriteweb.com/hack/2011/05/the-next-drupal-zotonic.php

Computer Language Design: What’s List Comprehension and Why is It Harmful?
http://xahlee.org/comp/list_comprehension.html

Node.js vs Erlang: SyncPad’s Experience
http://blog.mysyncpad.com/post/2073441622/node-js-vs-erlang-syncpads-experience

Hacker News | They’re so different and yet so similar it’s probably best taking them one topic…
http://news.ycombinator.com/item?id=2414035

9 Programming Languages To Watch In 2011 | Regular Geek
http://regulargeek.com/2010/12/11/9-programming-languages-to-watch-in-2011/

InfoQ: Scala, Erlang, F# Creators Discuss Functional Languages
http://www.infoq.com/interviews/functional-langs

InfoQ: Computation Abstraction: Going Beyond Programming Language Glue
http://www.infoq.com/presentations/Computation-Abstraction

Write A Template Compiler For Erlang
http://evanmiller.org/write-a-template-compiler-for-erlang.html

Erlang | September 2010 | Communications of the ACM
http://cacm.acm.org/magazines/2010/9/98014-erlang/fulltext

Ebot | Matteo Redaelli
http://www.redaelli.org/matteo-blog/projects/ebot/
Erlang Bot (Ebot) is an opensource web crawler written on top of Erlang,

The Lisp Before the End of My Lifetime
http://metalinguist.wordpress.com/2007/08/04/the-lisp-before-the-end-of-my-lifetime/
Networked & Concurrent Programming: Leaders in this area: Erlang

InfoQ: Steve Vinoski on Erlang and Rest
http://www.infoq.com/interviews/steve-vinoski-erlang-rest

Try Erlang
http://www.tryerlang.org/

String Calculator – Erlang » Software Craftsmanship – Katas
http://katas.softwarecraftsmanship.org/?p=96

InfoQ: Kresten Krab Thorup on Erjang, JVM Languages, Kilim
http://www.infoq.com/interviews/thorup-erjang

Avoiding Erlang deadlocks – Embrace change
http://mue.tideland.biz/avoiding-erlang-deadlocks

InfoQ: Horizontal Scalability via Transient, Shardable, and Share-Nothing Resources
http://www.infoq.com/presentations/Horizontal-Scalability

Tidier: A refactoring tool for Erlang
http://tidier.softlab.ntua.gr:20000/tidier/getstarted

The Pragmatic Bookshelf | Seven Languages in Seven Weeks
http://pragprog.com/titles/btlang/seven-languages-in-seven-weeks

Parsing SPARQL in Erlang with a monadic combinatory parser
http://antoniogarrote.lacoctelera.net/post/2009/11/01/parsing-sparql-in-erlang-with-monadic-combinatory-parser

Lisp Flavored Erlang
http://metajack.im/2009/01/09/lisp-flavored-erlang/

InfoQ: RPC and its Offspring: Convenient, Yet Fundamentally Flawed
http://www.infoq.com/presentations/vinoski-rpc-convenient-but-flawed

10 programming languages worth checking out – H3RALD
http://www.h3rald.com/articles/10-programming-languages/

The Pragmatic Bookshelf | What’s all this fuss about Erlang?
http://pragprog.com/articles/erlang

Jim McBeath: Actor Exceptions
http://jim-mcbeath.blogspot.com/2008/07/actor-exceptions.html

InfoQ: John Hughes Contrasts Erlang and Haskell
http://www.infoq.com/interviews/Erlang-Haskell-John-Hughes

InfoQ: Systems that Never Stop (and Erlang)
http://www.infoq.com/presentations/Systems-that-Never-Stop-Joe-Armstrong

The “Anti-For” Campaign – Matthew Podwysocki – CodeBetter.Com – Stuff you need to Code Better!
http://codebetter.com/blogs/matthew.podwysocki/archive/2009/06/26/the-anti-for-campaign.aspx

Luke Galea on Ruby and Erlang
http://www.infoq.com/interviews/galea-ruby

Functional programming in the Java language
http://www.ibm.com/developerworks/java/library/j-fp.html

Contrasting Performance : Languages, styles and VMs – Java, Scala, Python, Erlang, Clojure, Ruby, Groovy, Javascript
http://blog.dhananjaynene.com/2011/08/cperformance-comparison-languages-styles-and-vms-java-scala-python-erlang-clojure-ruby-groovy-javascript/

State You are doing wrong
http://www.slideshare.net/jboner/state-youre-doing-it-wrong-javaone-2009

Erlang vs. Scala – PlanetErlang
http://www.planeterlang.org/en/planet/article/Erlang_vs._Scala/

Minimal Erlang SMTP, POP3 server code « LShift Ltd.
http://www.lshift.net/blog/2007/09/20/minimal-erlang-smtp-pop3-server-code

PubSub is taking off – ProcessOne
http://www.process-one.net/en/blogs/article/pubsub_is_taking_off/

Humanist → Scalable Web Apps: Erlang + Python
http://humani.st/scalable-web-apps-erlang-python/

InfoQ: CouchDB From 10,000 Feet
http://www.infoq.com/presentations/couchDB-from-10K-feet

Erlang Factory London 2009
http://www.erlang-factory.com/conference/London2009/talks

InfoQ: Domain Specific Languages in Erlang
http://www.infoq.com/presentations/dsl-erlang-dennis-byrne

Tic-tac-toe in Erlang — smart game space
http://nealabq.com/blog/2009/03/06/tic-tac-toe-erlang-smart-game-space/

The State of Axum
http://blogs.msdn.com/b/maestroteam/archive/2011/02/28/the-state-of-axum.aspx
How new C# features were influenced by Erlang
“I see axum as erlang done right and for the CLR, coouldnt be better!”

My links:
http://www.delicious.com/ajlopez/erlang

More links about functional programming are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

August 22, 2011

Haskell: Links, News and resources (1)

Filed under: Functional Programming, Haskell, Links, Programming Languages — ajlopez @ 3:41 pm

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:

http://en.wikipedia.org/wiki/Haskell_%28programming_language%29

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
http://learnyouahaskell.com/higher-order-functions

Haskell :: Functional Programming with Types
http://en.wikibooks.org/wiki/Haskell

How to learn Haskell – Stack Overflow
http://stackoverflow.com/questions/1012573/how-to-learn-haskell

Try Haskell! An interactive tutorial in your browser
http://tryhaskell.org/

A Neighborhood of Infinity: The Infinitude of the Primes
http://blog.sigfpe.com/2011/07/infinitude-of-primes.html

InfoQ: Multicore Programming in Haskell
http://www.infoq.com/presentations/Multicore-Programming-in-Haskell

Yesod :: Enumerator Package
http://www.yesodweb.com/book/enumerator

The implementation of the Gofer functional programming system
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.117.5058

I1M2010: Operaciones con el TAD de los polinomios en Haskell | Vestigium
http://www.glc.us.es/~jalonso/vestigium/i1m2010-operaciones-con-el-el-tad-de-los-polinomios-en-haskell/

Un problema de las olimpiadas rusas en Haskell | Vestigium
http://www.glc.us.es/~jalonso/vestigium/un-problema-de-las-olimpiadas-rusas-en-haskell/

Applicative Programming with Effects
http://www.soi.city.ac.uk/~ross/papers/Applicative.html

Arrows: A General Interface to Computation
http://www.haskell.org/arrows/

Haskell/Understanding arrows – Wikibooks, open books for an open world
http://en.wikibooks.org/wiki/Haskell/Understanding_arrows

Haskell :: Functional Programming with Types
http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html

Functional Languages will Rule (but not this year) – Good Stuff
http://goodstuff.im/functional-languages-will-rule-but-not-this-y

Ruminations of a Programmer: Combinators as the sublanguage of DSL syntax
http://debasishg.blogspot.com/2011/05/combinators-as-sublanguage-of-dsl.html

The Algebra of Data, and the Calculus of Mutation » Lab49 Blog
http://blog.lab49.com/archives/3011

Type inference – Wikipedia, the free encyclopedia
http://en.wikipedia.org/wiki/Type_inference

The Joy of Haskell, parte 1 – Introdução « Ars Physica
http://arsphysica.wordpress.com/2011/04/18/haskell1/

A Neighborhood of Infinity: Generalising Gödel’s Theorem with Multiple Worlds. Part II.
http://blog.sigfpe.com/2010/12/generalising-godels-theorem-with_24.html

The Arrows Calculus
http://homepages.inf.ed.ac.uk/wadler/papers/arrows-jfp/arrows-jfp.pdf

Wadler’s Blog: The Arrow Calculus
http://wadler.blogspot.com/2010/11/arrow-calculus.html

Program Haskell with Lisp Syntax Using Liskell or Lisk
http://www.readwriteweb.com/hack/2010/11/haskell-with-lisp-syntax.php

Lisk – Lisp and Haskell
http://chrisdone.com/posts/2010-11-25-lisk-lisp-haskell.html

johang88′s haskellinjavascript at master – GitHub
http://github.com/johang88/haskellinjavascript

Conal Elliott » “Everything is a function” in Haskell?
http://conal.net/blog/posts/everything-is-a-function-in-haskell/

Haskell: The Confusing Parts
http://echo.rsmw.net/n00bfaq.html

Video presentations – HaskellWiki
http://www.haskell.org/haskellwiki/Video_presentations

A Neighborhood of Infinity: Products, Limits and Parametric Polymorphism
http://blog.sigfpe.com/2010/03/products-limits-and-parametric.html

My Links
http://www.delicious.com/ajlopez/haskell

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

May 3, 2010

AjCoreLisp and MinimaLisp, a minimal Lisp interpreter implementation

As I mentioned in:

AjLisp family: Implementing Lisp Interpreters in C#

I was working written two Lisp interpreters: AjLisp and AjSharpure (a clojure-like interpreter). But I wanted to explore what is the core of the language, the minimal part that should be implemented, in order to have a Lisp interpreter.

Then, I wrote AjCoreLisp. You can download from my Google project

http://code.google.com/p/ajlisp/source/browse/#svn/trunk/AjCoreLisp

It is implemented in C#. The solution:

has five projects:

AjCoreLisp: core class library, implementing the language base, but without parser and lexer, only execution runtime.

AjCoreLisp.Tests: as usual, I developed the library using TDD approach. This is the tests project of the core library.

MinimaLisp: A proof-of-concept lexer, parser, and minimal machine, to show how to use the core library to build a minimal Lisp interpreter.

MiminaLisp.Console: the interactive console interpreter.

MiminaLisp.Test: TDD tests written during the development of MinimaLisp.

The root interface is IExpression:

    public interface IExpression
    {
        object Evaluate(IEnvironment environment);
    }

Any Lisp has list support. The IList interface is:

 

    public interface IList : IExpression
    {
        object First { get; }
        object Rest { get; }
        IList Next { get; }
    }

No update of the list are supported. If you want to add such list, you should derive from this interface, and put the implementation in your extending project, as MinimaLisp. Note that I borrowed from Clojure, the idea of having Rest and Next: the former return an object, the latter presumes the rest of the list is a list itselft.

Every form implements the interface IForm:

    public interface IForm
    {
        object Apply(IEnvironment environment, IList arguments);
    }

Then, the Form class implements IForm and IExpression:

    public class Form : IForm, IExpression
    {
        private IList parameters;
        private IIdentifier parameter;
        private IList body;
        private IEnvironment environment;
        public Form(IList parameters, IList body, IEnvironment environment)
        {
            this.parameters = parameters;
            this.body = body;
            this.environment = environment;
        }
        public Form(IIdentifier parameter, IList body, IEnvironment environment)
        {
            this.parameter = parameter;
            this.body = body;
            this.environment = environment;
        }
// ....
        public object Evaluate(IEnvironment environment)
        {
            return this;
        }
        public virtual object Apply(IEnvironment environment, IList arguments)
        {
            IEnvironment newenv;
            
            if (this.parameter != null)
                newenv = this.MakeNewEnvironmentList(arguments);
            else
                newenv = this.MakeNewEnvironment(arguments);
            return Machine.EvaluateBody(this.body, newenv);
        }
// ....
    }

Note that Form does not evaluate its arguments. That is the job of derived Function class:

    public class Function : Form, IExpression
    {
        public Function(IList parameters, IList body, IEnvironment environment)
            : base(parameters, body, environment)
        {
        }
        public Function(IIdentifier parameter, IList body, IEnvironment environment)
            : base(parameter, body, environment)
        {
        }
        public override object Apply(IEnvironment environment, IList arguments)
        {
            return base.Apply(environment, BaseForm.EvaluateList(arguments, environment));
        }
    }

As usual, macros have a twists: they evaluate its body, and then, evaluates the returned value:

    public class Macro : Form, IExpression
    {
// ...
        public override object Apply(IEnvironment environment, IList arguments)
        {
            object value = base.Apply(environment, arguments);
            value = Machine.Resolve(value, environment);
            return Machine.Evaluate(value, environment);
        }
    }

Ok, enough source code. Look the complete code, for more details. The main point is that AjCoreLisp implements few primitives:

The binding to this primitives is the job of MinimaLisp Machine:

        public MinimalMachine()
        {
            this.Environment.SetValue("first", new First());
            this.Environment.SetValue("rest", new Rest());
            this.Environment.SetValue("cons", new Cons());
            this.Environment.SetValue("quote", new Quote());
            this.Environment.SetValue("define", new Define());
            this.Environment.SetValue("lambda", new Lambda());
            this.Environment.SetValue("flambda", new FormLambda());
            this.Environment.SetValue("mlambda", new MacroLambda());
            this.Environment.SetValue("let", new Let());
            this.Environment.SetValue("letrec", new RecursiveLet());
            this.Environment.SetValue("eval", new Evaluate());
            this.Environment.SetValue("if", new If());
            this.Environment.SetValue("do", new Do());
            this.Environment.SetValue("nil?", new IsNil());
            this.Environment.SetValue("list?", new IsList());
            this.Environment.SetValue("equal?", new IsEqual());
        }

Based on that set, I could write a set of core functions:

(define list x x)
(define definem 
  (mlambda x 
    (list 
      'define 
      (first x)
      (cons 'mlambda (rest x))
    )
  )
)
(define mapfirst (fn lst)
  (if (nil? lst)
    nil
    (cons 
      (fn (first lst)) 
      (mapfirst fn (rest lst))
    )
  )
)
    
(define mapcond (fn lst)
  (if (nil? lst)
    nil
    (if (fn (first lst))
      (cons 
        (first lst) 
        (mapcond fn (rest lst))
      )
      (mapcond fn (rest lst))
    )
  )
)
(define append (x y) (if (nil? x) y (cons (first x) (append (rest x) y))))
  
(definem cond lst
  (if (nil? lst)
    nil 
    (list 
      'if 
      (first (first lst)) 
      (cons 'do (rest (first lst))) 
      (cons 'cond (rest lst))
    )
  )
)
(define atom? (x)
  (cond 
    ((nil? x) t)
    ((list? x) nil)
    (t t)
  )
)
(definem and lst
  (if (nil? lst)
    t
    (list 
      'if 
      (first lst)
      (cons 'and (rest lst))
      nil
    )
  )
)
(definem or lst
  (if (nil? lst)
    nil
    (list 
      'if 
      (first lst)
      t
      (cons 'or (rest lst))
    )
  )
)
(define not (x)
  (if x
    nil
    t
  )
)
(definem backquote (lst) 
  (cond 
      ((nil? lst) nil)
        ((atom? lst) (list 'quote lst))
        ((equal? (first lst) 'unquote) (first (rest lst)))
        ((and (list? (first lst)) (equal? (first (first lst)) 'unquote-slice)) (list 'append (first (rest (first lst))) (list 'backquote (rest lst))))
        (t (list 'cons (list 'backquote (first lst)) (list 'backquote (rest lst))))
  )
)
(definem while lst
  (list 'if (list 'not (first lst)) nil (cons 'do (rest lst)) (cons 'while lst))
)

I'm very proud of my implementation of backquote (macro expansion). That is, these tests are green (note the use of unquote and unquote-slice):

this.EvaluateAndCompare("(backquote (a b c))", "(a b c)");
this.EvaluateAndCompare("(backquote (a (b c) d))", "(a (b c) d)");
this.Evaluate("(define x '(b b))");
this.EvaluateAndCompare("(backquote (a (unquote x) c))", "(a (b b) c)");
this.EvaluateAndCompare("(backquote (a ((unquote x)) c))", "(a ((b b)) c)");
this.EvaluateAndCompare("(backquote (a (unquote-slice x) c))", "(a b b c)");
this.EvaluateAndCompare("(backquote (a ((unquote-slice x)) c))", "(a (b b) c)");
this.EvaluateAndCompare("(backquote (a (unquote-slice x) (unquote-slice x) c))", "(a b b b b c)");

There is no numeric support, then, I wrote numbers using Peano-like ideas, only for tests:

(define succ (x)
  (cons x nil))
  
(define pred (x)
  (first x))
(define add (x y)
  (if (nil? x)
    y
    (add (pred x) (succ y))
  )
)

I didn’t improve the code for a while, but my next step could be refactor AjLisp to be based on this core interpreter. Now, I have a more clear idea of what is needed and what is accesory in a Lisp interpreter.

And, as usual, I had fun written all this code! ;-)

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

April 30, 2010

Working in AjIo: Io-Like interpreter in C#

Filed under: .NET, AjIo, C Sharp, Functional Programming, Open Source Projects — ajlopez @ 12:34 pm

Last year, I discovered Io programming language:

http://www.iolanguage.com/

overview

Io is a prototype-based programming language inspired by Smalltalk (all values are objects, all messages are dynamic), Self (prototype-based), NewtonScript (differential inheritance), Act1 (actors and futures for concurrency), LISP (code is a runtime inspectable/modifiable tree) and Lua (small, embeddable).

It has a simple syntax, and its features are based in functional languages, Smalltalk, Self and others. As usual, I want to write my own version, with a twist: support for native objects. That is, to implement an interpreter over a virtual machine plus class libraries. The current choices are Java or .Net.

Two weeks ago, @MartinSalias pointed me to Io, again. Then, past weekend, I started my own implementation, based only in the written specification. It will be not exactly the same language, and it is still work in progress.

The code is in my Google project AjCodeKata:

http://code.google.com/p/ajcodekatas/

in the trunk, under AjIo folder. There is a .NET solution, with three projects:

The class library is the core, the console program can be used to interact with the interpreter, and the test project has the test I wrote during the design/coding process.

Actually, I have written the lexer, the parser, and the main languages objects, using TDD approach, as usual. You can write:

Some days ago, I implemented the assignment operators (syntax suger over setSlot, newSlot, updateSlot):

but, now, you have native .NET object support:

Next steps:

- Write more comparison operators (I only write ==)
- Native numbers (now, only ints are parsed, but other can be managed, try 1 / 6, it returns a real)
- Precedence in arithmetic operators (now 2 + 2 * 3 returns 12, instead 8)
- for, foreach, range, and more (I only write if())
- block() (I have method())
- include()
- Begin to write some Io library objects

About last point: I should decide how to implements things like:

List clone

Possible approaches:

- List as a derived object (Object clone) with its own slots, wrapping a native list
- List clone returning native ArrayList, then ArrayList type has associated “slots”
- No List, and use directly the native objects

As in AjSharp, original Io has agents and coroutines. I want to add AjSharp features (agents, goroutines, channels, queue channels, futures) to AjIo. Original Io implements agents with virtual machine “threads”: that is, it’s not using operating system threads, the virtual machine executes the many agents code, switching from one code to another during running (I guess, I don’t see the implementation code in Io). I won’t take that approach, in my first attempts.

As usual, I had fun written this stuff!

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

February 25, 2009

Presenting AjLambda: Lambda calculus implementation in C#

Filed under: .NET, C Sharp, Functional Programming, Programming Languages — ajlopez @ 8:21 am

I was working on my “code kate” AjLambda, a Lambda Calculus implementation, written using C#:

http://code.google.com/p/ajcodekatas/source/browse/#svn/trunk/AjLambda

(If you are new to Lambda Calculus notation, there are tutorial links at the end of this post)

Yes! It’s the geeky project I wrote this year…;-).. The solution is simple, it contains three projects:

It has a core library, AjLambda, a test project AjLambda.Tests and an AjLambda.Console program to run. The core library has few main classes:

Expression is the base abstract class. .Reduce is the method that implements the reduction of an expression. .Replaces is used to change a variable by other. Sometimes, it’s needed to choose a new name for a variable, that it doesn’t collides with another free variable name. .FreeVariables is the method to obtain the list of free variables in an expression. For example, in the lambda expression:

\x.xy

x and y are variables, but y is a free variable, and x is a bound parameter.

Variable express the variable (a lower-case letter in this implementation). Lambda is the lamba (parameter plus body). The lambda is entered using:

\x.x

The short version with multiple parameters is supported:

\xy.yx

This is the .Reduce implementation for Pair (a pair of expression, left and right): 

public override Expression Reduce() { if (this.left is Lambda) return ((Lambda)this.left).Apply(this.right); Expression newLeft = this.left.Reduce(); if (newLeft != this.left) return new Pair(newLeft, this.right); Expression newRight = this.right.Reduce(); if (newRight == this.right) return this; return new Pair(newLeft, newRight); }

Running AjLamnda.Console with a parameter:

AjLambda.Console Boot.l

loads the auxiliary file Boot.l, where I defined some predefined functions:

; True
T = \xy.x
; False
F = \xy.y
; And
AND = \ab.abF
; If Then Else
IFTHENELSE = \x.x
; Natural numbers
0 = \fx.x
1 = \fx.fx
2 = \fx.f(fx)
3 = \fx.f(f(fx))
; Succesor
SUCC = \nfx.f(nfx)
; Add
ADD = \nmfx.nf(mfx)
; Multiply
MULT = \nmf.n(mf)
; Is Zero
ISZERO = \nxy.n(\z.y)x
; Predecessor
PRED = \nfx.n(\gh.h(gf))(\u.x)(\u.u)
; Pair Functions
PAIR = \xyf.fxy
FIRST = \p.pT
SECOND = \p.pF
NIL = \x.T
NULL = \p.p(\xy.F)
; Fixed Point
A = \xy.y(xxy)
Y = A A
; Factorial
FACT = Y (\f.\n.IFTHENELSE (ISZERO n) (1) (MULT n (f (PRED n)))))

You can ask about the predefined names. I defined the first natural numbers, including zero:

Names are words that begin with upper case letter. Variable names are lower letter (from ‘a’ thru ‘z’, only one letter per variable).

As usual, I defined SUCC and PRED (succesor and predecessor functions):

Each reduction step is printed, until no more reduce is possible.

You can define new functions using Name = <expression>:

More information about Lambda Calculus at:

Lecture Notes on the Lambda Calculus (pdf) (excellent paper to learn Lambda Calculus)

Peter Selinger- Papers

Lambda calculus – Wikipedia, the free encyclopedia

A Tutorial Introduction to the Lambda Calculus

http://delicious.com/ajlopez/lambda

Lambda Calculus implementation from Fred’s Page

Angel “Java” Lopez
http://www.ajlopez.com/
http://twitter.com/ajlopez

October 9, 2008

F# and Functional Programming Resources

Filed under: .NET, F#, Functional Programming — ajlopez @ 10:13 am

F# is a functional language, created by Microsoft. Implemented under .NET CLR, it’s a typed language, with access to .NET framework. It inherits most of ML/OCaml features.

F# was born in Microsoft Research, and its main creator is Don Syme. Although is a functional language, it supports object programming, too. After years of development, now it’s mature. It’s gaining momentum in scientific community, thanks to its flexibility: it’s not limited to its own library: it can access all .NET framework (The image at left shows F# program running a demo using DirectX from .NET).

Citing Expert F# book promotion at Apress:

While inspired by OCaml, F# isn’t just another functional programming language. Drawing on many of the strengths of both OCaml and .NET, it’s a general–purpose language ideal for real–world development. F# integrates functional, imperative, and object–oriented programming styles so you can flexibly and elegantly solve programming problems, and brings .NET development alive with interactive execution. Whatever your background, you’ll find that F# is easy to learn, fun to use, and extraordinarily powerful. F# will help change the way you think about and go about programming.

There is lot of information about the language. This post is a collection of links, blogs, posts, resources, books, about this very interesting language.

Links

The first page to visit  Microsoft F# Home page:

Microsoft Research’s website for F#
F# Manual
F# Documentation

There are blogs and forums at
hubFS- The place for F# – F# news, forums and blogs

Personal blogs with F# info:
Don Syme’s web log, a key source of information on F#
Robert Pickering’s blog
Tomas Petricek
Granville Barnett’s blog
Luke Hoban’s blog
Chris Smith (F# Tester)
Brian McNamara (F# Dev)
Jomo Fisher (F# Dev)
Andrew Kennedy (MSR)
Luca Bolognese (Managed Languages Principal PM)

Harry Pierson has written many post about functional programming, C# and F#:
DevHawk Functional Programming category

Posts and podcasts

Some links to blog posts (there are hundreds in the above links), only to taste the language and its power:

Episode 18- Matt Podwysocki on F# and Functional Programming Herding Code
Matt Podwysocki puts the fun in functional programming with a deep dive into F#.

Concurrency on a single thread
F# has the async computation expression for writing parallel programs.

F# September 2008 CTP Released
The F# Team has released the F# September 2008 CTP. 

F# Overview (I.) – Introduction Articles TomasP.Net

Functional Understanding

Practical F# Parsing- The Parse Buffer

Play Ball Script in F#

Units of Measure in F#- Part One, Introducing Units

The Weekly Source Code 34 – The Rise of F#

To listen

Herding Code 18- Matthew Podwysocki on F# and Functional Programming
Software Engineering Radio Episode 108 – Simon Peyton Jones on Functional Programming and Haskel
.NET Rocks Episode 310 – Simon Peyton Jones on Functional Programming and Haskell

Examples

F# Samples – Home
Ant Colony Simulation
FsTest
FsUnit

F# Books

  Foundations of F#

Every professional .NET programmer needs to learn about FP, and there’s no better way to do it than by learning F#–and no easier way to learn F# than from Foundations of F#. Written by F# evangelist Rob Pickering, this is an elegant, comprehensive introduction to all aspects of the language and an incisive guide to using F# for real-world professional development.

by Robert Pickering | ISBN-13: 978-1-59059-757-6 | Published May 2007 | 360pp.

 

 Expert F#

Written by F#’s inventor and two major contributors to its development, Expert F# is the authoritative, comprehensive, and in–depth guide to the language and its use. Designed to help others become experts, the first part of the book quickly yet carefully describes the F# language. The second part then carefully shows how to use F# elegantly for a wide variety of practical programming tasks.

by Don Syme, Adam Granicz, Antonio Cisternino | ISBN-13: 978-1-59059-850-4 | Published Dec 2007 | 609pp.

Another book by Jon Harrop: 

F# for Scientists

F# for Scientists will bring you up to speed with basic syntax and programming language concepts. Written in a clear and concise style with practical and enlightening examples, this book is accessible and easy to understand. By reviewing the Visual Studio screen shots that illustrate compilation, debugging and interactive use, you will understand both the functional aspects of F# and the object-oriented task-based features that make F# so useful in practice.

Functional Programming

If you are looking for functional programming in general:

Functional Programming for the Rest of Us

Why Functional Programming Matters a classic by John Hughes

Why Haskell Matters

The classic paper by Backus backus.pdf

A “potpurry” of links:

Are FP and OO Incompatible Syntactic Styles-
A Gentle Introduction to Haskell, Version 98
About Erlang
APL (programming language) (one of my first encounter with FP)
An APL Compiler (Timothy Budd book)
The Cat Programming Language
YouTube – Tangible Functional Programming
Functional Programming Notables #1 (more links to FP)
The Little MLer
functional objects Felleisen
Erlang in Lisp
Free Online Functional Programming Books — FreeTechBooks.com
The Expression Lemma (very geek, category theory, functional programming and LINQ!!)
Chaitin’s construction (more geeky, more category theory, Chaitin visited my country many times, he’s argentinian)
On being stateful
The Glasgow Haskell Compiler
A Neighborhood of Infinity- You Could Have Invented Monads! (And Maybe
InfoQ- Domain Specific Languages in Erlang

Functional C#

.NET and C# are moving to functional style. All you want to know about programming functional C# at Mattew Podwysocki post:

Richmond Code Camp 2008.2 – Functional C# Recap

Other links:

Functional C# Project
Is C# Becoming a Functional Language- – Mads Torgersen
Functional C# – Learn from F# and LINQ

My Delicious

As usual, the links I found useful are added to my delicious. Check:

http://delicious.com/ajlopez/fsharp
http://delicious.com/ajlopez/f%23
http://delicious.com/ajlopez/functionalprogramming
http://delicious.com/ajlopez/haskell
http://delicious.com/ajlopez/erlang

Angel “Java” Lopez
http://www.ajlopez.com/en
http://twitter.com/ajlopez
http://delicious.com/ajlopez

August 13, 2008

Closures in F#

Filed under: .NET, F#, Functional Programming — ajlopez @ 11:30 am

In my previous post about F#:

First steps in F#

I declared that there is no variable in the language, instead, we talk about identifiers. Why? Let’s explore the concept of closure, and how is used in F#.

According to Wikipedia article about closures in computer science:

a closure is a function that is evaluated in an environment containing one or more bound variables

But, what does this mean? To reveal its meaning, let’s assign a value to an identifier, using fsi.exe, the F# interactive interpreter:

MSR F# Interactive, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.9.3.4, compiling for .NET Framework Version v2.0.50727

NOTE:
NOTE: See ‘fsi –help’ for flags
NOTE:
NOTE: Commands: #r <string>; reference (dynamically load) the given DLL.
NOTE: #I <string>; add the given search path for referenced DLLs.

NOTE: #use <string>; accept input from the given file.
NOTE: #load <string> …<string>;
NOTE: load the given file(s) as a compilation unit.
NOTE: #time;; toggle timing on/off.
NOTE: #types;; toggle display of types on/off.
NOTE: #quit;; exit.
NOTE:
NOTE: Visit the F# website at
http://research.microsoft.com/fsharp.
NOTE: Bug reports to fsbugs@microsoft.com. Enjoy!

> let x = 2;;

val x : int

Now, we have an identifier named x. We can show its value:

> x;;
val it : int = 2

A simple integer. Now, we cannot change its value: this identifier was carved in stone as an integer 2. Nothing in the human history could change its value. Is it true? Let’s define a function:

> let dup n = n * x;;

val dup : int -> int

This function dup takes an argument n and multiplies it by the value of identifier x. This identifier is a free “variable” in the function. During the evaluation of the function, x takes its value from the environment. Let’s try now:

> dup 3;;
val it : int = 6

The result was six, as expected. But now, let’s “change” the value of x:

> let x = 3;;

val x : int

> x;;
val it : int = 3

But this is the point to understand closures: this “x” is ANOTHER identifier, that it shadows the previous one. BUT, for the function dup, the identifier x is STILL the previous one. Let’s try again to invoke the function:

> dup 3;;
val it : int = 6

The dup still uses the original x!! That’s the closure in action. If we try:

> dup;;
val it : (int -> int) = <fun:clo@0>

Note the clo @ 0 : its the signature of the closure this function is using. It points to the original environment where the function was defined.

This feature implies that the behaviour of a function doesn’t change after its definition. Even the apparently “free variables” are bounded at definition time. All this is part of the solid fundations of functional programming, in general, and F#, in particular.

About closures and related concept, lambdas, these are the seminal papers:

The Original ‘Lambda Papers’ by Guy Steele and Gerald Sussman

You can learn a lot about Lisp, and closures/lambdas, visiting:

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

 

I implemented some lambdas and closures, in my Lisp interpreter:

AjLisp: a Lisp interpreter in .NET

More C# related stuff about closures:

What’s In A Closure?
Fibonacci Numbers, Caching and Closures

Angel “Java” Lopez
http://www.ajlopez.com/en

August 11, 2008

First steps in F#

Filed under: .NET, F#, Functional Programming, Programming Languages — ajlopez @ 12:22 pm

The F# language has been under development in Microsoft Research. Its main creator is Don Syme. You can visit the F# web site:

http://research.microsoft.com/fsharp/fsharp.aspx

A comment from that site:

Combining the efficiency, scripting, strong typing and productivity of ML with the stability, libraries, cross-language working and tools of .NET.

F# is a programming language that provides the much sought-after combination of type safety, performance and scripting, with all the advantages of running on a high-quality, well-supported modern runtime system.

The last published version, up today, is:

F# 1.9.4.19 realease announcement

Installing F#

You can download a .msi file, or a .zip one. The .msi is an installer program, that install F# compiler, and F# for Visual Studio. I installed the 1.9.3.4 version in my machine. This is one of the screen from my past year installation:

 

 

The last step could take many minutes. It install the support of F# inside Visual Studio. You can use VS or, alternative, a F# command line compiler and interpreter. The F# programs can be launched from Mono, then you can write F# code under Linux.

At the end of install, a folder is created c:\Program Files\FSharp-<version> (it has a .sh file to install the tools in Mono).

There is a new program menu:

The fsi interpreter

We can use an interactive tool, that is the F# interpreter at bin\fsi.exe:

C:\Program Files\FSharp-1.9.3.4\bin>fsi MSR F# Interactive, (c) Microsoft Corporation, All Rights Reserved F# Version 1.9.3.4, compiling for .NET Framework Version v2.0.50727 NOTE: NOTE: See 'fsi --help' for flags NOTE: NOTE: Commands: #r <string>;; reference (dynamically load) the given DLL. NOTE: #I <string>;; add the given search path for referenced DLLs. NOTE: #use <string>;; accept input from the given file. NOTE: #load <string> ...<string>;; NOTE: load the given file(s) as a compilation unit. NOTE: #time;; toggle timing on/off. NOTE: #types;; toggle display of types on/off. NOTE: #quit;; exit. NOTE: NOTE: Visit the F# website at http://research.microsoft.com/fsharp. NOTE: Bug reports to fsbugs@microsoft.com. Enjoy!

Using let

Let’s enter

> let x = 10;;

We get at output:

val x : int

The ;; makes the program to compile and execute the entered commands. In this command, x is an identifier, that has an integer value. F# is a typed language. We didn’t define the type of the identifier x: it was inferred automatically from the value we put in it. Let’s note that is an identifier, not a variable. Once an identifier is set, we can’t change its value. That is a distinctive feature of functional programming in general. I’ll explore that behavior in future posts.

Now, let’s enter

> x;;

(the > was added by the program, it’s the fsi’s prompt) We get

val it : int = 10

The fsi program prints the expression and its type. it is the name that it uses when we don’t speficy a target identifier.

Defining functions

Using the same let, we can define functions:

>  let dup x = x * 2;;
val dup : int -> int

For F#, values and functions are the same. A function is a first class citizen in the F# language, and it can be manipulated as any other value.

The second line above shows that dup is a function that receives an integer and returns another integer. The identifier dup now points to that function. It is its value.

We can apply the function entering:

> dup 10;;
val it : int = 20

A function is a value, we can pass a function as a parameter:

> let apply f x = f (f x);;
val apply : (‘a -> ‘a) -> ‘a -> ‘a

The result is something more cryptic. The term ‘a refers to a undefined type. It could be an integer, or an string, or something else. But if we give an integer as second parameter to apply, the first one MUST BE a function that takes an integer and returns another integer. Don Syme, the creator of F#, was involved in the definition and implementation of generics in .NET 2.x. One could think he implemented that features to create the F# language… ;-)

If we entered

> apply dup 2;;

then we get

val it : int = 8

that is the same that

> dup (dup 2);;

Conclusion

For those who are not familiar with functional programming, the concept of a function as a first class value, citizen with the same rights and duties of a value, could sound something strange. But if you can grasp the base of this approach, you’ll appreciate the advantages of this path (the appearance of lambda and delegates in mainstream .NET is an example of such adoption). If you have seen a Lisp or other functional implementation, all this sounds as a deja vu for you.

The interesting part of F# is that not only supports the functional programming paradigm but also interacts with the rest of the .NET framework. Then, F# is not an “academic” language, only related to itself, but was adopted in many projects. Although I was dealing with the command line interpreter in this post, we can use the Visual Studio, leveraging debugging, projects, and editors.

Enjoy F#!

Angel “Java” Lopez
http://www.ajlopez.com/en

« Newer Posts

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 28 other followers