read


read
or learn more

Broccoli version 0.0.b

Mar 11, 2008

I’m chugging along on the Broccoli interpreter adding the following:<br/>

fast lists

Lists are backed by arrays now, so random access is O(1). I was considering making an extra array type, but the array-backed list will work just as well and keep the type system cleaner.

for loops

I have added a for loop that works as both a list iterator and a range iterator. I was considering using only the former form, but that would have been a bit messy behind the scenes in the way that the recognition of ranges would need to occur. The BNF of the for loop is as follows:<br/> List iteration form:<br/>

<list iteration for>    ::= (for <scalar-variable> in <list> <expression>*)

Range iteration form:<br/>

<range iteration for>   ::= (for <scalar-variable> in <start-index> to <end-index> <expression>*)
<start-index>    ::= <integer> | <scalar-variable>
<end-index>      ::= <integer> | <scalar-variable>

<br/> In the list iteration case, the scalar-variable will be the currently indexed element in the list. In order to obtain the current index count for this case, the special variable <scalar-variable>-index is provided. In the range iteration case, the scalar-variable is the loop index.<br/>

if-then-else

Basic if-then-else statements are provided of the form:

<if-then-else>    ::= (if <boolean-condition> <expression>* else <expression>)

functions

Functions are now provided. Recursion is possible, although tail-recursion will trash the stack at around 16K calls deep.<br/> Functions take the form:<br/>

<function>   ::= (fn <name> (<parameter>*) <expression>*)
<name>       ::= <symbol>
<parameter>  ::= <symbol>

<br/>

An example of the solution for your Week 1 undergrad C.S. assignment would therefore be:

(fn fib ($num)
    (if (< $num 2)
        $num
    else
        (+ (fib (- $num 1)) (fib (- $num 2)))
    )
)

(fn fact ($num)
    (if (== $num 0)
        1
    else
        (* $num (fact (- $num 1)))
    )
)

-m

No Comments, Comment or Ping

Reply to “Broccoli version 0.0.b”