Calico Scheme

From IPRE Wiki
Revision as of 05:09, 8 December 2014 by Doug Blank (Talk | contribs)

Jump to: navigation, search

Here we will provide documentation for using Calico and Calysto Scheme version 3.0.0

Calico Scheme is a new implementation of a Scheme-based language for Calico. It implements many core Scheme functions, but also adds some functionality to bring it into line with the other modern languages like Python and Ruby. In can run inside Calico as a DLL.

Calysto Scheme is a transformation of Calico Scheme into Python. You can see Calysto Scheme here: https://github.com/Calysto/calysto/tree/master/calysto/language/scheme

You can install Calysto Scheme with:

pip install calysto

To use with IPython/Jupyter:

pip install calysto-scheme

You can see many examples using Calysto Scheme in IPython/Jupyter notebooks:

The Scheme in C# can be found in Calico, installed from here:

Calico Download

Contents

Starting Scheme

Example:

$ ipython console kernel --calysto_scheme
Calysto Scheme, version 3.0.0
----------------------------
Use (exit) to exit
==>

To run in Calico:

  1. Calico Download
  2. Run in gui
  3. Run from command-line

Example:

$ calico --repl --lang=scheme
Loading Calico version 3.0.0...
scheme>

From either, Enter expressions such as "(+ 1 1)". Control+d will exit.

Scheme Extensions

Calico Scheme is the beginning of a complete Scheme, but is currently missing many functions (see scheme issues in our issue tracker). Even still, we have added some extensions to Scheme, including:

  1. allows doc-strings on any defined item
  2. can trace executing expressions in Calico GUI
  3. shows stack traces (that look like Python's) on exceptions (turn off with (use-stack-trace #f))
  4. Exceptions - implements try/catch/finally
  5. implements non-deterministic choose/fail
  6. Modules and namespaces - implements namespaces for imports and foreign objects
  7. import libraries written for Python (in the Python version), or CLR (in the C# version)
  8. Interop - ways for Scheme to interop with other Calico languages

Types

literals

Literals are self-evaluating values in Scheme. Quoting them is not necessary, and does not change them.

  1. numbers
  2. characters
  3. strings
  4. booleans

numbers

There are 4 types of numbers in Calico Scheme:

  1. integers
  2. BigIntegers - automatically moves to BigIntegers when overflow occurs
  3. floating point numbers
  4. rationals

booleans

Boolean values consist of #t (true) and #f (false). In testing (eg, if, cond), anything that is not #f is considered true. That means that 0 and '() are both considered true.

symbols

Symbols are created using either a preceding single-quote character, or by using the (quote ...) form.

Examples:

'thing
(quote thing)

Symbols with the same name represent the same object. That means (eq? 'x 'x) returns #t.

'() is a special symbol, pronounced "the empty list".

Commands

The following are the functions, syntax, and special forms for Calico Scheme.

%

(% ...)

Modulo gives the amount left over after a divide.

Example:

(% 10 3) => 1

*

(* ...)

Multiply will take a number of arguments and give you the total of all numbers multiplied with each other.

Examples:

(*) => 1

(* 12) => 12

(* 2 3) => 6

(* 2 3 4) => 24

+

(+ ...)

Addition will take a number of arguments and give you the sum of all of the numbers added together.

Example:

(+ 7 8) => 15

-

(- ...)

Subtraction will subtract one number from another.

Example:

(- 5 2) => 3

/

(/ ...)

Divide will divide one number from the previous.

Examples:

(/) => 1

(/ 2) => 1/2

(/ 3 4) => 3/4

<

(< ...)

Less than will return #t or #f as to whether the first number is less than the second.

Example:

(< 5 2) => #f

<=

(<= ...)

Less than or equal than will return #t or #f as to whether the first number is less than, or equal to, the second.

Example:

(<= 5 6) => #t

=

(= ...)

Equality for numbers.

Example:

(= 6 7) => #f

>

(> ...)

Greater than will return #t or #f as to whether the first number is greater than the second.

Example:

(> 9 2) => #t

>=

(>= ...)

Greater than or equals will return #t or #f as to whether the first number is greater than or equal to the second.

Example:

(>= 4 5) => #f

abs

(abs ...)

Returns the absolute value of the number.

Example:

(abs -1) => 1

and

(and ...)

And will return #f as soon as it encounters a #f in the items (eg, it short circuits without further evaluation of arguments). If no #f is encountered, it returns the last item.

Examples:

(and 4 1 2 #t (quote ()) 0) => 0

(and 4 1 2 #t '() 3) => 3

(and 4 1 2 #f '() 0) => #f

append

(append ...)

Append takes a number of lists and combines them. The last item can be an atom, in which case it returns an improper list.

Examples:

(append (quote (1 2 3)) (quote (4 5 6))) => (1 2 3 4 5 6)

(append '(1 2 3) '(4 5 6)) => (1 2 3 4 5 6)

(append '(1 2 3) '(4 5 6) '(7 8 9)) => (1 2 3 4 5 6 7 8 9)

(append '(1 2 3) '(4 5 6) 7) => (1 2 3 4 5 6 . 7)

apply

(apply f args)

Apply takes a function and applies it to a list of arguments. (apply f '(1 2)) operates as if it were written (f 1 2).

Examples:

(apply car (quote ((1)))) => 1

(apply car '((1))) => 1

assq

(assq ...)

Find an association using the eq? operator. Given an item, look it up in a list of pair of associations.

Examples:

(assq 1 (quote ((1 2) (3 4)))) => (1 2)

(assq 1 '((1 2) (3 4))) => (1 2)

assv

(assv ...)

Find an association using the eqv? operator. Given an item, look it up in a list of pair of associations.

Examples:

(assv 1 (quote ((1 2) (3 4)))) => (1 2)

(assv 1 '((1 2) (3 4))) => (1 2)

atom?

(atom? item)

Returns #t if item is an atom.

Example:

(atom? 1) => #t

boolean?

(boolean? item)

Returns #t if item is a boolean (#t or #f) and #f otherwise.

Examples:

(boolean? #t) => #t

(boolean? #f) => #t


callback

(callback args body)

For use with event-oriented host APIs.

car, cdr and related

Given one of these functions and a list, it will return part of the list.

(car ...)

Examples:

(car '(a b)) => a

(car '(a . b)) => a

(car '((a) b) => (a)

(car (quote (((((hello there) this is a test) what is this) another item) in the list))) 
     => ((((hello there) this is a test) what is this) another item)

(cdr ...)

Returns everything in a list, except the car.

Examples:

(cdr '(a b)) => (b)

(cdr '(a . b) => b

(cdr (quote (((((hello there) this is a test) what is this) another item) 1 2 3))) => (1 2 3)

(caaaar list)

Is the same as (car (car (car (car list)))).

Examples:

(caaaar (quote (((((hello there) this is a test) what is this) another item) in the list))) => (hello there)

(caaaar '(((((hello there) this is a test) what is this) another item) in the list)) => (hello there)

(caaadr ...)

Example:

(caaadr (quote (((((hello there) this is a test) what is this) another item) 
            ((((((1 2 3) 4 5 6) 7 8 9) 10 11 12) 13 14 15) 16 17 18)))) 
=> ((((1 2 3) 4 5 6) 7 8 9) 10 11 12)

(caaar ...)

Example:

(caaar (quote (((((hello there) this is a test) what is this) another item) in the list))) => ((hello there) this is a test)

(caadar ...)

Example:

(caadar (quote (((((hello there) this is a test) what is this) (((1 2 3) 4 5 6) 7 8 9) another item) in the list))) 
   => ((1 2 3) 4 5 6)

(caaddr ...)

Example:

(caaddr (quote (((((hello there) this is a test) what is this) (((1 2 3) 4 5 6) 7 8 9) another item) head ((1 2) 3 4) in the list))) => (1 2)

(caadr ...)

Example:

(caadr (quote (((((hello there) this is a test) what is this) (((1 2 3) 4 5 6) 7 8 9) another item) (in this) ((7 8)) the list))) 
=> in

(caar ...)

Example:

(caar (quote (((((hello there) this is a test) what is this) another item) in the list))) 
=> (((hello there) this is a test) what is this)

(cadaar ...)

Example:

(cadaar (quote (((((hello there) this is a test) (what) is this) (yet another) item) in the list))) => (what)

(cadadr ...)

Example:

(cadadr (quote (((((hello there) this is a test) what is this) (yet another) item) (in the) list))) => the

(cadar ...)

Example:

(cadar (quote (((((hello there) this is a test) what is this) (yet another) item) in the list))) => (yet another)

(caddar ...)

Example:

(caddar (quote (((((hello there) this is a test) what is this) another item) in the list))) => item

(cadddr ...)

Example:

(cadddr (quote (((((hello there) this is a test) what is this) another item) in the list))) => list

(caddr ...)

Example:

(caddr (quote (((((hello there) this is a test) what is this) another item) in the list))) => the

(cadr ...)

Example:

(cadr (quote (((((hello there) this is a test) what is this) another item) in the list))) => in

(cdaaar ...)

Example:

(cdaaar (quote (((((hello there) this is a test) what is this) another item)))) => (this is a test)

(cdaadr ...)

Example:

(cdaadr (quote (((((hello there) this is a test) what is this) another item) ((7 8)) 9 10))) => (8)

(cdaar ...)

Example:

(cdaar (quote (((((hello there) this is a test) what is this) another item)))) => (what is this)

(cdadar ...)

Example:

(cdadar (quote (((((hello there) this is a test) what is this) (another two) items)))) => (two)

(cdaddr ...)

Example:

(cdaddr (quote (((((hello there) this is a test) what is this) another item) 1 (2 5) 3 4))) => (5)

(cdadr ...)

Example:

(cdadr (quote (((((hello there) this is a test) what is this) another item) (1 6) (2 5) 3 4))) => (6)

(cdar ...)

Example:

(cdar (quote (((((hello there) this is a test) what is this) another item)))) => (another item)

(cddaar ...)

Example:

(cddaar (quote (((((hello there) this is a test) what is this) another item) 1 (2) 3))) => (is this)

(cddadr ...)

Example:

(cddadr (quote (((((hello there) this is a test) what is this) another item) (7 13) (8 12) 9 10))) => ()

(cddar ...)

Example:

(cddar (quote (((((hello there) this is a test) what is this) another item)))) => (item)

(cdddar ...)

Example:

(cdddar (quote (((((hello there) this is a test) what is this) another item)))) => ()

(cddddr ...)

Example:

(cddddr (quote (((((hello there) this is a test) what is this) another item) 1 2 3 4 5))) => (4 5)

(cdddr ...)

Example:

(cdddr (quote (((((hello there) this is a test) what is this) another item) 1 2 3 4))) => (3 4)

(cddr ...)

Example:

(cddr (quote (((((hello there) this is a test) what is this) another item) 1 2 3))) => (2 3)

case

(case ...)

For use in handling different cases. Returns the first expression that matches. "else" acts as it were #t (always matches). If nothing matches, #f is returned.

Examples:

(case 'thing1 
   (thing2 1) 
   (thing1 2))           => 2

(case 'thing1 
   (thing2 1) 
   ((thing1 thing3) 2))  => 2

(case 'thingx 
   (thing2 1) 
   ((thing1 thing3) 2) 
   (else 3))             => 3
(let ((r 5)) 
  (case (quote banana) 
    (apple (quote no)) 
    ((cherry banana) 1 2 r) 
    (else (quote no))))      => 5

cd/current-directory

(cd ...)
(current-directory)

Change/current directory. Given a string, will change to that directory. If you leave out the argument, it returns the current directory.

Example:

(cd)                    => ""
(cd "..")               => moves up one directory

char->integer

(char->integer ...)

Converts a character into an integer.

Example:

(char->integer #\a) => 97

char->string

(char->string ...)

Converts a character into a string.

Example:

(char->string #\b) => "b"

char-alphabetic?

(char-alphabetic? c)

Is c an alphabetic character?

Examples:

(char-alphabetic? #\A) => #t

(char-alphabetic? #\1) => #f

char-numeric?

(char-numeric? c)

Is c an numeric character?

Example:

(char-numeric? #\1) => #t

char-whitespace?

(char-whitespace? ...)

Is c a whitespace (e.g. tab, space, newline) character?

Example:

(char-whitespace? #\t) => #f

(char-whitespace? #\tab) => #t

(char-whitespace? #\newline) => #t

(char-whitespace? #\a) => #f

char=?

(char=? ...)

Returns #t if two characters are the same.

Example:

(char=? #\a #\a) => #t

(char=? #\a #\b) => #f

char?

(char? item)

Is item a character?

Example:

(char? 2) => #f

cond

(cond ...)

Asks a series of questions, and if true, returns the associated expression. "else" acts as if it were "#t".

Example:

(cond 
   (#f 1) 
   (else 2))        => 2

cons

(cons item1 item2)

Constructs a new cons cell by cons-ing item1 onto item2. A proper list ends in the special symbol, '() pronounced "empty list". An improper list ends with a dot, followed by the last item.

Examples:

(cons 1 '())      => (1)

(cons 1 2)        => (1 . 2)

current-environment

(current-environment)

Get the current environment.

Example:

(current-environment)                  => the current environment

current-time

(current-time)

Returns the current time.

Example:

(current-time) => 1397405584.229055

cut

(cut ...)

The (cut) operation will succeed, but cannot be back-tracked afterwards.

Example:

(letrec ((loop (lambda (n) (if (= n 0) (set! var (cut 23)) (loop (- n 1))))) (var 0)) (loop 10) var) => (23)

define

(define variable value)

Define is used to create global variables, whether they have a value or function bound to them.

Examples:

(define x 1)
(define f (lambda (n) n))

You may also use the MIT form:

(define (function args ...) body)

One final alternative is to allow a doc-string when defining any item:

(define function
    "This is a useful bit of text regarding function"
    (lambda (n)
        n))

(define speed "this is the speed in km/sec" 34)

define!

(define! variable value)

Define! is used to create variables in the hosting environment (Python or C#), whether they have a value or function bound to them. If you define! a function, Calico Scheme will automatically wrap it in a manner that is appropriate for the hosting environment. Note that this turns a Scheme function into a stack-based function in the host environment.

Examples:

(define! x 1)
(define! f (lambda (n) n))

dict

(dict ...)

Make a dictionary.

Example:

(dict (quote ((1 2) (3 4)))) => none

dir

(dir ...)

Object properties and environment variables.

==> (dir)
(- % * / + < <= = =? > >= abort abs and append apply assq assv atom? boolean? caaaar caaadr caaar caadar 
caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call/cc call-with-current-continuation 
car case cases cd cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr 
cddr cdr char? char=? char-alphabetic? char-numeric? char-whitespace? cond cons current-directory 
current-environment current-time cut debug define-datatype dir display eq? equal? eqv? error eval 
eval-ast even? exit float for-each format get get-member globals import int iter? length let let* letrec 
list list? list->string list->vector list-head list-ref list-tail load load-as make-set make-vector map member 
memq memv newline not null? number? number->string odd? or pair? parse parse-string print printf 
procedure? property quotient range rational read-string record-case remainder require reset-toplevel-env 
reverse safe-print set-car! set-cdr! sort sqrt string string? string<? string=? string->list string->number 
string->symbol string-append string-length string-ref string-split substring symbol symbol? symbol->string 
typeof unparse unparse-procedure use-lexical-address use-tracing vector vector? vector->list 
vector-ref vector-set! void zero?)
==> (dir my-stuff)
(x y z)

You can also use dir on an object:

(import "Myro")
(dir Myro)

Example:

(length (dir)) => 170

eq?

(eq? ...)

Tests if two object are the same.

Example:

(eq? (quote a) (quote a)) => #t

equal?

(equal? ...)

Tests if two things evaluate to the same value.

Example:

(equal? 1 1.0) => #t

eqv?

(eqv? ...)

Slightly less strict than eq?.

Example:

(eqv? 1 1) => #t

error

(error name message)

Throw an exception. See also the try/catch examples below.

Example:

(try (error (quote a) "message") (catch e (cadr e))) => "Error in 'a': message"

eval

(eval item)

Evaluate an expression.

Example:

(eval '(+ 1 2)) => 3

eval-ast

(eval-ast ...)

Evaluate an abstract syntax tree.

Example:

(eval-ast (parse (quote (+ 3 4)))) => 7

even?

(even? number)

Returns #t if a number is even.

Example:

(even? 33) => #f

float

(float number)

Returns a floating point version of a number.

Example:

(float 23) => 23.0

for-each

(for-each f sequence)

Maps a function f onto a sequence, but doesn't return anything. Sequence can be a string, list, vector, or other iterator. for-each is used for its side-effects.

Example:

(for-each (lambda (n) (+ n 1)) (quote (1 2 3))) => <void>

format

(format message arg ...)

Formats a message using the following special codes:

  • ~a - "any", prints as display does
  • ~s - "s-expression", prints as write does
  • ~% - newline

Example:

(format "~a ~s ~%" "hello1" "hello2") outputs: hello1 \"hello2\" 

get-stack-trace

(get-stack-trace)

Gets the current stack trace. You can disable stack traces with (use-stack-trace #f).

Example:

(caddr (cadar (get-stack-trace))) => 69

import

(import <string-exp>)
(import <string-exp> '<symbol-exp>)

Importing a modules provide an easy method for structuring hierarchies of libraries and code.

Examples:

==> (import "my-file.ss")

my-file.ss is a Scheme program file, which itself could have imports.

==> (import "my-file.ss" 'my-stuff)

Loads the file, and puts it in the namespace "my-stuff" accessible through the lookup interface below.

import uses the local environment, while load uses the toplevel-environment.

Lookup imported names:

module.name
module.module.name
==> (import "my-file.ss" 'my-stuff)
==> my-stuff.x
5

int

(int number)

Returns an integer form of the number. Note that this rounds to the nearest integer.

Example:

(int 12.8) => 13

integer->char

(integer->char ...)

Converts an integer to a character.

Example:

(integer->char 97) => #\a

iter?

(iter? item)

Returns #t if item is an iterator.

Example:

(iter? 3) => #f

lambda

(lambda ...)

Create a function. Allows "varargs" (variable number of arguments).

Examples:

((lambda x x) 1 2 3 4 5) => (1 2 3 4 5)

((lambda (x . y) (list x y)) 1 2 3 4 5) => (1 (2 3 4 5))

((lambda (a b . z) (list a b z)) 1 2 3 4 5) => (1 2 (3 4 5))

((lambda (a b . z) (list a b z)) 1 2 3) => (1 2 (3))

((lambda (a b . z) (list a b z)) 1 2) => (1 2 ())

(try ((lambda (a b . z) (list a b z)) 1) (catch e "not enough arguments given")) => "not enough arguments given"

length

(length ls)

Returns the length of a list, ls. Note that this does not recurse into the list, but only counts the toplevel items, even if those are lists.

Example:

(length (quote (1 2 3))) => 3

let

(let ...)

One method of creating local variables.

Example:

(let ((x 1)) x) => 1

let*

(let* ...)

Allows the creation of variables whose value depends on previous variables.

Example:

(let* ((x 1) (y (+ x 1))) y) => 2

In this example, note that y depends on x.

letrec

(letrec ...)

Allows creating recursively defined values.

Example:

(letrec ((loop (lambda (n) 
                  (if (= n 0) 
                      (quote ok) 
                      (loop (- n 1)))))) 
     (loop 10))                              => ok

list

(list ...)

Create a new list by consing the items onto each other, ending in '(), creating a proper list.

Example:

(list 1 2) => (1 2)

list->string

(list->string ...)

Converts a list of characters into a string.

Example:

(list->string (quote (#\1 #\2 #\3))) => "123"

list->vector

(list->vector ...)

Converts a list into a vector. A vector has a fixed length, and can index directly into a position.

Example:

(list->vector (quote (1 2 3))) => [1, 2, 3]

In Python, Scheme uses the Python List as a vector. In C#, Scheme uses an array to represent a vector.

list-ref

(list-ref ...)

A convenient method to get an item from a list. This is no more efficient than a series of car/cdrs.

Example:

(list-ref (quote (1 2 3)) 1) => 2

list?

(list? ...)

Returns #t if an item is a proper list, or the empty list '().

Example:

(list? (quote (1 2 3))) => #t

load

Load Scheme file(s).

(load "file1.ss" "file2.ss" ...)

load-as

Load a Scheme file into a namespace.

(load "file.ss" 'namespace)

make-set

(make-set ...)

Creates a list of unique items.

Example:

(sort < (make-set (quote (1 2 3 1 2)))) => (1 2 3)

make-vector

(make-vector size)

Creates a vector of a specific size.

Example:

(make-vector 3) => [0, 0, 0]

map

(map f sequence)

Applies a function to all elements in a sequence, and returns the resulting values in a list.

Example:

(map (lambda (n) (+ n 1)) (range 5)) => (1 2 3 4 5)

member

(member item ls)

Check to see if item is in a list. If it is in the list, return the rest of the list. If not, return #f.

Example:

(member "b" (quote ("a" "b" "c"))) => ("b" "c")

memq

(memq item ls)

Check if item is in ls (like member) but using the eq? operator.

Example:

(memq (quote b) (quote (a b c))) => (b c)

memv

(memv ...)

Check if item is in ls (like member) but using the eqv? operator.

Example:

(memv 2 (quote (1.0 2.0 3.0))) => (2.0 3.0)

not

(not item)

Flips the boolean value of item.

Example:

(not #f) => #t

null?

(null? item)

Checks to see if an item is eq? to the empty list, '().

Example:

(null? (quote ())) => #t

number->string

(number->string ...)

Convert a number into a string.

Example:

(number->string 23) => "23"

number?

(number? item)

Is item a number?

Example:

(number? 23) => #t

odd?

(odd? number)

Is number odd?

Example:

(odd? 45) => #t

or

(or ...)

Or will return #t as soon as it encounters a non-#f in the items (eg, it short circuits without further evaluation of arguments). If no non-#f is encountered, it returns #f.

Example:

(or #t (/ 1 0)) => #t

pair?

(pair? item)

A pair is a cons cell. This function tests to see if item is a cons cell.

Example:

(pair? (quote ())) => #f

(pair? (cons 1 2)) => #t

Note that '() is not a cons cell; it is a symbol.

parse

(parse ...)

Parse takes an s-expression and returns a parsed version.

Example:

(parse (quote (+ 1 2))) => (app-aexp (lexical-address-aexp 0 1 + none) ((lit-aexp 1 none) (lit-aexp 2 none)) none)

parse-string

(parse-string ...)

Parse-string takes a string representing an s-expression and returns the parsed version, like parse.

Example:

(parse-string "(- 7 8)") => (app-aexp (lexical-address-aexp 0 2 - (stdin 1 2 2 1 2 2)) ((lit-aexp 7 (stdin 1 4 4 1 4 4)) (lit-aexp 8 (stdin 1 6 6 1 6 6))) (stdin 1 1 1 1 7 7))

The additional numbers are details about line, column, starting and ending place in the file from which this code was received (or "stdin" if it came not from a file.

procedure?

(procedure? item)

Returns #t if item is a procedure.

Example:

(procedure? procedure?) => #t

quote, quasiquote, and unquote

(quote item)
'item

A quoted item (represented by a single-quote) is a symbol (if item is an atom), or is a list of quoted items if item is a list. Literals that are quoted are just the literals.

Examples:

'symbol => symbol
'(a list of items) => (a list of items)
(quasiquote item)
`item

Quasiquote (represented by a back-quote) is like a regular quoted item; however, with a quasiquote, unquoted (represented with a comma) items are evaluated.

Examples:

(quasiquote (list (unquote (+ 1 2)) 4)) => (list 3 4)
`(list ,(+ 1 2) 4) => (list 3 4)

Notice that the (+ 1 2) is evaluated.

,@expression will unqote the contents without the containing list.

quotient

(quotient numerator denominator)

Returns the number of times the denominator will go into the numerator.

Example:

(quotient 1 4) => 0

rac

(rac ls)

Opposite of "car"... returns the last item in a list.

Example:

(rac (quote (1 2 3))) => 3

range

(range stop)
(range start stop)
(range start stop step)

Returns a range of integers. "stop" never includes the stop number given.

Example:

(range 10) => (0 1 2 3 4 5 6 7 8 9)

rational

(rational numerator denominator)

Returns the same as what / (divide) would give.

Example:

(rational 3 4) => 3/4

rdc

(rdc ls)

Opposite of "cdr"... returns everything in a list but the last item.

Example:

(rdc (quote (1 2 3))) => (1 2)

read-string

(read-string ...)

Example:

(read-string (quote (1 2 3))) 

=> ((pair) 
    ((atom) 1 (stdin 1 2 2 1 2 2)) 
    ((pair) 
     ((atom) 2 (stdin 1 4 4 1 4 4)) 
     ((pair) 
      ((atom) 3 (stdin 1 6 6 1 6 6)) 
      ((atom) () none) 
      none) 
     none) 
    (stdin 1 1 1 1 7 7))

remainder

(remainder a b)

The remainder, after b is divided into a.

Example:

(remainder 1 4) => 1

require

(require expression)

Requires that an expression to be true. If it is not, then it fails, handling control to the fail continuation.

Example:

(require #t) => ok

reverse

(reverse ls)

Returns a list in reversed order.

Example:

(reverse (quote (1 2 3))) => (3 2 1)

round

(round ...)

Rounds a number to the nearest integer.

Example:

(round 45.5) => 46

(round 45.4) => 45

set!

(set! variable value)

set! is used to assign values. Note that you must use define to create a global variable before you can set it.

Examples:

(define x 'undefined)
(set! x 4)

set-car!

(set-car! ls item)

Changes the car of a list to be a new item.

Example:

(let ((x (quote (1 2 3)))) (set-car! x 0) x) => (0 2 3)

set-cdr!

(set-cdr! ls item)

Changes the cdr of a list to be a new item.

Example:

(let ((x (quote (1 2 3)))) (set-cdr! x (quote (3 4))) x) => (1 3 4)

snoc

(snoc item ls)

Opposite of "cons"... connects an item onto the end of a list.

Example:

(snoc 0 (quote (1 2 3))) => (1 2 3 0)

sort

(sort comparison-function ls)

Takes a comparison-function (such as < or >) and sorts a list using that function. < gives a list in ascending order.

Example:

(sort < (quote (3 7 1 2))) => (1 2 3 7)

sqrt

(sqrt number)

Returns the square root of a number.

Example:

(sqrt 3) => 1.7320508075688772

string

(string c ...)

Takes the given characters and turns them into a string.

Example:

(string #\1 #\2) => "12"

string->list

(string->list ...)

Takes a string, and returns a list of characters.

Example:

(string->list "hello world") => (#\h #\e #\l #\l #\o #\  #\w #\o #\r #\l #\d)

string->number

(string->number ...)

Takes a string and returns a number.

Example:

(string->number "12.1") => 12.1

string->symbol

(string->symbol ...)

Takes a string, and returns a symbol.

Example:

(string->symbol "hello") => hello

string-append

(string-append ...)

Takes the given strings, appends them together, and returns the resulting string.

Example:

(string-append "hell" "o") => "hello"

string-length

(string-length s)

Returns the length of a string.

Example:

(string-length "what") => 4

string-ref

(string-ref s position)

Returns the character in the given position in string s.

Example:

(string-ref "what" 2) => #\a

string-split

(string-split s c)

Splits a string s into strings given a delimiting character c.

Example:

(string-split "hello.world" #\.) => ("hello" "world")

string<?

(string<? a b)

Is string a less than string b in lexicographic order?

Example:

(string<? "apple" "banana") => #t

string=?

(string=? a b)

Is string a equal to string b?

Example:

(string=? "a" "b") => #f

string?

(string? item)

Is item a string?

Example:

(string? "hello") => #t

substring

(substring s start stop)

Given a string s, a start position, and stop position, return the substring.

Example:

(substring "hello" 1 3) => "el"

symbol

(symbol s)

Given a string s, return a symbol.

Example:

(symbol "hello") => hello

symbol->string

(symbol->string sym)

Convert a symbol sym into a string.

Example:

(symbol->string (quote hello)) => "hello"

symbol?

(symbol? item)

Is item a symbol?

Example:

(symbol? (quote hello)) => #t

trace-lambda

(trace-lambda name (args...) body)

Similar to regular lambda, but display tracing information at runtime.

Example:

==> ((trace-lambda test (n) n) 4)
call: (test 4)
return: 4
4

typeof

(typeof item)

Get the internal type of item. In Python, this will return Python types. In C#, this will return CLR types.

==> (typeof 1)
System.Int32
==> (typeof 238762372632732736)
Microsoft.Scripting.Math.BigInteger
==> (typeof 1/5)                
Rational

Examples:

(typeof 23) => <type 'int'>

unparse

(unparse ...)

Unparse a parsed expression.

Example:

(unparse (parse (quote (+ 1 2)))) => (+ 1 2)

use-lexial-address

(use-lexial-address)
(use-lexial-address bool)

Get or set the use-lexical-address setting.

Example:

(use-lexical-address) => #t

(use-lexical-address #f)

(use-lexical-address) => #f

use-stack-trace

(use-stack-trace)
(use-stack-trace bool)

Set or get the use-stack-trace setting.

Example:

(use-stack-trace) => #t

use-tracing

(use-tracing)
(use-tracing ...)

Get or set the use-tracking setting.

Example:

(use-tracing) => #f

import

(import ...)

Use a native library. On Python, you can use Python libraries. In Calico, you can use Calico libraries.

Example:

(try (import "math") (catch e (import "Graphics"))) => ()

You can use "import" to fill in missing functions from Scheme. For example, Calico Scheme doesn't currently have a sin function. You can add that:

In Scheme in Python:

(import "math")    ## Python library
(math.sin 3.14)                        => 0.0015926529164868282

In Scheme in Calico:

(import "Math")   ## Calico library
(Math.Sin 3.14)                        => 0.00159265291648683

vector

(vector ...)

Create a vector with the elements given.

Example:

In Scheme-in-Python:

(vector 1 2 3) => [1, 2, 3]

In Scheme-in-Calico:

(vector 1 2 3) => #3(1 2 3)


In Scheme-in-Python, vectors are represented by Python's list. In Scheme-in-Calico, vectors are represented by CLR's object arrays (object []).

vector->list

(vector->list ...)

Convert the vector into a list.

Example:

(vector->list (vector 1 2 3)) => (1 2 3)

vector-ref

(vector-ref ...)

Get an element from a vector. O(1) operation costs.

Example:

(vector-ref (vector 1 2 3) 2) => 3

vector-set!

(let ...)

Create local variables.

Example:

(let ((v (vector 1 2 3))) (vector-set! v 2 (quote a)) v) => [1, 2, a]

vector?

(vector? item)

Is item a vector?

Example:

(vector? (vector)) => #t

(void)

(void)

Create the void object.

Example:

(void) => <void>

zero?

(zero? number)

Is number equal to zero?

Example:

(zero? 0.0) => #t


Advanced topics

Exceptions

(raise <exp>)
(try <exp>...)
(try <exp>... (catch <sym> <exp>...))
(try <exp>... (finally <exp>...))
(try <exp>... (catch <sym> <exp>...) (finally <exp>...))

There are four main forms of try:

  1. try alone: has no effect---doesn't catch exceptions
  2. try with a catch-clause: if exception in try-body, catch-clause will catch and provide return value, otherwise body of try provides. If exception in catch-clause will simple raise it.
  3. try with a finally-clause: finally-clause will run if exception in try-body or not. If there is an exception in the finally, it will raise it.
  4. try with a catch-clause and finally-clause: if an exception in try-body, the catch-clause will run, followed by the finally-clause. If an exception is raised in the catch-clause too, then finally-clause will run, and then raise the catch-exception; if there is an exception raised in the finally-clause, then it will raise.

The <sym> of the catch-clause will be bound to the expression raised.

Examples:

==> 

> (try x)
(uncaught exception: "unbound variable x")
==> "(try x (catch e e))"
"unbound variable x"
==> "(try x (catch e (raise e)))"
(uncaught exception: "unbound variable x")
==> "(try x (finally 'hi))"
hi 
(uncaught exception: "unbound variable x")
==> "(try x (catch e 1 2 3 4 (finally 'hi))"
hi 
4


(try (let loop ((n 5))
        (if (= n 0) 
            (raise (quote blastoff!))) 
        (loop (- n 1))) 
     (catch e e))                      => blastoff!

(try 3) => 3

(try 3 
     (finally 'yes 4))                 => 3

(try (raise (quote yes)) 
     (catch e e))                      => yes

(try (try (raise (quote yes))) 
     (catch e e))                      => yes

(try (try (begin (quote one) 
                 (raise (quote oops)) 
          (quote two))) 
     (catch e e))                      => oops

(* 10 (try (begin (quote one) 
                  (raise (quote oops)) 
                  (quote two)) 
           (catch ex 3 4)))            => 40

(* 10 (try (begin (quote one) 
                  (quote two) 
                  5) 
           (catch ex 3 4)))            => 50

(* 10 (try (begin (quote one) 
                  (raise (quote oops)) 5) 
           (catch ex (list (quote ex:) ex) 
      4)))                                  => 40

(try (* 10 (try (begin (quote one) 
                       (raise (quote oops)) 5) 
                (catch ex (list (quote ex:) ex) (raise ex) 4))) 
     (catch e e))                                          => oops

(try (* 10 (try (begin (quote one) 
                       (raise (quote oops)) 5) 
                (catch ex (list (quote ex:) ex) (raise ex) 4) 
                (finally (quote two) 7))) 
     (catch e e)) => oops

(try (* 10 (try (begin (quote one) 
                       (raise (quote oops)) 5) 
                (catch ex (list (quote ex:) ex) (raise (quote bar)) 4))) 
     (catch x (quote hello) 77))                                         => 77

(try 3 
     (finally (quote hi) 4)) => 3

(try (div 10 0) 
     (catch e e)) => "division by zero"

(try (let ((x (try (div 10 0)))) x) 
                   (catch e e)) => "division by zero"

(let ((x (try (div 10 2) 
              (catch e -1)))) x) => 5

(let ((x (try (div 10 0) 
              (catch e -1)))) x) => -1

(let ((x (try (div 10 2) 
              (catch e -1) 
              (finally (quote closing-files) 42)))) 
   x) => 5

(let ((x (try (div 10 0) 
              (catch e -1) 
              (finally (quote closing-files) 42)))) 
   x) => -1

(let ((x (try (div 10 2) 
              (finally (quote closing-files) 42)))) 
   x) => 5

(try (let ((x (try (div 10 0) 
              (catch e -1 (raise (quote foo))) 
              (finally (quote closing-files) 42)))) 
        x) 
     (catch e e)) => foo

(try (let ((x (try (div 10 0) 
                   (catch e -1 (raise (quote foo))) 
                   (finally (quote closing-files) (raise (quote ack)) 42)))) 
        x) 
   (catch e e)) => ack

(try (let ((x (try (div 10 0) 
                   (catch e -1 (raise (quote foo))) 
                   (finally (quote closing-files) 
                            (raise (quote ack)) 42)))) 
       x) 
     (catch e (if (equal? e (quote ack)) 
                  99 
                  (raise (quote doug)))) 
     (finally (quote closing-outer-files))) => 99

(try (try (let ((x (try (div 10 0) 
                        (catch e -1 (raise (quote foo))) 
                        (finally (quote closing-files) 
                                 (raise (quote ack)) 42)))) 
             x) 
          (catch e (if (equal? e (quote foo)) 
                       99 
                       (raise (quote doug)))) 
          (finally (quote closing-outer-files))) 
      (catch e e)) => doug

(raise ...)

Example:

(define div (lambda (x y) (if (= y 0) (raise "division by zero") (/ x y)))) => <void>


record-case

(record-case ...)

Record-case takes a "structured list", matches on the car, and returns the associated expression.

Example:

(let ((r 5)) 
  (record-case (cons 'banana (cons 'orange (cons (* 2 3) '()))) 
       (apple (a b c)           (list c b a r)) 
       ((cherry banana) (a . b) (list b a r)) 
       ((orange) ()             (quote no)) 
       (else                    2 3 4)))           => ((6) orange 5)

define-datatype

(define-datatype ...)

Define-datatype is a useful set of extensions for defining data, and associated functions.

Example:

The following defines a recursive datatype, called ls-exp, that can take three forms: var-exp, lambda-exp, and app-exp.

(define-datatype lc-exp lc-exp?
  (var-exp 
   (var symbol?))
  (lambda-exp 
   (bound-var symbol?)
   (body lc-exp?))
  (app-exp
   (rator lc-exp?)
   (rand lc-exp?)))

When you define a datatype, it also defines related support functions. For example, the above define-datatype also defines:

lc-exp?
var-exp
lambda-exp
app-exp

You can use those to create data in the prescribed format:

(var-exp (quote a)) => ()

(lambda-exp (quote a) (var-exp (quote a))) => ()

(app-exp (lambda-exp (quote a) (var-exp (quote a))) (var-exp (quote a))) => ()

You can use the datatypes in any number of ways, included the "cases" special form. For example, here is an un-parse function that takes the datatypes defined above, and turns it make into its original form:

(define un-parse
  (lambda (exp)
    (cases lc-exp exp
       (var-exp (var) var)
       (lambda-exp (bound-var body) (list bound-var body))
       (app-exp (rator rand) (list rator rand)))))

(un-parse (var-exp (quote a)))                                            => a
(un-parse (lambda-exp (quote a) (var-exp (quote a))))                     => (a (var-exp a))
(un-parse (app-exp (lambda-exp (quote a) (var-exp (quote a))) (var-exp (quote a)))) 
                                                                          => ((lambda-exp a (var-exp a)) (var-exp a))

call/cc

(call/cc procedure)

Calls procedure with the current continuation. The current continuation is "everything that is left to be done" at the location where the call/cc is located.

Examples:

(* 10 (call/cc (lambda (k) 4))) => 40

(* 10 (call/cc (lambda (k) (+ 1 (k 4))))) => 40

(* 10 (call/cc (lambda (k) (+ 1 (call/cc (lambda (j) (+ 2 (j (k 5))))))))) => 50

(* 10 (call/cc (lambda (k) (+ 1 (call/cc (lambda (j) (+ 2 (k (j 5))))))))) => 60

choose/fail/cut

Calico Scheme also contains a non-deterministic search with back-tracking. To use this, you select choice-points using the keyword "choose" with arguments, set requirements using the keyword "require", and fail using "(choose)". For example, to automatically find two numbers that sum to seven:

(define sum-to-seven
  (lambda ()
    (let ((num1 (choose 0 1 2 3 4 5 6 7 8 9))
          (num2 (choose 0 1 2 3 4 5 6 7 8 9)))
      (require (= (+ num1 num2) 7))
      (printf "The numbers are ~s ~s\n" num1 num2))))

Then, you can let Scheme do the searching for you:

scheme>>> (sum-to-seven)
The numbers are 0 7
Done

If you don't like that result, you can force Scheme back to any choice-points to make a different choice:

scheme>>> (choose)
The numbers are 1 6
Done

This can continue until there are no more choices left.

See menu -> File -> Examples -> Scheme -> choose-examples.ss for more examples.

scheme>>> (choose)
The numbers are 7 0
Done
(define distinct? 
  (lambda (nums) 
    (or (null? nums) 
	(null? (cdr nums)) 
	(and (not (member (car nums) (cdr nums))) 
	     (distinct? (cdr nums))))))

Cut is used to cutoff the possibility of back-tracking.

Here is an example that solves a constraint-satisfaction problem:

;; Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an
;; apartment house that contains only five floors.  Baker does not live on the
;; top floor.  Cooper does not live on the bottom floor.  Fletcher does not
;; live on either the top or the bottom floor.  Miller lives on a higher floor
;; than does Cooper.  Smith does not live on a floor adjacent to Fletcher's.
;; Fletcher does not live on a floor adjacent to Cooper's.  Where does
;; everyone live?

You can use choose and require to solve the problem:

(define floors2 
  (lambda () 
    (let ((baker (choose 1 2 3 4 5))) 
      (require (not (= baker 5))) 
      (let ((fletcher (choose 1 2 3 4 5))) 
	(require (not (= fletcher 5))) 
	(require (not (= fletcher 1))) 
	(let ((cooper (choose 1 2 3 4 5))) 
	  (require (not (= cooper 1))) 
	  (require (not (= (abs (- fletcher cooper)) 1))) 
	  (let ((smith (choose 1 2 3 4 5))) 
	    (require (not (= (abs (- smith fletcher)) 1))) 
	    (let ((miller (choose 1 2 3 4 5))) 
	      (require (> miller cooper)) 
	      (require (distinct? (list baker cooper fletcher miller smith))) 
	      (list (list (quote baker:) baker) 
		    (list (quote cooper:) cooper) 
		    (list (quote fletcher:) fletcher) 
		    (list (quote miller:) miller) 
		    (list (quote smith:) smith)))))))))

You could wait until the end to list the requires. However, moving them up above later (choose ...) statements creates a more efficient search.

(floors2) => ((baker: 3) (cooper: 2) (fletcher: 4) (miller: 5) (smith: 1))

define-syntax

define-syntax is used to change the semantics of Scheme in a manner not possible with regular functions. For example, imagine that you wanted to time a particular function call. To time a function, you can do:

(let ((start (current-time)))
  (fact 5)
  (- (current-time) start))

If you tried to define a function time such that you could call it like:

(time (fact 5))

then, unfortunately, you would evaluate (fact 5) before you could do anything in the function time. You could call it like:

(time fact 5)

but that looks a bit strange. Perhaps a more natural way would be to just change the semantics of Scheme to allow (time (fact 5)). Scheme makes that easy with define-sytnax:

(define-syntax time 
  [(time ?exp) (let ((start (current-time)))
		 ?exp
		 (- (current-time) start))])

Now, you can call it like:

(time (fact 5))

and you get the correct answer.

define-syntax takes a list of two items: a template, and a response. If the template matches, then you evaluate the response. In this example, (time ?exp) matches, so the system will record the start time, evaluate the ?exp, and then return the time minus the start time.

Calico Scheme uses this simple, but powerful pattern matcher to implement define-case. Here is a more complex example: for.

(define-syntax for
  [(for ?exp times do . ?bodies)
   (for-repeat ?exp (lambda () . ?bodies))]
  [(for ?var in ?exp do . ?bodies)
   (for-iterate1 ?exp (lambda (?var) . ?bodies))]
  [(for ?var at (?i) in ?exp do . ?bodies)
   (for-iterate2 0 ?exp (lambda (?var ?i) . ?bodies))]
  [(for ?var at (?i ?j . ?rest) in ?exp do . ?bodies)
   (for ?var at (?i) in ?exp do
     (for ?var at (?j . ?rest) in ?var do . ?bodies))])

In this example, define-syntax creates a for function with 4 forms:

(for 4 times do (function ...))

(for x in '(1 2 3) do (function ...))

(for x at (0) in '(1 2 3) do (function ...))

(for x at (0 1 2) in (range 10) do (function ...))
(define-syntax collect
  [(collect ?exp for ?var in ?list)
   (filter-map (lambda (?var) ?exp) (lambda (?var) #t) ?list)]
  [(collect ?exp for ?var in ?list if ?condition)
   (filter-map (lambda (?var) ?exp) (lambda (?var) ?condition) ?list)])

(collect (* n n) for n in (range 10)) => (0 1 4 9 16 25 36 49 64 81)

(collect (* n n) for n in (range 5 20 3)) => (25 64 121 196 289)

(collect (* n n) for n in (range 10) if (> n 5)) => (36 49 64 81)

More define-syntax examples

A for form:

(define-syntax for
  [(for ?exp times do . ?bodies)
   (for-repeat ?exp (lambda () . ?bodies))]
  [(for ?var in ?exp do . ?bodies)
   (for-iterate1 ?exp (lambda (?var) . ?bodies))]
  [(for ?var at (?i) in ?exp do . ?bodies)
   (for-iterate2 0 ?exp (lambda (?var ?i) . ?bodies))]
  [(for ?var at (?i ?j . ?rest) in ?exp do . ?bodies)
   (for ?var at (?i) in ?exp do
     (for ?var at (?j . ?rest) in ?var do . ?bodies))])

(define for-repeat
  (lambda (n f)
    (if (< n 1)
      'done
      (begin
	(f)
	(for-repeat (- n 1) f)))))

(define for-iterate1
  (lambda (values f)
    (if (null? values)
      'done
      (begin
	(f (car values))
	(for-iterate1 (cdr values) f)))))

(define for-iterate2
  (lambda (i values f)
    (if (null? values)
      'done
      (begin
	(f (car values) i)
	(for-iterate2 (+ i 1) (cdr values) f)))))

(define matrix2d
  '((10 20)
    (30 40)
    (50 60)
    (70 80)))

(define matrix3d
  '(((10 20 30) (40 50 60))
    ((70 80 90) (100 110 120))
    ((130 140 150) (160 170 180))
    ((190 200 210) (220 230 240))))

Using for:

(begin (define hello 0) (for 5 times do (set! hello (+ hello 1))) hello) => 5

(for sym in (quote (a b c d)) do (define x 1) (set! x sym) x) => done

(for n in (range 10 20 2) do n) => done

(for n at (i j) in matrix2d do (list n (quote coords:) i j)) => done

(for n at (i j k) in matrix3d do (list n (quote coords:) i j k)) => done

Defining streams: scons, scar, and scdr and more:

(define-syntax scons
  [(scons ?x ?y) (cons ?x (lambda () ?y))])

(define scar car)

(define scdr
  (lambda (s)
    (let ((result ((cdr s))))
      (set-cdr! s (lambda () result))
      result)))

(define first
  (lambda (n s)
    (if (= n 0)
      '()
      (cons (scar s) (first (- n 1) (scdr s))))))

(define nth
  (lambda (n s)
    (if (= n 0)
      (scar s)
      (nth (- n 1) (scdr s)))))

(define smap
  (lambda (f s)
    (scons (f (scar s)) (smap f (scdr s)))))

(define ones (scons 1 ones))

(define nats (scons 0 (combine nats + ones)))

(define combine
  (lambda (s1 op s2)
    (scons (op (scar s1) (scar s2)) (combine (scdr s1) op (scdr s2)))))

(define fibs (scons 1 (scons 1 (combine fibs + (scdr fibs)))))

(define facts (scons 1 (combine facts * (scdr nats))))

(define ! (lambda (n) (nth n facts)))

Testing !, nth, and first:

(! 5) => 120

(nth 10 facts) => 3628800

(nth 20 fibs) => 10946

(first 30 fibs) => (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 
                    987 1597 2584 4181 6765 10946 17711 28657 46368 
                    75025 121393 196418 317811 514229 832040)

Calico Libraries

You can use any of the libraries in the hosting environment (Python or Mono/.NET):

scheme> (import "DLLName")
scheme> (DLLName.Class arg1 arg2)

For example, you can use Scheme to do art or control robots:

(import "Myro")
(Myro.init "sim")
(Myro.joystick)

Interop

There is a special object in the environment, calico. It has access to a variety of Calico functions. See Calico: calico object for more details.

Use the define! to put a variable in the global Calico namespace.

scheme> (define! x 8)
python> x
8

Wrap a function for use by other Calico languages:

scheme> (func (lambda (a b) (+ a b)))

Combine for cross-language interoperation:

 scheme> (define fact (lambda (n) (if (= n 1) 1 (* n (fact (- n 1))))))
 scheme> (define! factorial (func fact))
 python> factorial(5)
 120

Be careful not to wrap the func around the part that is called recursively, or you will destroy the tail-call optimization.

Iterators

Strings, vectors, and lists all work with map and for-each.

==> (map display "123")
123(void void void)
==> (for-each (lambda (v) (printf "~a\n" v)) (range 3))
1
2
3


Language Interop

Converting from Scheme to Python in Calico:

scheme> (define pylist (calico.Evaluate "lambda *args: list(args)" "python"))
Ok
scheme> (define pytuple (calico.Evaluate "lambda *args: args" "python"))
Ok
scheme> (pylist 1 2 3)
[1, 2, 3]
scheme> (pytuple 1 2 3)
(1, 2, 3)

Converting from Python to Scheme

scheme> (define pylist2list
           (lambda (args)
              (map (lambda (i) i) args)))
Ok
scheme> (pylist2list (pylist 1 2 3))
(1 2 3)
scheme> (pylist2list (pytuple 1 2 3))
(1 2 3)

Use in Python

You can get the single file necessary to run Scheme in Python here:

https://bitbucket.org/ipre/calico/raw/master/languages/Scheme/Scheme/calicoscheme.py

Download and save in your working folder.

You can just use calicoscheme.py as a script in Python, IronPython, or Jython:

$ python calicoscheme.py       ## use ipython to have file-system tab work in quotes
Calico Scheme, version 3.0.0
----------------------------
Use (exit) to exit
==> (+ 1 1)
2

This environment has access to Python's built-ins through calicoscheme.ENVIRONMENT:

==> (sum '(1 2 3))

sum is found in the Python environment.

You can also import and use Python libraries directly:

==> (import "math" "numpy")
(math numpy)
==> (math.sin 3.14)
0.0015926529164868282
==> (numpy.array 10)
array(100)
==> (exit) # or control+d

You can also use calicoscheme inside Python:

$ python 
>>> import calicoscheme
>>> calicoscheme.ENVIRONMENT = globals()    # set the environment to the locals here
>>> calicoscheme.start_rm()
==> (+ 1 1)
2
==> (define! f (lambda (n) (+ n 1)))     ### define! puts it in the external env
==> (exit)
goodbye

And back in Python you can call the define! function using Scheme's infrastructure:

>>> f(100)
101

You can also call into Scheme like so:

>>> calicoscheme.execute_string_rm("(define x 23)")
<void>
>>> calicoscheme.execute_string_rm("x")
23

You can turn debug on to help track down issues:

==> (set! DEBUG #t)

Current limitations

  1. known missing items: bitbucket.org/ipre/calico/issues
  2. define-syntax is a simplified version
  3. all exceptions, procedures, etc, are represented by lists
  4. no pretty-print yet
  5. display/write in general is rough... not much protection for safe and proper printing
  6. no file (read/write) functions yet
  7. no package management tools: can't use cross-Scheme packages and facilities (eg, module, requires, provides, etc)
  8. if (use-stack-trace) is true, then it will keep track of stack; if you have an infinite loop, you might want to turn that off (use-stack-trace #f)

Patches accepted! Python-specific code should go in Scheme.py, general Scheme code should go in interpreter-cps.ss (and related files).

If you have questions or comments, please see our mailing list:

http://calico-users.1054103.n5.nabble.com/

Under The Hood

Calico Scheme is written in Scheme, in continuation-passing style (CPS), transformed into simpler forms, and then translated into C# and Python. Language-native components are written in Scheme.py (for Python) and Scheme.cs (for C#).

You can get the sources in Calico/language/Scheme/Scheme here:

https://bitbucket.org/ipre/calico/raw/master/languages/Scheme/Scheme/

Running "make calicoscheme.py" in that directory will build the file. You will need a Scheme to begin with (we use Petite Scheme, a freely available Scheme).

The process generally works like this:

                     ds-transformer.ss     rm-transformer.ss        translate_rm.py
                               |                    |                    |
*-cps.ss > calicoscheme-cps.ss > calicoscheme-ds.ss > calicoscheme-rm.ss > calicoscheme.py

This is a general process: it can take most any Scheme cps code and transform it into Python or C#.

As an example, consider the function fibonacci. Here it is, written in continuation-passing style:

(load "transformer-macros.ss")

(define* fib-cps
  (lambda (n k)
    (cond
      ((= n 1) (k 1))
      ((= n 2) (k 1))
      (else (fib-cps (- n 1)
	      (lambda-cont (v1)
		(fib-cps (- n 2)
		  (lambda-cont (v2)
		    (k (+ v1 v2))))))))))

(define fib
  (lambda (n)
    (fib-cps n TOP-k)))

(define TOP-k
  (lambda-cont (v)
    (halt* v)))

That is, whenever you have a result, pass it to a function that takes the result, and does further processing to it. The process is started with a TOP-k continuation that signals to halt and return the result.

You can run this code in Petite Scheme:

> (fib 10)
55

This code is transformed into a data structure representation:

$ petite
> (load "ds-transformer.ss")
> (transform-ds "fib-cps.ss" "fib-ds.ss")

That creates the following:

(load "transformer-macros.ss")

;;----------------------------------------------------------------------
;; continuation datatype

(define make-cont (lambda args (cons 'continuation args)))

(define*
  apply-cont
  (lambda (k value) (apply+ (cadr k) value (cddr k))))

(define+
  <cont-1>
  (lambda (value fields)
    (let ((v1 (car fields)) (k (cadr fields)))
      (apply-cont k (+ v1 value)))))

(define+
  <cont-2>
  (lambda (value fields)
    (let ((n (car fields)) (k (cadr fields)))
      (fib-cps (- n 2) (make-cont <cont-1> value k)))))

(define+
  <cont-3>
  (lambda (value fields) (let () (halt* value))))

;;----------------------------------------------------------------------
;; main program

(define*
  fib-cps
  (lambda (n k)
    (cond
      ((= n 1) (apply-cont k 1))
      ((= n 2) (apply-cont k 1))
      (else (fib-cps (- n 1) (make-cont <cont-2> n k))))))

(define fib (lambda (n) (fib-cps n TOP-k)))

(define TOP-k (make-cont <cont-3>))

This breaks out the continuations into stand-alone functions.

You can run this in Petite Scheme:

> (fib 10)
55

Next, we turn the data structure representation into a register machine:

$ petite
> (load "rm-transformer.ss")
> (transform-rm "fib-ds.ss" "fib-rm.ss")

That creates the following:

(load "transformer-macros.ss")

;;----------------------------------------------------------------------

;; global registers
(define pc 'undefined)
(define fields_reg 'undefined)
(define final_reg 'undefined)
(define k_reg 'undefined)
(define n_reg 'undefined)
(define value_reg 'undefined)

(define make-cont
  (lambda args (return* (cons 'continuation args))))

(define*
  apply-cont
  (lambda () (return* (apply (cadr k_reg) (cddr k_reg)))))

(define <cont-1>
  (lambda (v1 k)
    (set! value_reg (+ v1 value_reg))
    (set! k_reg k)
    (set! pc apply-cont)))

(define <cont-2>
  (lambda (n k)
    (set! k_reg (make-cont <cont-1> value_reg k))
    (set! n_reg (- n 2))
    (set! pc fib-cps)))

(define <cont-3>
  (lambda () (set! final_reg value_reg) (set! pc #f)))

(define*
  fib-cps
  (lambda ()
    (if (= n_reg 1)
        (begin (set! value_reg 1) (set! pc apply-cont))
        (if (= n_reg 2)
            (begin (set! value_reg 1) (set! pc apply-cont))
            (begin
              (set! k_reg (make-cont <cont-2> n_reg k_reg))
              (set! n_reg (- n_reg 1))
              (set! pc fib-cps))))))

(define fib
  (lambda (n)
    (set! k_reg TOP-k)
    (set! n_reg n)
    (set! pc fib-cps)))

(define TOP-k (make-cont <cont-3>))

;; the trampoline
(define trampoline
  (lambda () (if pc (begin (pc) (trampoline)) final_reg)))

(define run
  (lambda (setup . args)
    (apply setup args)
    (return* (trampoline))))

You can then run this in Petite Scheme:

(run fib 10)
55

This requires a special form to run the code, as the new fib function doesn't return anything.

Finally, the register machine program can be translated into C# or Python:

python translate_rm.py "fib-rm.ss" "fib.py"

The ending extension of the second filename indicates whether to generate Python or C#.

Here is the bottom of the Python version:

...
symbol_emptylist = Symbol("()")
symbol_undefined = Symbol("undefined")
symbol_continuation = Symbol("continuation")

pc = symbol_undefined
fields_reg = symbol_undefined
final_reg = symbol_undefined
k_reg = symbol_undefined
n_reg = symbol_undefined
value_reg = symbol_undefined

def apply_cont():
    return Apply(cadr(k_reg), cddr(k_reg))

def cont_1(v1, k):
    globals()['value_reg'] = plus(v1, value_reg)
    globals()['k_reg'] = k
    globals()['pc'] = apply_cont

def cont_2(n, k):
    globals()['k_reg'] = make_cont(cont_1, value_reg, k)
    globals()['n_reg'] = minus(n, 2)
    globals()['pc'] = fib_cps

def cont_3():
    globals()['final_reg'] = value_reg
    globals()['pc'] = False

def fib_cps():
    if Equal(n_reg, 1):
        globals()['value_reg'] = 1
        globals()['pc'] = apply_cont
    else:
        if Equal(n_reg, 2):
            globals()['value_reg'] = 1
            globals()['pc'] = apply_cont
        else:
            globals()['k_reg'] = make_cont(cont_2, n_reg, k_reg)
            globals()['n_reg'] = minus(n_reg, 1)
            globals()['pc'] = fib_cps

def fib(n):
    globals()['k_reg'] = REP_k
    globals()['n_reg'] = n
    globals()['pc'] = fib_cps

REP_k = make_cont(cont_3)
def run(setup, *args):
    args = List(*args)
    Apply(setup, args)
    return trampoline()

This can be run in Python:

>>> run(fib, 10)
55


For further information on the overall strategy and philosophy, please see Essentials of Programming Languages.

References

  1. Calico
  2. Essentials of Programming Languages by Dan Friedman and Mitch Wand.
  3. CalicoDevelopment - plans and details for Calico development
  4. http://www.scheme.com/tspl4/ - The Scheme Programming Language, 4th edition

There is a compatible version of sllgen.ss provided in Calico/examples/scheme/sllgen.ss

For Developers