/concatenative-php

Concatenative-PHP, a lightweight functional language built on PHP.

Primary LanguagePHPOtherNOASSERTION

This document will attempt to explain all of the language features.

Statements

Statements are laid out in postfix notation. That is, in PHP the tokens are parsed left to right and the function call comes first (i.e. foo(x,y) ). Lisp is similar to this, but the parenthesis comes before the function name and the parameters are delimited by spaces (i.e. (foo x y) ). This language also delimits with spaces (same as Lisp) but switches the order from right to left and removes the requirement for parentheses too. (i.e. y x foo).

3 3 + 2 - println
( prints 4 )

"Hello world" println
( prints "Hello world" )

Comments

Comments are denoted by being enclosed between parenthesis.

( This is a comment )

Quotation (lambda) functions

Whether you want to call them partial functions, curried functions, lambdas, thunks or, as they are known in the Forth community quotations, you can define them with square brackets.

[ dup * ]

And these can be called with the call word, or passed around.

3 [ dup * ] call println

: deferred-square ( -- quot ) 
  [ dup * ] ;

: foo ( -- value ) 
  3 deferred-square ;

foo
( prints 9 )

Arrays

Arrays are trivial to define, all of the following are valid arrays:

{ 1 2 3 }                        ( simple array )

{ 2 3 { 1 2 3 } }                ( nested array )

{ "WI" => "Wisconsin"            ( associative array )
  "IL" => "Illinois" }

{ "square" => [ dup * ]          ( array of qoutations )
  "cube"   => [ dup dup * * ] }

Defining functions

You may have already noticed, but you can define functions using the colon word. The syntax is as follows:

: <name> (<comment>) <definition> ;

When that word appears in the syntax it will be called immediately unless it is in a function defininition or inside square brackets.

Conditional operations

{ 'rtf' => "Rich Text Format"
  'doc' => "Microsoft Document Format"
  'xml' => "Extensible Markup Language"
} 'rtf' cond println 
( prints "Rich Text Format" )

Objects

This language uses a prototype based OOP model. You might be familiar with this model if you've written javascript.

( Here we define a new class, mainly for compatability with PHP )
Document class 

This extends the basic Prototype object and lets the rest of the runtime be aware of the Document class. To instantiate the new object we can do the following.

: my-document ( -- doc ) 
  { 'title'  => 'An introduction to Concatenative PHP' 
    'author' => 'Garrett Bluma'
    'hiFive' => [ "Hi Five" echo ] 
  } Document new ;

Here we define a couple properties (title and author) while also defining a member function on our object (hiFive). We tell the system that we want it to be of the Document class, we name it my-document and then kick off the instantiation process with new.