Friday, July 31, 2009

A small project I'm working on

I'm currently working on a small project that's turned out pretty well. A functional language: It's basically lisp with pattern-matching grafted onto it. This has turned out to make the language very powerful. Nearly nothing needs to come built-in, except the definition, matching and expansion of patterns.

To explain the code examples in this post, I'll first outline the rough grammar of the definition statement.

The overall grammar is the following:
define ( pattern ) name expansion.

In the pattern, atoms may be prefixed with
~
Not to be evaluated until it is absolutely unavoidable (otherwise, they are evaluated on an as-needed basis)
@
Only allowed in the last atom, meaning that it is to correspond with what is left on the stack
=
Matching against the following token, and only the following token


In the expansion, the only prefix that exists is @, which appends the token onto the stack, instead of adding a list cell pointing to the value on the stack.


Some examples of the language.
Basic lisp-style arithmetics
( + 23 14 ( * 7 2 ) ) 


Conditional evaluation:
define ( =true @statement ) if   @statement.
define ( other @statement ) if .


Factorial function:
define ( 0 ) fac 1 .
define ( n ) fac ( * n ( fac ( + n -1 ) ) ).


Map function:
define ( ( @op ) ( top @rest ) ) map
( @op top ) map op rest.
define ( ( @op ) ( last ) ) map
( @op last )


Mapping factorial function to some numbers:
print ( map ( fac ) ( 1 2 3 4 5 6 7 8 9 10 ) ).
( 1 2 6 24 120 720 5040 40320 362880 3628800 )


Mapping a lambda function corresponding to squaring to same numbers:
print ( map ( ,\ ( x ) ( * x x ) )  ( 1 2 3 4 5 6 7 8 9 10 ) ) .
( 1 4 9 16 25 36 49 64 81 100 )


A more complicated example:
define ( ( a @as ) ( b @bs ) ) zip 
( a b ) zip as bs .
define ( ( a ) ( b ) ) zip
( a b ) .
define ten ( 1 2 3 4 5 6 7 8 9 10 )
print ( zip ( map ( fac ) ten ) ten ) .
( ( 1 1 ) ( 2 2 ) ( 6 3 ) ( 24 4 ) ( 120 5 ) ( 720 6 ) ( 5040 7 )
( 40320 8 ) ( 362880 9 ) ( 3628800 10 ) )

I'll post more details later. Mostly because the details are in such heavy flux right now.

1 comment: