Ad

Just a little fix :)

Code
Diff
  • #lang racket/base
    (display "Hello, world!")
    • #lang racket/base
    • (display "Hello, world!")

Parsing infix arithmetic with Racket.

#lang racket
(require (for-syntax syntax/parse) racket/trace)
(begin-for-syntax
  (define-syntax-class val
    #:literals (+ - * /)
    (pattern (~or x:id x:number)
      #:attr value #'x)
    (pattern (a:expr (~or o:* o:/ o:+ o:-) b:expr ...)
      #:attr value #'(infix a o b ...))
    (pattern (proc:id v:expr ...)
      #:attr value #'(proc v ...))))

(trace-define-syntax (infix stx)
  (syntax-parse stx
    #:literals (+ - * /)
    [(_ - v:expr) #'(- v)]
    [(_ - a:val + v ...)
      #'(+ (- a.value) (infix v ...))]
    [(_ - a:val - v ...)
      #'(+ (- a.value) (infix - v ...))]
    [(_ - a:val v ...)
      (with-syntax ([x (datum->syntax stx (gensym 'expr))])
        #'(let-values (((x) (- a.value)))
          (infix x v ...)))]
    [(_ a:val + b:val v ...)
      #'(+ a.value (infix b.value v ...))]
    [(_ a:val - b:val v ...)
      #'(+ a.value (infix - b.value v ...))]
    [(_ a:val (~or o:* o:/) b:val + v ...)
      #'(+ (o a.value b.value) (infix v ...))]
    [(_ a:val (~or o:* o:/) b:val - v ...)
      #'(+ (o a.value b.value) (infix - v ...))]
    [(_ a:val (~or o:* o:/) b:val v ...)
      (with-syntax ([x (datum->syntax stx (gensym 'expr))])
        #'(let-values (((x) (o a.value b.value)))
          (infix x v ...)))]
    [(_ v:expr) #'v]))

(define x 4)
(infix - (cos 0) - (2 * 3 - x) - 3 * x / 5 + 6)
XomapFailed Tests

Anaphoric IF

An if statement that passes the tested value to the body.

#lang racket
(require racket/stxparam)
(define-syntax-parameter value (lambda (stx) (error "not inside aif")))
(define-syntax (aif stx)
  (syntax-case stx ()
    [(_ test true false) 
      #'(let ([t test])
        (syntax-parameterize ([value (lambda (_) #'t)])
          (if t true false)))]))

(aif (regexp-match #rx"Hello" "Hello World!")
  (display (car value))
  (display "Failed!"))

Calculates the factorial of a given integer with applicative y-combinator (or z-combinator).

#lang racket/base
(define (y f)
  ((lambda (x) (f (lambda (v) ((x x) v))))
    (lambda (x) (f (lambda (v) ((x x) v))))))
(define factorial 
  (y (lambda (partial) 
    (lambda (n) (if (zero? n) 1 (* n (partial (sub1 n))))))))
(factorial 50)