Next: , Previous: Filesystem Tree Walk, Up: Top


58 Reading Infix

To load support for reading infix expressions, evaluate the forms:

     (use-modules (ice-9 infix))
     (activate-infix)
   This module adds to Guile simple parser of infix (C-like)
expressions. Parser is quite simple - you have to keep in mind that
all operators are scheme symbols - you should write spaces around
them to separate them from numbers and other symbols (variables,
"function" names etc).

   '[', ']' and ',' act as separators - these are exceptions handled
by infix parser.

   Also note that parser handles C-like expressions, not statements!
Semicolon ';' start comments

Examples:

 #[ 1 + 2 * 3 ]
   -=> 7

 #[ (1 + 2) * 3 ]
   -=> 9

 #[ cos (PI) ]
   -=> -1

 #[2 ^ 3 ^ 4]
   -=> 2417851639229258349412352

 #[(2 ^ 3) ^ 4 ]
   -=> 4096

 #[6 / 3 / 2]
   -=> 1

 #[6 / (3 / 2)]
   -=> 4

 #[sin(1) ^ 2 + cos(1) * cos(1)]
   -=> 1

 #[ string-length("foo") ]
   -=> 3

 #[ modulo(5, 3) ]
   -=> 2

 (vector-ref a 12)
   -=> 12

 #[ a[12]^(a[12] - 10) ]

 #[a[12] < 13 && ! (25 * 0 > 1)]
   -=> #t
— Scheme Procedure: activate-infix

Modify Guile's read mechanisms to recognize #[ expr ] as an infix expression.

— Scheme Procedure: read-infix-expr get-token end? allow-commas

Call thunk get-token repeatedly until a well-formed Scheme expression can be constructed from the tokens. Return the expression. end? is a procedure called on a token; it returns non-#f to break the reading loop. allow-commas, if non-#f, means to process commas without error.

— Scheme Procedure: infix-string->expr s

Parse string s as an infix expression and return the corresponding Scheme expression.

— Scheme Procedure: helper-nth object n

Return the zero-based nth item from object. object may be a vector, pair or a string.

— Scheme Procedure: make-read-tokenizer port

Return a thunk reads from port and returns a token to be used by the rest of the infix machinery.

— Scheme Procedure: add-infix-operator name priority

Add name (a symbol) to the internal table of infix operators. priority is an integer. Optional keys: #:right (boolean) means the operator is right-associative, and #:func (symbol) names a Scheme procedure to call to actually do the operation. (For example, we specify modulo for %.)

— Scheme Procedure: add-prefix-operator name priority

Add name (a symbol) to the internal table of prefix operators. priority is an integer. Optional key #:func (symbol) names a Scheme procedure to call to actually do the operation.

Here is a snapshot of the initial table of infix operators:

      '||   5	#:func 'or
      '&&  10	#:func 'and
     
      '<   15
      '>   15
      '==  15	#:func 'eq?
      '<=  15
      '>=  15
     
     
      '+   20
      '-   20
     
      '*   25
      '/   25
      '%   25	#:func 'modulo
     
      '^    35	#:func 'expt	#:right #t
      '**   35	#:func 'expt    #:right #t

Likewise for prefix operators:

      '! 40	#:func 'not
      '- 40