blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
171
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
8
| license_type
stringclasses 2
values | repo_name
stringlengths 6
82
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 13
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 1.59k
594M
⌀ | star_events_count
int64 0
77.1k
| fork_events_count
int64 0
33.7k
| gha_license_id
stringclasses 12
values | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_language
stringclasses 46
values | src_encoding
stringclasses 14
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 1
class | length_bytes
int64 4
7.87M
| extension
stringclasses 101
values | filename
stringlengths 2
149
| content
stringlengths 4
7.87M
| has_macro_def
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55dd9cbeae30a80d9b90ccbd9ad55a624628f76d | cc06424c5203c28d6aea69f8d5734f9acc067075 | /src/test/enum-set-test.rkt | 182214454f7b5f455606b6241aea59ea3fb54071 | []
| no_license | uwplse/syncro | 48e5ab79793dfb631b85e39a19803e1b407854d0 | cd89d345293f9512350b716ed9e938ff308a162b | refs/heads/master | 2021-01-23T10:55:06.557355 | 2017-11-24T23:26:15 | 2017-11-24T23:26:15 | 93,102,017 | 2 | 1 | null | 2017-11-24T23:26:16 | 2017-06-01T21:43:17 | Racket | UTF-8 | Racket | false | false | 2,246 | rkt | enum-set-test.rkt | #lang rosette
(require rackunit rackunit/text-ui)
(require "../rosette/enum-set.rkt" "../rosette/types.rkt")
(provide run-enum-set-tests)
(define tests
(test-suite
"Tests for language.rkt"
(test-case "Concrete operations"
(define eset (enum-make-set 5))
(check-true (enum-set-empty? eset))
(check-equal? (enum-set-size eset) 0)
(for ([i 5])
(check-false (enum-set-contains? eset i)))
(enum-set-add! eset 4)
(enum-set-add! eset 1)
(check-false (enum-set-empty? eset))
(check-true (enum-set-contains? eset 4))
(check-true (enum-set-contains? eset 1))
(check-false (enum-set-contains? eset 2))
(check-equal? (enum-set-size eset) 2)
(enum-set-add! eset 4)
(enum-set-add! eset 4)
(check-false (enum-set-empty? eset))
(check-true (enum-set-contains? eset 4))
(check-true (enum-set-contains? eset 1))
(check-false (enum-set-contains? eset 2))
(check-equal? (enum-set-size eset) 2)
(enum-set-remove! eset 1)
(check-false (enum-set-empty? eset))
(check-true (enum-set-contains? eset 4))
(check-false (enum-set-contains? eset 1))
(check-false (enum-set-contains? eset 2))
(check-equal? (enum-set-size eset) 1)
(enum-set-add! eset 2)
(check-equal? (enum-set-size eset) 2)
(define evens (build-enum-set 5 even?))
(check-equal? (enum-set-size evens) 3)
(check-true (enum-set-contains? evens 0))
(check-true (enum-set-contains? evens 2))
(check-true (enum-set-contains? evens 4))
(check-false (enum-set-contains? evens 1))
(check-false (enum-set-contains? evens 3))
(check-equal? (enum-set-union eset evens) evens)
(enum-set-add! eset 3)
(define combined (enum-set-union eset evens))
(check-equal? (enum-set-size combined) 4)
(check-true (enum-set-contains? combined 0))
(check-true (enum-set-contains? combined 2))
(check-true (enum-set-contains? combined 3))
(check-true (enum-set-contains? combined 4))
(check-false (enum-set-contains? combined 1)))
;; TODO: Symbolic tests
))
(define (run-enum-set-tests)
(displayln "Running tests for enum-set.rkt")
(run-tests tests))
(module+ main
(run-enum-set-tests))
| false |
c2994a01c30d7692eb030934813a8bf096f1c3d2 | 37c451789020e90b642c74dfe19c462c170d9040 | /diff/carla-fernanda.rkt | cc9e48ca7f64530b427b41d06508a954c15536ff | []
| no_license | hmuniz/LP-2016.2 | 11face097c3015968feea07c218c662dc015d1cf | 99dc28c6da572701dbfc885f672c2385c92988e7 | refs/heads/master | 2021-01-17T21:26:06.154594 | 2016-12-20T15:22:16 | 2016-12-20T15:22:16 | 71,069,658 | 1 | 0 | null | 2016-10-16T18:41:10 | 2016-10-16T18:41:09 | null | UTF-8 | Racket | false | false | 2,032 | rkt | carla-fernanda.rkt | #lang racket
(require levenshtein)
; Resultados gerados na forma de matriz
(define (matrix-of-results list-a list-b teste)
(define (aux list-1 list-2 matrix)
(cond ((empty? list-1) matrix)
(else (aux (cdr list-1)
list-2
(append matrix (list (map (lambda (x) (teste (car list-1) x))
list-2)))))))
(aux list-a list-b '()))
; Resultados gerados na forma de lista + Frequência
(define (list-of-results list-a list-b teste)
(define (aux list-1 list-2 list-out)
(cond ((empty? list-1) list-out)
(else (aux (cdr list-1)
list-2
(append list-out (map (lambda (x) (teste (car list-1) x))
list-2))))))
(aux list-a list-b '()))
;; sobre o codigo acima, não precisava com
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
;; (accumulate append empty (matrix-of-results '("alexandre" "rademaker") '("pedro" "paulo") string-levenshtein))
(define (results-to-list lol)
(define (lol-aux lol res)
(if (empty? lol)
res
(lol-aux (cdr lol) (append res (car lol)))))
(lol-aux lol empty))
(define (frequency-of-results results)
(define (aux list-results list-frequencies)
(if (empty? list-results)
(unique-values list-frequencies)
(aux (cdr list-results) (append list-frequencies
(list (value-key (car list-results)))))))
(define (value-key item)
(cons item (count (lambda (x) (eq? x item)) results)))
(aux results '()))
(define (unique-values values)
(define (aux list-values uniques)
(cond ((empty? list-values) uniques)
((member (car list-values) uniques) (aux (cdr list-values) uniques))
(else (aux (cdr list-values)
(append uniques (list (car list-values)))))))
(aux values '())) | false |
a99672c054c1f800f8b7cc57ff725cf7d1d15e9e | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/succeed/struct-exec.rkt | 0964a5d9e4edc0be7445d2d7c488df2b1b097c98 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/typed-racket | 2cde60da289399d74e945b8f86fbda662520e1ef | f3e42b3aba6ef84b01fc25d0a9ef48cd9d16a554 | refs/heads/master | 2023-09-01T23:26:03.765739 | 2023-08-09T01:22:36 | 2023-08-09T01:22:36 | 27,412,259 | 571 | 131 | NOASSERTION | 2023-08-09T01:22:41 | 2014-12-02T03:00:29 | Racket | UTF-8 | Racket | false | false | 145 | rkt | struct-exec.rkt | #lang typed-scheme
(define-typed-struct/exec X ([a : Number] [b : Boolean]) [(lambda: ([x : X]) (+ 3 (X-a x))) : (X -> Number)])
((make-X 1 #f))
| false |
e6605fb9855c3fd6037c6b685ee05159af0e4582 | 616e16afef240bf95ed7c8670035542d59cdba50 | /redex-test/redex/tests/run-err-tests/test-equal.rktd | 2c110fd57080412a8a5e331a1b45f5b9c3a873dc | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/redex | bd535d6075168ef7be834e7c1b9babe606d5cd34 | 8df08b313cff72d56d3c67366065c19ec0c3f7d0 | refs/heads/master | 2023-08-19T03:34:44.392140 | 2023-07-13T01:50:18 | 2023-07-13T01:50:18 | 27,412,456 | 102 | 43 | NOASSERTION | 2023-04-07T19:07:30 | 2014-12-02T03:06:03 | Racket | UTF-8 | Racket | false | false | 114 | rktd | test-equal.rktd | ("bang"
([bad-test (test-equal #f #f)])
(parameterize ([default-equiv (λ (x y) (error "bang"))])
bad-test))
| false |
2a6d362240cf33572cb183407cf43b4c47d44e32 | e1cf61b84282c33b7a245f4d483883cf77739b91 | /se3-bib/examples/Kapitel01-Pythagoras.rkt | a980ad5c4bdeb66e9c0f26306fc2f3add943cf8d | []
| no_license | timesqueezer/uni | c942718886f0366b240bb222c585ad7ca21afcd4 | 5f79a40b74240f2ff88faccf8beec7b1b3c28a7c | refs/heads/master | 2022-09-23T21:57:23.326315 | 2022-09-22T13:17:29 | 2022-09-22T13:17:29 | 71,152,113 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 845 | rkt | Kapitel01-Pythagoras.rkt | #lang racket
#|
################################################################################
## ##
## This file is part of the se3-bib Racket module v3.0 ##
## Copyright by Leonie Dreschler-Fischer, 2010 ##
## Ported to Racket v6.2.1 by Benjamin Seppke, 2015 ##
## ##
################################################################################
|#
;;; Mein erstes Racket-Programm:
;;; Berechne die Hypothenuse eines Dreiecks
;;; nach dem Satz von Pythagoras
(define a 10)
(define b 20)
;; Jetzt können wir c (ueber c-Quadrat) ausrechnen
(define c
(sqrt (+ (* a a)
(* b b))))
| false |
9b6b8fcea108d7add90d4b3a19a8ec342ea2178a | 1b35cdffa859023c346bed5fcac5a9be21b0a5a6 | /polyglot-doc/polyglot/scribblings/guide/motivation.scrbl | a02776b7d2df12dded5ae05a782cec3ae10dbdca | [
"MIT"
]
| permissive | zyrolasting/polyglot | dd8644425756c87357c1b425670f596be708104d | d27ca7fe90fd4ba2a6c5bcd921fce89e72d2c408 | refs/heads/master | 2021-07-03T01:09:33.887986 | 2021-01-01T16:17:57 | 2021-01-01T16:17:57 | 204,181,797 | 95 | 6 | MIT | 2020-05-26T13:44:19 | 2019-08-24T16:18:07 | Racket | UTF-8 | Racket | false | false | 1,353 | scrbl | motivation.scrbl | #lang scribble/manual
@title[#:tag "motivation"]{Why @italic{Another} Web Development... Thing?!}
I designed Polyglot to address my own common pains after many years of
switching platforms, frameworks, or libraries to develop websites. Each switch
often made me learn the next trendy rephrasal of basic concepts and tasks. I
can’t make a new tool without being a part of that problem, so why should you
use anything I make in an already saturated space?
For one thing, if you want to change how you work on a website when neck deep
with Polyglot, you can do so without rewriting all of your code. Unlike
Scribble or Pollen, Polyglot views documents as @italic{containers of programs}
where any block of code is subject to rules you can change.
Polyglot is not for everybody. It gives you freedom, which means work. It won’t
give you staple featues you think every website should have. Its core job is to
give you flexibility and backwards-compatibility when you inevitably end up
with code that you want to use, yet leave behind.
Naturally I want you to use Polyglot, but I prefer you use what fits the
job. So unless you identify with everything I said up until now, then you might
prefer another tool. If you want something that protects what you already made
while keeping you ready to prototype anything new, then consider trying
Polyglot.
| false |
7b82a418c833b13a88519d90b385bc7ac21b8485 | b3f7130055945e07cb494cb130faa4d0a537b03b | /gamble/private/instrument-data.rkt | e0a7fb788c58199d7b5202ceba712ad74b8f310c | [
"BSD-2-Clause"
]
| permissive | rmculpepper/gamble | 1ba0a0eb494edc33df18f62c40c1d4c1d408c022 | a5231e2eb3dc0721eedc63a77ee6d9333846323e | refs/heads/master | 2022-02-03T11:28:21.943214 | 2016-08-25T18:06:19 | 2016-08-25T18:06:19 | 17,025,132 | 39 | 10 | BSD-2-Clause | 2019-12-18T21:04:16 | 2014-02-20T15:32:20 | Racket | UTF-8 | Racket | false | false | 6,585 | rkt | instrument-data.rkt | ;; Copyright (c) 2015 Ryan Culpepper
;; Released under the terms of the 2-clause BSD license.
;; See the file COPYRIGHT for details.
#lang racket/base
(require (for-syntax racket/base
racket/list
racket/syntax
syntax/parse
syntax/id-table)
"interfaces.rkt"
"context.rkt")
(provide define/instr-protocol
(for-syntax instr-fun-table
register-instrumented-fun!
instr-fun)
declare-observation-propagator
(for-syntax observation-propagators
non-random-first-order-funs))
;; ============================================================
;; Instrumented function protocol
(begin-for-syntax
;; instr-fun-table : (free-id-table Id => (cons Id (Listof Nat)))
(define instr-fun-table
(make-free-id-table))
(define (register-instrumented-fun! id id* arity)
(free-id-table-set! instr-fun-table id (cons id* arity)))
(define-syntax-class instr-fun
#:attributes (instr arity)
(pattern f:id
#:do [(define p (free-id-table-ref instr-fun-table #'f #f))]
#:when p
#:with instr (car p)
#:attr arity (cdr p)))
)
(define-syntax (define/instr-protocol stx)
(syntax-parse stx
#:literals (case-lambda)
[(_ (f:id arg:id ...) body ...)
#'(define/instr-protocol f (case-lambda [(arg ...) body ...]))]
[(define/instr-protocol f:id (case-lambda [(arg:id ...) body ...] ...))
(define/with-syntax (f*) (generate-temporaries #'(f)))
(define/with-syntax arity (map length (syntax->datum #'((arg ...) ...))))
#'(begin (define-values (f*)
(case-lambda
[(addr obs arg ...)
(with ([ADDR addr] [OBS obs]) body ...)]
...))
(define-values (f)
(case-lambda
[(arg ...)
(call-with-immediate-continuation-mark OBS-mark
(#%plain-lambda (obs) (f* (ADDR-mark) obs arg ...)))]
...))
(begin-for-syntax*
(register-instrumented-fun!
(quote-syntax f)
(quote-syntax f*)
'arity)))]))
(define-syntax (begin-for-syntax* stx)
(syntax-case stx ()
[(_ expr ...)
(case (syntax-local-context)
[(module top-level)
#'(begin-for-syntax expr ...)]
[else
#'(define-syntaxes () (begin expr ... (values)))])]))
;; ============================================================
;; Observation propagators and non-random primitives
(begin-for-syntax
;; id-table[ (Listof ObservationPropagator) ]
(define observation-propagators (make-free-id-table))
;; An ObservationPropagator
;; - (list '#:final-arg Identifier Identifier Identifier)
;; - (list '#:all-args Identifier (listof Identifier))
(define (register-final-arg-propagator! id pred inverter scaler)
(free-id-table-set! observation-propagators id (list '#:final-arg pred inverter scaler)))
;; non-random-first-order-funs : free-id-table[ #t ]
(define non-random-first-order-funs (make-free-id-table))
(define (register-non-random-first-order-fun! id)
(free-id-table-set! non-random-first-order-funs id #t))
)
(define-syntax (declare-non-random-first-order stx)
(syntax-parse stx
[(declare-non-random-first-order f:id ...)
#'(begin-for-syntax
(register-non-random-first-order #'f) ...)]))
(define-syntax (declare-observation-propagator stx)
(define-syntax-class ID
(pattern (~and _:id (~not (~literal ...)) (~not (~literal _)))))
(syntax-parse stx
[(declare-observation-propagator
(op:ID arg:ID ... (~literal _))
ok?:expr inverter:expr scaler:expr)
#'(begin
(define-syntax-rule (pred y arg ...) (ok? y))
(define-syntax-rule (invert y arg ...) (inverter y))
(define-syntax-rule (scale x arg ...) (scaler x))
(begin-for-syntax
(register-final-arg-propagator! #'op #'pred #'invert #'scale)))]
[(declare-observation-propagator
(op:ID arg:ID ... rest-arg:ID (~literal ...) (~literal _))
ok?:expr inverter:expr scaler:expr)
#'(begin
(define-syntax-rule (pred y arg ... rest-arg (... ...)) (ok? y))
(define-syntax-rule (invert y arg ... rest-arg (... ...)) (inverter y))
(define-syntax-rule (scale x arg ... rest-arg (... ...)) (scaler x))
(begin-for-syntax
(register-final-arg-propagator! #'op #'pred #'invert #'scale)))]))
;; ------------------------------------------------------------
#|
observe y(σ) = v
where y(σ) = f(x(σ))
want to weight by
dσ/dy -- note inverse!
= (dy/dσ)^-1
= [ df/dx * dx/dσ ]^-1
= (df/dx)^-1 * dσ/dx
= (df/dx)^-1 * p_x(x)
where x = f^-1(v)
eg, if f(x) = 2x
then weight by 1/2
eg, if f(x) = x^3
then weight by [ 3x^2 ]^-1
--- except x^n does not have unique inverse
eg, if f(x) = exp(x)
then weight by [ exp(x) ]^-1
|#
;; FIXME: add predicate; if y fails predicate, then fail
;; eg, for arithmetic, should be real?, for matrix* should be matrix (of right shape?)
;; FIXME: return log(1/scale) instead?
;; Exact arithmetic mostly good for discrete cases, so doesn't matter ???
;; FIXME: real? vs number? (ie, complex?) --- scale requires real ???
(declare-observation-propagator (+ a ... _)
rational?
(lambda (y) (- y a ...))
(lambda (x) 1))
;; Suppose (a ...) = (a0 ai ...)
;; then y = (- a0 ai ... x)
;; so x = (- a0 ai ... y) = (- a ... y)
;; Suppose (a ...) = ()
;; then x = (- y) = (- a ... y)
;; So can handle both cases with same pattern!
(declare-observation-propagator (- a ... _)
rational?
(lambda (y) (- a ... y))
(lambda (x) 1))
(declare-observation-propagator (* a ... _)
rational?
(lambda (y) (/ y a ...))
(lambda (x) (abs (/ (* a ...)))))
(declare-observation-propagator (/ a ... _)
(lambda (y) (and (rational? y) (not (eq? y 0))))
(lambda (y) (/ (/ a ... 1) y))
(lambda (x) (abs (/ (* x x) (* a ...)))))
(declare-observation-propagator (exp _)
real?
(lambda (y) (log y))
(lambda (x) (/ (exp x)))) ;; FIXME: pass y = (exp x) too?
(declare-observation-propagator (log _)
real?
(lambda (y) (exp y))
(lambda (x) (abs x)))
;; dx/dy = (dy/dx)^-1 = (1/x)^-1 = x
(begin-for-syntax
(free-id-table-set! observation-propagators #'cons
(list '#:all-args #'pair? (list #'car #'cdr))))
;; FIXME: use 0 for scale of non-continuous operations?
| true |
74306518ed59f311171ee879b1a928fbfafa30c6 | a96f96269cc22628682440e24b71508073467ae1 | /vm.rkt | 6ac41a96e372aaf71db184f147383d130f6646fc | []
| no_license | umatani/tiny-opalclj | a206bb54597cc9abc121462863b9a1e66dacd588 | fb7f2ce3ca4174e47ae440bb5df3c740c9fc831e | refs/heads/main | 2023-03-17T18:11:36.984125 | 2021-03-16T09:12:06 | 2021-03-16T09:12:06 | 348,214,983 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,567 | rkt | vm.rkt | #lang racket/base
(require (for-syntax racket/base)
syntax/parse/define
racket/stxparam
(prefix-in conc$ "domain/concrete.rkt"))
(provide (rename-out [vm-module-begin #%module-begin])
;; from racket/base
#%app #%datum #%top begin let if
;; from racket for debug
displayln quote
;; from this module
operand-stack make-stack dump-stack pop-stack
(for-syntax sinit-id) sinit
def-class self def-method
store load while print-top dup
iconst iadd isub imul idiv lt eq
new invokevirtual getfield putfield
;; hooks
load-impl store-impl delta-impl
invokevirtual-impl getfield-impl putfield-impl
)
;;;;;;;;;;;;;;;;;;;;;;;;;
;; bytecode execution
;;;;;;;;;;;;;;;;;;;;;;;;;
;; operand stack
(define operand-stack (make-parameter #f))
(define (make-stack l) (box l))
(define (dump-stack) (unbox (operand-stack)))
(define (push-stack v)
(set-box! (operand-stack) (cons v (unbox (operand-stack)))))
(define (pop-stack)
(let ([s (unbox (operand-stack))])
(begin0 (car s)
(set-box! (operand-stack) (cdr s)))))
(define (peek-stack) (car (unbox (operand-stack))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-syntax (vm-module-begin stx)
(syntax-parse stx
#:literals [vm-module-begin]
[(vm-module-begin b ...)
#'(#%module-begin b ...)]))
(define-simple-macro (def-class cname:id sname (v:id ...) m ...)
(conc$def-class cname sname (v ...) m ...))
(define-syntax-parameter self (syntax-rules ()))
(define-for-syntax sinit-id (car (generate-temporaries '(sinit))))
(define sinit (box #f))
(define-syntax (def-method stx)
(syntax-parse stx
#:literals [def-method]
[(def-method mname:id (param:id) (var:id ...) body:expr)
#`(let ([f (λ (obj param [var #f] ...)
(parameterize ([operand-stack (make-stack '())])
(syntax-parameterize
([self (make-rename-transformer #'obj)])
body)
(pop-stack)))])
#,(if (free-identifier=? #'mname sinit-id)
#'(set-box! sinit f)
#'(void))
f)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-simple-macro (iconst i:integer)
(push-stack (conc$const i)))
(define-syntax-parameter load-impl
(make-rename-transformer #'conc$load))
(define-simple-macro (load v:id)
(push-stack (load-impl v)))
(define-syntax-parameter store-impl
(make-rename-transformer #'conc$store))
(define-simple-macro (store v:id)
(store-impl v (pop-stack)))
(define-syntax-parameter delta-impl
(make-rename-transformer #'conc$delta))
(define-simple-macro (iadd)
(let ([v2 (pop-stack)]
[v1 (pop-stack)])
(push-stack (delta-impl 'iadd v1 v2))))
(define-simple-macro (isub)
(let ([v2 (pop-stack)]
[v1 (pop-stack)])
(push-stack (delta-impl 'isub v1 v2))))
(define-simple-macro (imul)
(let ([v2 (pop-stack)]
[v1 (pop-stack)])
(push-stack (delta-impl 'imul v1 v2))))
(define-simple-macro (idiv)
(let ([v2 (pop-stack)]
[v1 (pop-stack)])
(push-stack (delta-impl 'idiv v1 v2))))
(define-simple-macro (lt)
(let ([v2 (pop-stack)]
[v1 (pop-stack)])
(delta-impl 'lt v1 v2)))
(define-simple-macro (eq)
(let ([v2 (pop-stack)]
[v1 (pop-stack)])
(delta-impl 'eq v1 v2)))
(define-simple-macro (while cond:expr body:expr)
(letrec ([loop (λ ()
(if cond
(begin body (loop))
(void)))])
(loop)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-simple-macro (new lbl:id cname:id)
(push-stack (conc$new cname)))
(define-syntax-parameter invokevirtual-impl
(make-rename-transformer #'conc$invokevirtual))
(define-simple-macro (invokevirtual cname:id mname:id)
(let ([arg (pop-stack)]
[tgt (pop-stack)])
(push-stack (invokevirtual-impl cname tgt mname arg))))
(define-syntax-parameter getfield-impl
(make-rename-transformer #'conc$getfield))
(define-simple-macro (getfield cname:id fname:id)
(let ([tgt (pop-stack)])
(push-stack (getfield-impl cname tgt fname))))
(define-syntax-parameter putfield-impl
(make-rename-transformer #'conc$putfield))
(define-simple-macro (putfield cname:id fname:id)
(let ([v (pop-stack)]
[tgt (pop-stack)])
(putfield-impl cname tgt fname v)))
(define-simple-macro (print-top)
(conc$displayln (pop-stack)))
;; for debug (not used in compiled code)
(define-simple-macro (dup)
(push-stack (peek-stack)))
| true |
d72c3418205c911d27c486b87df9dd8afee8ad1e | 9dc73e4725583ae7af984b2e19f965bbdd023787 | /the-little-series/the-seasoned-schemer/17-we-changes-therefore-we-are!.rkt | e984ad59f4e447e236cdb15aa055b5f57d5308e8 | []
| no_license | hidaris/thinking-dumps | 2c6f7798bf51208545a08c737a588a4c0cf81923 | 05b6093c3d1239f06f3657cd3bd15bf5cd622160 | refs/heads/master | 2022-12-06T17:43:47.335583 | 2022-11-26T14:29:18 | 2022-11-26T14:29:18 | 83,424,848 | 6 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,640 | rkt | 17-we-changes-therefore-we-are!.rkt | #lang racket
;;; write deep with if
(define deep
(lambda (m)
(if (zero? m)
(quote pizza)
(cons (deep (sub1 m))
(quote ())))))
;;; a deepM with the new version of deep
(define deepM
(let ((Rs (quote ()))
(Ns (quote ()))
(D (lambda (m)
(if (zero? m)
(quote pizza)
(cons (deepM (sub1 m))
(quote ()))))))
(lambda (n)
(let ((exists (find n Ns Rs)))
(if (atom? exists)
(let ((result (D n)))
(set! Rs (cons result Rs))
(set! Ns (cons n Ns))
result)
exists)))))
;;; Since the definition does not contain
;;; (set! D ...) and D is used in only one place,
;;; we can replace D by its value:
(define deepM2
(let ((Rs (quote ()))
(Ns (quote ())))
(lambda (n)
(let ((exists (find n Ns Rs)))
(if (atom? exists)
(let ((result ((lambda (m)
(if (zero? m)
(quote pizza)
(cons (deepM2 (sub1 m))
(quote ()))))
n)))
(set! Rs (cons result Rs))
(set! Ns (cons n Ns))
result)
exists)))))
;;; applying (lambda ...) immediately to an argument is equivalent to
;;; (let ...)
(define deepM3
(let ((Rs (quote ()))
(Ns (quote ())))
(lambda (n)
(let ((exists (find n Ns Rs)))
(if (atom? exists)
(let ((result
(let ((m n))
(if (zero? m)
(quote pizza)
(cons (deepM3 (sub1 m))
(quote ()))))))
(set! Rs (cons result Rs))
(set! Ns (cons n Ns))
result)
exists)))))
;;; we could unname again.
(define deepM4
(let ((Rs (quote ()))
(Ns (quote ())))
(lambda (n)
(let ((exists (find n Ns Rs)))
(if (atom? exists)
(let ((result
(if (zero? n)
(quote pizza)
(cons (deepM4 (sub1 n))
(quote ())))))
(set! Rs (cons result Rs))
(set! Ns (cons n Ns))
result)
exists)))))
;;; helper
(define atom?
(lambda (a)
(and (not (null? a)) (not (pair? a)))))
(define find
(lambda (n Ns Rs)
(letrec
((A (lambda (ns rs)
(cond
((null? ns) #f)
((= (car ns) n) (car rs))
(else
(A (cdr ns) (cdr rs)))))))
(A Ns Rs))))
;;; write a function consC which returns
;;; the same value as cons and counts how
;;; many times it sees arguments.
;;; This is no different from writing deepR except
;;; that we use add1 to build a number rather than
;;; cons to build a list.
;; (define consC
;; (let ((N 0))
;; (lambda (x y)
;; (set! N (add1 N))
;; (cons x y))))
;; (define deepC
;; (lambda (m)
;; (if (zero? m)
;; (quote pizza)
;; (consC (deepC (sub1 m))
;; (quote ())))))
;;; But N is define in (let ...)
;;; How could we possibly see something
;;; that is imaginary?
(define counter 0)
(define set-counter 0)
;;; we can use (counter) to refer N
(define consC
(let ((N 0))
(set! counter
(lambda ()
N))
(set! set-counter
(lambda (x)
(set! N x)))
(lambda (x y)
(set! N (add1 N))
(cons x y))))
;;; use deepM to avoid repeat
(define deepC
(lambda (m)
(if (zero? m)
(quote pizza)
(consC (deepM5 (sub1 m))
(quote ())))))
(define supercounter
(lambda (f)
(letrec
((S (lambda (n)
(if (zero? n)
(f n)
(let ()
(f n)
(S (sub1 n)))))))
(S 1000)
(counter))))
(define deepM5
(let ((Rs (quote ()))
(Ns (quote ())))
(lambda (n)
(let ((exists (find n Ns Rs)))
(if (atom? exists)
(let ((result
(if (zero? n)
(quote pizza)
(consC
(deepM5 (sub1 n))
(quote ())))))
(set! Rs (cons result Rs))
(set! Ns (cons n Ns))
result)
exists)))))
;;; in the test, the prev code still has a problem.
;;; Here is rember1* again:
(define rember1*
(lambda (a l)
(letrec
((R (lambda (l oh)
(cond
((null? l)
(oh (quote no)))
((atom? (car l))
(if (eq? (car l) a)
(cdr l)
(cons (car l)
(R (cdr l) oh))))
(else
(let ((new-car
(let/cc oh
(R (car l)
oh))))
(if (atom? new-car)
(cons (car l)
(R (cdr l) oh))
(cons new-car
(cdr l)))))))))
(let ((new-l (let/cc oh (R l oh))))
(if (atom? new-l)
l
new-l)))))
(define rember1*C
(lambda (a l)
(letrec
((R (lambda (l oh)
(cond
((null? l)
(oh (quote no)))
((atom? (car l))
(if (eq? (car l) a)
(cdr l)
(consC (car l)
(R (cdr l) oh))))
(else
(let ((new-car
(let/cc oh
(R (car l)
oh))))
(if (atom? new-car)
(consC (car l)
(R (cdr l) oh))
(consC new-car
(cdr l)))))))))
(let ((new-l (let/cc oh (R l oh))))
(if (atom? new-l)
l
new-l)))))
;;; the first good version of rember1*
(define rember1*2
(lambda (a l)
(letrec
((R (lambda (l)
(cond
((null? l) (quote ()))
((atom? (car l))
(if (eq? (car l) a)
(cdr l)
(cons (car l)
(R (cdr l)))))
(else
(let ((av (R (car l))))
(if (eqlist? (car l) av)
(cons (car l)
(R (cdr l)))
(cons av
(cdr l)))))))))
(R l))))
(define rember1*2C
(lambda (a l)
(letrec
((R (lambda (l)
(cond
((null? l) (quote ()))
((atom? (car l))
(if (eq? (car l) a)
(cdr l)
(consC (car l)
(R (cdr l)))))
(else
(let ((av (R (car l))))
(if (eqlist? (car l) av)
(consC (car l)
(R (cdr l)))
(consC av
(cdr l)))))))))
(R l))))
(define eqlist?
(lambda (l1 l2)
(cond
((and (null? l1) (null? l2))
#t)
((or (null? l1) (null? l2))
#f)
(else (and (equal? (car l1) (car l2))
(eqlist? (cdr l1) (cdr l2)))))))
| false |
89a09d636507958fcd453fc378cea1e4298f22ec | 898dceae75025bb8eebb83f6139fa16e3590eb70 | /pl1/asg2/osx-dist/lib/plt/assignment2-osx/collects/racket/private/generic-interfaces.rkt | c998aada2189bbbf4cb7c591c626722895572b10 | []
| no_license | atamis/prog-hw | 7616271bd4e595fe864edb9b8c87c17315b311b8 | 3defb8211a5f28030f32d6bb3334763b2a14fec2 | refs/heads/master | 2020-05-30T22:17:28.245217 | 2013-01-14T18:42:20 | 2013-01-14T18:42:20 | 2,291,884 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,310 | rkt | generic-interfaces.rkt | (module generic-interfaces "pre-base.rkt"
;; Defines (forgeries of) generic interfaces that correspond to struct
;; properties that come from racket/base.
;; Since racket/base can't depend on racket/generics, we can't use
;; `define-generics' to build these generic interfaces. Thus we must
;; forge them.
(#%require (for-syntax '#%kernel))
(#%provide gen:equal+hash gen:custom-write)
(define-values (prop:gen:equal+hash equal+hash? gen:equal+hash-acc)
(make-struct-type-property
'prop:gen:equal+hash
(lambda (v si)
(if (and (vector? v)
(= 3 (vector-length v))
(procedure? (vector-ref v 0))
(procedure-arity-includes? (vector-ref v 0) 3)
(procedure? (vector-ref v 1))
(procedure-arity-includes? (vector-ref v 1) 2)
(procedure? (vector-ref v 2))
(procedure-arity-includes? (vector-ref v 2) 2))
v
(raise-argument-error 'guard-for-prop:gen:equal+hash
(string-append
"(vector/c (procedure-arity-includes/c 3)\n"
" (procedure-arity-includes/c 2)\n"
" (procedure-arity-includes/c 2))")
v)))
(list (cons prop:equal+hash vector->list))))
(define-syntax gen:equal+hash
(list (quote-syntax prop:gen:equal+hash)
(quote-syntax equal-proc)
(quote-syntax hash-proc)
(quote-syntax hash2-proc)))
(define-values (prop:gen:custom-write gen:custom-write? gen:custom-write-acc)
(make-struct-type-property
'prop:gen:custom-write
(lambda (v si)
(if (and (vector? v)
(= 1 (vector-length v))
(procedure? (vector-ref v 0))
(procedure-arity-includes? (vector-ref v 0) 3))
v
(raise-argument-error 'guard-for-prop:gen:custom-write
"(vector/c (procedure-arity-includes/c 3))"
v)))
(list (cons prop:custom-write (lambda (v) (vector-ref v 0))))))
(define-syntax gen:custom-write
(list (quote-syntax prop:gen:custom-write)
(quote-syntax write-proc)))
)
| true |
a019d3834b246b90eed22045e83adea5bb289cfe | 416e7d2651195905c2d8370744b248c8ebefa3b5 | /dkanren.rkt | 87b2e175f65704777643209bd50fc62bdecdfb19 | [
"MIT"
]
| permissive | gregr/dKanren | 0758f640d3ba1b8669257264bdac0f952a809b1b | 2f05275b00dfba5c2f0ca196a514c377b3b60798 | refs/heads/master | 2021-04-03T04:12:46.775763 | 2020-03-28T13:08:04 | 2020-03-28T13:08:04 | 83,606,045 | 16 | 3 | null | 2017-04-08T01:05:17 | 2017-03-01T22:00:02 | Racket | UTF-8 | Racket | false | false | 129,440 | rkt | dkanren.rkt | #lang racket/base
(provide
==
=/=
absento
dk-evalo
fail
fresh
not-numbero
not-pairo
not-symbolo
numbero
symbolo
run
run*
succeed
term?
)
(require
racket/control
(except-in racket/list take)
(except-in racket/match ==)
racket/vector
)
(module+ test
(require
rackunit
))
; TODO:
; force remaining goals that are mentioned only in vattrs (e.g. disunify-or-suspend)
; unlike normal mk, all vars in =/=* should be tracked for earliest access to determinism
; these constraints can shrink domains, which may trigger new unifications, and so on
; implement quasiquote, let, let*, and, or, cond, match for evalo
; extended mk variant, mixing in deterministic computation where possible
; tagging and pluggable solvers (one in particular)
; aggressive, parallel term guesser
; not complete on its own, but likely more effective for typical synthesis
; analayzes all eval goals for the same term, analyzing the different envs and results
; size-incrementing basic component enumeration
; literals, vars, car/cdrs of everything available in env
; then cons (only as backwards info flow suggests) and predicate applications of components
; note: some primitives may have been shadowed or renamed
; may introduce lambdas when backwards info flow indicates a closure is necessary
; identifying components useful as conditions (capable of partitioning the eval goals)
; not useful unless component expresses both #f and not #f at least once each across envs
; e.g. literals are not useful
; could perform this identification in parallel, for each component over each env
; defer components that are not available in all envs, until conditional splitting
; general size-incrementing component enumeration
; e.g. applying non-primitive procedures (try to avoid unnested self-application/non-termination)
; conditional splitting, producing lambdas, letrecs, etc.
; conditional splitting (if, cond, match, depending on shadowing/complexity)
; if none of if/cond/match are available, and no closures are capable of conditional splitting,
; could potentially refute this line of search early
; if there are basic components useful as conditions, try those before general components
; tagging and reification for =/=, absento
; could do this just for =/= and be satisfied with some infinite absento enumerations
; port everything to chez
; performance and benchmarking
; move from closure-encoding interpreter to ahead-of-time compiler
; tweak mk data reprs
; e.g. try path compression
; try relational arithmetic
; try first-order minicurry tests
; future
; de bruijn encoding interpreter
; could be a useful alternative to closure-encoding for 1st order languages
; try for both dkanren (for comparison) and relational interpreter (may improve perf)
; possible ways to improve performance
; infer impossible scrutinee domains and immediately distypify them (integrate with prefix factoring?)
; pattern prefix factoring (also affects run* termination)
; ideally we'd use full-blown pattern compilation
; but hard to preserve programmer's intended(?) clause search priority with nesting changes
; in contrast factoring only the final clauses will not affect priorities (since nothing follows them)
; match/r, reversible match: manually describe a reversed computation
; should be much better than falling back to denote-rhs-pattern-unknown
; auto-compacting, left-associative binds
; Left-associative binds are preferred because they allow rewards to be
; doled out every time a new conjunct is reached. The downside is that
; left-associative tree structures involve longer paths between the root
; and active leaf nodes of the search, and these paths are traversed down
; and up for every resumption/suspension. To mitigate this overhead we
; can compress contiguous left-associative conjunction chains into a single
; node, unpacking the next conjunct only once it's needed by a successful
; child result. This avoids the overhead along any portion of a chain that
; hasn't yet encountered a child success disjunction, but we'd also like to
; recognize when we can safely recompact. It's safe to recompact
; left-associative conjuncts when there are no intervening disjunctions.
; Intervening disjunctions may come and go either due to branch failure, or
; to a successful branch continually being promoted (it was originally
; promoted in, causing the disruption, but now succeeded again, so it's
; promoted up and out). If we track the type of suspension thunks that are
; returned to bind, to differentiate between (outermost) conjunction and
; disjunction thunks, we can gradually recompact: when returning a
; conjunction thunk to a conjunction, incorporate the chain of the returned
; conjunction into the parent.
; profiling results
; quine:
; match-chain-try loop: 58.6%, 27.0%
; pattern-exec-and: 54.2%, 2.1%
; thrine:
; match-chain-try loop: 84.3%, 23.1%
; pattern-exec-and: 77.5%, 4.6%
; pattern-assert-==: 32.1%, 21.4%
; append (cdr xs):
; state-resume-det loop1 94.6%, 0%
; match-chain-try loop: 79.7%, 45.5%
; append more:
; match-chain-try loop: 92.1%, 75.8%
; arithmetic:
; retry: 73.6%, 1.4%
; match-chain-try loop: 69.3%, 16.3%
; pattern-exec-and: 42.8%, 13.3%
; pattern-assert-or: 31.8%, 1.4%
; pattern-assert-==: 28.5%, 12.3%
; pattern-assert-pair: 27.6%, 0%
; unify: 17.6%, 10.8%
; val-depend: 6.8%
; "define record" for portability to chez
(define-syntax defrec
(syntax-rules ()
((_ name fnames ...) (struct name (fnames ...) #:transparent))))
(define-syntax let*/and
(syntax-rules ()
((_ () rest ...) (and rest ...))
((_ ((name expr) ne* ...) rest ...)
(let ((name expr))
(and name (let*/and (ne* ...) rest ...))))))
(define-syntax let/if
(syntax-rules ()
((_ (name expr) true-alt false-alt)
(let ((name expr)) (if name true-alt false-alt)))))
(define-syntax let/list
(syntax-rules ()
((_ loop ((ncar ncdr expr) binding ...) pair-alt else-alt)
(let loop ((npair expr) binding ...)
(match npair
(`(,ncar . ,ncdr) pair-alt)
('() else-alt))))))
(define store-empty (hasheq))
(define store-ref hash-ref)
(define store-set hash-set)
(define store-remove hash-remove)
(define store-keys hash-keys)
(define (list-add-unique xs v) (if (memq v xs) xs (cons v xs)))
(define (list-cons-unique x xs) (if (memq x xs) xs (cons x xs)))
(define (list-append-unique xs ys)
(if (null? xs) ys
(let ((zs (list-append-unique (cdr xs) ys))
(x0 (car xs)))
(if (memq x0 ys) zs (cons x0 zs)))))
(define (list-subtract xs ys)
(if (null? xs) xs
(let ((x0 (car xs))
(xs1 (list-subtract (cdr xs) ys)))
(if (memq x0 ys) xs1
(if (eq? xs1 (cdr xs)) xs
(cons x0 xs1))))))
(defrec var name)
(define var-0 (var 'initial))
(define (value->vars st val)
(match (walk1 st val)
(`(,a . ,d) (list-append-unique (value->vars st a) (value->vars st d)))
((? var? vr) (list vr))
(_ '())))
(define domain-full '(pair symbol number () #f #t))
(define (domain-remove dmn type) (remove type dmn))
(define (domain-has-type? dmn type)
(or (eq? domain-full dmn) (memq type dmn)))
(define (domain-has-val? dmn val)
(or (eq? domain-full dmn) (memq (match val
((? pair?) 'pair)
((? symbol?) 'symbol)
((? number?) 'number)
(_ val)) dmn)))
(define (domain-overlap? d1 d2)
(cond ((eq? domain-full d1) #t)
((eq? domain-full d2) #t)
(else (let loop ((d1 d1) (d2 d2))
(or (memq (car d1) d2)
(and (pair? (cdr d1)) (loop (cdr d1) d2)))))))
(define (domain-intersect d1 d2)
(cond ((eq? domain-full d1) d2)
((eq? domain-full d2) d1)
(else (let loop ((d1 d1) (d2 d2) (di '()))
(let* ((d1a (car d1))
(d1d (cdr d1))
(d2d (memq d1a d2))
(di (if d2d (cons (car d1) di) di))
(d2d (if d2d (cdr d2d) d2)))
(if (or (null? d1d) (null? d2d))
(if (null? di) #f (reverse di))
(loop d1d d2d di)))))))
; The state-vs will contain either vattr records or terms on the right hand side
(defrec vattr
domain ; type constraints, but not concrete values. Because we don't use vattrs for known terms, this domain
; will never be just #f or just #t or just ().
=/=s ; Disequality constraint information. Only has individual pairs, not =/=* info as in faster-miniKanren.
goals ; (list symbol) identifying entries in state-goals. (This indirection saves us from running a goal
; multiple times when it appears attached to different variables or otherwise is multiply scheduled).
; Includes any goal for which this variable is a blocker, or for which this variable represents the result of
; the match statement represented by the goal
dependencies ; (list symbol) identifying entries in state-goals
; A subset of goals, just including the goals for which this variable represents the result of
; the match statement represented by the goal except for those that have not been scheduled
; as a result of dependency analysis. Gets smaller as scheduling sets up execution with binds.
)
(define (vattrs-get vs vr) (store-ref vs vr vattr-empty))
(define vattrs-set store-set)
(define vattr-empty (vattr domain-full '() '() '()))
(define (vattr-domain-set va dmn)
(vattr dmn (vattr-=/=s va) (vattr-goals va) (vattr-dependencies va)))
(define (vattr-=/=s-clear va)
(vattr (vattr-domain va) '() (vattr-goals va) (vattr-dependencies va)))
(define (state-vattr-=/=s-add st vr va val)
(if (or (var? val) (domain-has-val? (vattr-domain va) val))
(let ((=/=s (vattr-=/=s va)))
(if (memq val =/=s) st
(state-var-set
st vr (vattr (vattr-domain va)
(cons val =/=s)
(vattr-goals va)
(vattr-dependencies va)))))
st))
(define (vattr-=/=s-add va val)
(if (or (var? val) (domain-has-val? (vattr-domain va) val))
(let ((=/=s (vattr-=/=s va)))
(if (memq val =/=s) va
(vattr (vattr-domain va)
(cons val =/=s)
(vattr-goals va)
(vattr-dependencies va))))
va))
(define (vattr-=/=s-has? va val) (memq val (vattr-=/=s va)))
(define (vattr-associate va goal)
(vattr (vattr-domain va)
(vattr-=/=s va)
(list-cons-unique goal (vattr-goals va))
(vattr-dependencies va)))
(define (vattr-associate* va goals)
(vattr (vattr-domain va)
(vattr-=/=s va)
(list-append-unique goals (vattr-goals va))
(vattr-dependencies va)))
(define (vattr-depend va goal)
(vattr (vattr-domain va)
(vattr-=/=s va)
(list-cons-unique goal (vattr-goals va))
(list-cons-unique goal (vattr-dependencies va))))
(define (vattr-depend* va goals)
(vattr (vattr-domain va)
(vattr-=/=s va)
(list-append-unique goals (vattr-goals va))
(list-append-unique goals (vattr-dependencies va))))
(define (vattr-goals-clear va)
(vattr (vattr-domain va) (vattr-=/=s va) '() (vattr-dependencies va)))
(define (vattr-dependencies-clear va)
(vattr (vattr-domain va) (vattr-=/=s va) (vattr-goals va) '()))
(define (vattr-overlap? va1 va2)
(domain-overlap? (vattr-domain va1) (vattr-domain va2)))
(define (vattr-intersect va1 va2)
(let*/and ((di (domain-intersect (vattr-domain va1) (vattr-domain va2))))
(vattr di
(list-append-unique (vattr-=/=s va1) (vattr-=/=s va2))
(append (vattr-goals va1) (vattr-goals va2))
(append (vattr-dependencies va1)
(vattr-dependencies va2)))))
; These appear as values in state-goals
; All goal-suspendeds are created as the result of a suspended match
(defrec goal-suspended
tag ; Not yet used. Intent is that user could tag match statements with arbitrary data that says
; what kind of expression it is. Then a meta-process could inspect the goal store and group goals
; by type for its reasoning and rescheduling purposes, or solving with a domain-specific solver
result ; Used for the same purpose as tag, but stores the result of the underlying match statement.
blockers ; Variables, that if bound, may allow this goal to run deterministically. Any that are unified will
; trigger this goal for a deterministic attempt.
retry ; Goal (function taking state) to run to resume the goal execution. This one will only attempt deterministic
; computation, and will suspend if a guess must be made.
guess ; Goal (function taking state) to run to resume the goal execution. This one will make a guess and create an
; mplus subtree.
active? ; If #f, then this is a lazy match
)
(define (goal-ref-new) (gensym))
(define (goal-retry goals goal)
(if (procedure? goal) goal
(let*/and ((gsusp (store-ref goals goal #f)))
(goal-suspended-retry gsusp))))
(define (goal-block-cons block blocks)
(if (null? block) blocks (cons block blocks)))
(defrec schedule det nondet)
(define schedule-empty (schedule '() '()))
(define (schedule-add-det sch det)
(schedule (goal-block-cons det (schedule-det sch))
(schedule-nondet sch)))
(define (schedule-add-nondet sch nondet)
(schedule (schedule-det sch)
(goal-block-cons nondet (schedule-nondet sch))))
(define (schedule-add sch det nondet)
(schedule (goal-block-cons det (schedule-det sch))
(goal-block-cons nondet (schedule-nondet sch))))
(define (schedule-clear-det sch)
(schedule '() (schedule-nondet sch)))
(defrec state vs goals schedule)
(define state-empty (state store-empty store-empty schedule-empty))
(define (state-var-get st vr) (vattrs-get (state-vs st) vr))
(define (state-var-set st vr va)
(state (vattrs-set (state-vs st) vr va)
(state-goals st)
(state-schedule st)))
(define (state-suspend st forward? vr goal)
(state-var-set
st vr (let ((va (state-var-get st vr)))
(if forward?
(vattr-associate va goal)
(vattr-depend va goal)))))
(define (state-suspend* st var-forwards var-backwards goal-ref goal)
(define (update vattr-add vs vrs)
(foldl (lambda (vr vs)
(vattrs-set vs vr (vattr-add (vattrs-get vs vr) goal-ref)))
vs vrs))
(let* ((goals (store-set (state-goals st) goal-ref goal))
(vs (state-vs st))
(vs (update vattr-associate vs var-forwards) )
(active? (and (goal-suspended? goal) (goal-suspended-active? goal)))
(vs (update
(if active? vattr-depend vattr-associate) vs var-backwards)))
(state vs goals (let ((sch (state-schedule st)))
(if (and (null? var-backwards) active?)
(schedule-add-nondet sch (list goal-ref))
sch)))))
(define (state-goals-set st goals)
(state (state-vs st) goals (state-schedule st)))
(define (state-remove-goal st goal)
(state-goals-set st (store-remove (state-goals st) goal)))
(define (state-schedule-clear-det st)
(state (state-vs st) (state-goals st) (schedule-clear-det
(state-schedule st))))
(define (state-schedule-set st sch) (state (state-vs st) (state-goals st) sch))
(define (state-schedule-clear st) (state-schedule-set schedule-empty))
(define det-quota 200)
(define det-cost 0)
(define (det-reset) (set! det-cost 0))
(define (det-pay cost)
(let ((next-cost (+ cost det-cost)))
(if (> det-quota next-cost)
(set! det-cost next-cost)
(begin (set! det-cost 0) (shift k k)))))
(define-syntax reset-cost
(syntax-rules ()
((_ body ...) (let ((result (reset body ...)))
(det-reset)
result))))
(define (state-resume-det1 st)
(let* ((det (schedule-det (state-schedule st)))
(st (state-schedule-clear-det st)))
(let/list loop ((goals det det) (st st))
(let/list loop1 ((goal goals goals) (st st))
(let/if (retry (goal-retry (state-goals st) goal))
(let*/and ((st (retry st))
(st (state-resume-det1 st)))
(loop1 goals st))
(loop1 goals st))
(loop det st))
st)))
(define (state-resume-nondet1 st)
(let* ((sgoals (state-goals st))
(nondet (schedule-nondet (state-schedule st))))
(let/list loop ((goals nondet (reverse nondet)) (vs (state-vs st)))
(let/list loop1 ((goal goals1 goals))
(let/if (gsusp (store-ref sgoals goal #f))
(let/list loop2 ((blocker blockers (goal-suspended-blockers gsusp)))
(let-values (((blocker va) (walk-vs vs blocker)))
(let ((deps (vattr-dependencies va)))
(if (null? deps) (loop2 blockers)
(loop
(cons deps (cons (cons goal goals1) nondet))
(vattrs-set vs blocker (vattr-dependencies-clear va))))))
(let ((sch-next (schedule '() (reverse (cons (cons goal goals1) nondet)))))
; Interesting bit for (demanded) search tree structure!
; Greg thinks this would better as a left-associative bind instead of
; the right-associative one resulting from the current recursion structure.
; That is, (bind (bind (bind guess resume-pending) sch-next(0)) sch-next(1)) etc
(bind
(bind ((goal-suspended-guess gsusp)
(state vs sgoals schedule-empty))
state-resume-pending)
(lambda (st)
(state-resume-nondet1 (state-schedule-set st sch-next))))))
(loop1 goals1))
(loop nondet vs))
(state vs sgoals schedule-empty))))
(define (state-resume-pending st)
(bind (reset-cost (state-resume-det1 st)) state-resume-nondet1))
; This runs goals that are not demanded
(define (state-resume-remaining st)
(define sgoals (state-goals st))
(define all (store-keys sgoals))
(let/list loop ((goal-ref goal-refs all) (active '()))
(let ((gsusp (store-ref sgoals goal-ref)))
(if (goal-suspended-active? gsusp)
(loop goal-refs (cons goal-ref active))
(loop goal-refs active)))
(if (null? active)
(if (null? all) st
; TODO: also force remaining unnamed goals from vattrs
(bind
(state-resume-nondet1
(state-schedule-set st (schedule '() (list all))))
state-resume-remaining))
; If there's undemanded by not lazy stuff, do it. Currently no hierarchy between them.
(bind (state-resume-nondet1
(state-schedule-set st (schedule '() (list active))))
state-resume-remaining))))
; First run everything demanded; only after those and those they generate are done, then do undemanded
(define (state-resume st)
(bind (state-resume-pending st) state-resume-remaining))
(define (state-var-domain-set st vr va dmn)
(match dmn
(`(,(and (not 'symbol) (not 'number) singleton))
(state-var-== st vr va (if (eq? 'pair singleton)
`(,(var 'pair-a) . ,(var 'pair-d)) singleton)))
('() #f)
(dmn (let ((st (state-var-set st vr (vattr-domain-set va dmn))))
(if (eq? domain-full dmn) st
(state (state-vs st)
(state-goals st)
(schedule-add (state-schedule st)
(vattr-goals va)
(vattr-dependencies va))))))))
(define (state-var-domain-== st vr va dmn)
(let*/and ((dmn (domain-intersect (vattr-domain va) dmn)))
(state-var-domain-set st vr va dmn)))
(define (state-var-type-== st vr va type)
(and (domain-has-type? (vattr-domain va) type)
(state-var-domain-set st vr va `(,type))))
(define (state-var-type-=/= st vr va type)
(state-var-domain-set st vr va (domain-remove (vattr-domain va) type)))
;; Ideally we would notify any vars in =/=s that they can drop 'vr' from their
;; own =/=s, but not doing so shouldn't be a big deal. Same story when
;; handling state-var-==-var.
(define (state-var-== st vr va val)
(cond
((eq? vattr-empty va) (state-var-set st vr val))
((domain-has-val? (vattr-domain va) val)
(let ((=/=s (vattr-=/=s va)))
(and (not (memq val =/=s))
(let* ((vps (filter (if (pair? val)
(lambda (x) (or (var? x) (pair? x)))
var?) =/=s))
(deps (vattr-dependencies va))
(vs (if (null? deps) (state-vs st)
(let val-depend ((vs (state-vs st)) (val val))
(match val
(`(,pa . ,pd) (val-depend (val-depend vs pa) pd))
((? var? evr)
(let-values (((evr eva) (walk-vs vs evr)))
(if (var? evr)
(store-set vs evr (vattr-depend* eva deps))
(val-depend vs evr))))
(_ vs)))))
(st (state (store-set vs vr val)
(state-goals st)
(schedule-add (state-schedule st)
(vattr-goals va)
deps))))
(disunify* st val vps)))))
(else #f)))
(define (state-var-=/= st vr va val)
(if (or (eq? '() val) (eq? #f val) (eq? #t val))
(state-var-type-=/= st vr va val)
(state-vattr-=/=s-add st vr va val)))
(define (state-var-==-var st vr1 va1 vr2 va2)
(let*/and ((va (vattr-intersect va1 va2)))
(let* ((=/=s (vattr-=/=s va))
(va (vattr-=/=s-clear va))
(st (state-var-set st vr1 vr2))
(st (state (state-vs st)
(state-goals st)
(schedule-add-det (state-schedule st) (vattr-goals va))))
(va (vattr-goals-clear va)))
(disunify* (state-var-set st vr2 va) vr2 =/=s))))
(define (state-var-=/=-var st vr1 va1 vr2 va2)
(if (vattr-overlap? va1 va2)
(state-vattr-=/=s-add (state-vattr-=/=s-add st vr1 va1 vr2) vr2 va2 vr1)
st))
(define (state-var-=/=-redundant? st vr va val)
(or (not (domain-has-val? (vattr-domain va) val))
(vattr-=/=s-has? va val)))
(define (state-var-=/=-var-redundant? st vr1 va1 vr2 va2)
(or (not (vattr-overlap? va1 va2))
(vattr-=/=s-has? va1 vr2)
(vattr-=/=s-has? va2 vr1)))
(define (walk-vs vs vr)
(let ((va (vattrs-get vs vr)))
(cond ((vattr? va) (values vr va))
((var? va) (walk-vs vs va))
(else (values va #f)))))
(define (walk st tm)
(if (var? tm)
(walk-vs (state-vs st) tm)
(values tm #f)))
(define (walk1 st tm) (let-values (((val va) (walk st tm))) val))
(define (not-occurs? st vr tm)
(if (pair? tm) (let-values (((ht _) (walk st (car tm))))
(let*/and ((st (not-occurs? st vr ht)))
(let-values (((tt _) (walk st (cdr tm))))
(not-occurs? st vr tt))))
(if (eq? vr tm) #f st)))
(define (unify st v1 v2)
(let-values (((v1 va1) (walk st v1))
((v2 va2) (walk st v2)))
(cond ((eq? v1 v2) st)
((var? v1) (if (var? v2)
(state-var-==-var st v1 va1 v2 va2)
(and (not-occurs? st v1 v2)
(state-var-== st v1 va1 v2))))
((var? v2) (and (not-occurs? st v2 v1)
(state-var-== st v2 va2 v1)))
((and (pair? v1) (pair? v2))
(let*/and ((st (unify st (car v1) (car v2))))
(unify st (cdr v1) (cdr v2))))
(else #f))))
(define (disunify* st v1 vs)
(if (null? vs) st (let*/and ((st (disunify st v1 (car vs))))
(disunify* st v1 (cdr vs)))))
(define (disunify st v1 v2) (disunify-or st v1 v2 '()))
(define (disunify-or-suspend st v1 va1 v2 pairings)
(state-suspend st #t v1 (lambda (st) (disunify-or st v1 v2 pairings))))
(define (disunify-or st v1 v2 pairings)
(let-values (((v1 va1) (walk st v1)))
(disunify-or-rhs st v1 va1 v2 pairings)))
(define (disunify-or-rhs st v1 va1 v2 pairings)
(let-values (((v2 va2) (walk st v2)))
(cond
((eq? v1 v2)
(and (pair? pairings)
(disunify-or st (caar pairings) (cdar pairings) (cdr pairings))))
((var? v1)
(if (null? pairings)
(if (var? v2)
(state-var-=/=-var st v1 va1 v2 va2)
(state-var-=/= st v1 va1 v2))
(if (var? v2)
(if (state-var-=/=-var-redundant? st v1 va1 v2 va2) st
(if (state-var-=/=-var st v1 va1 v2 va2)
(disunify-or-suspend st v1 va1 v2 pairings)
(disunify-or
st (caar pairings) (cdar pairings) (cdr pairings))))
(if (state-var-=/=-redundant? st v1 va1 v2) st
(if (state-var-=/= st v1 va1 v2)
(disunify-or-suspend st v1 va1 v2 pairings)
(disunify-or
st (caar pairings) (cdar pairings) (cdr pairings)))))))
((var? v2)
(if (null? pairings)
(state-var-=/= st v2 va2 v1)
(if (state-var-=/=-redundant? st v2 va2 v1) st
(if (state-var-=/= st v2 va2 v1)
(disunify-or-suspend st v2 va2 v1 pairings)
(disunify-or
st (caar pairings) (cdar pairings) (cdr pairings))))))
((and (pair? v1) (pair? v2))
(disunify-or
st (car v1) (car v2) (cons (cons (cdr v1) (cdr v2)) pairings)))
(else st))))
(define (typify st type val)
(let-values (((val va) (walk st val)))
(if (var? val) (state-var-type-== st val va type)
(and (match type
('symbol (symbol? val))
('number (number? val))
('pair (pair? val))
(_ (eq? type val)))
st))))
(define (distypify st type val)
(let-values (((val va) (walk st val)))
(if (var? val) (state-var-type-=/= st val va type)
(and (not (match type
('symbol (symbol? val))
('number (number? val))
('pair (pair? val))
(_ (eq? type val))))
st))))
(define (domainify st val dmn)
(if (eq? domain-full dmn) st
(let-values (((val va) (walk st val)))
(if (var? val)
(state-var-domain-== st val va dmn)
(and (domain-has-val? dmn val) st)))))
(define (domainify* st val dmn*)
(define d-pair (cdr dmn*))
(let*/and ((st1 (domainify st val (car dmn*))))
(if (pair? d-pair)
(let ((val (walk1 st1 val)))
(if (pair? val)
(let*/and ((st2 (domainify* st1 (car val) (car d-pair))))
(domainify* st2 (cdr val) (cdr d-pair)))
st1))
st1)))
(define (succeed st) st)
(define (fail st) #f)
(define (== t0 t1) (lambda (st) (unify st t0 t1)))
(define (=/= t0 t1) (lambda (st) (disunify st t0 t1)))
(define (symbolo tm) (lambda (st) (typify st 'symbol tm)))
(define (numbero tm) (lambda (st) (typify st 'number tm)))
(define (not-symbolo tm) (lambda (st) (distypify st 'symbol tm)))
(define (not-numbero tm) (lambda (st) (distypify st 'number tm)))
(define (not-pairo tm) (lambda (st) (distypify st 'pair tm)))
(define (absento atom tm)
(dk-evalo
`(letrec ((absent?
(lambda (tm)
(match/lazy tm
(`(,ta . ,td) (and (absent? ta) (absent? td)))
(',atom #f)
(_ #t)))))
(absent? ',tm))
#t))
(define-syntax zzz (syntax-rules () ((_ body ...) (lambda () body ...))))
(define (mplus ss zss)
(match ss
(#f (zss))
((? procedure?) (zzz (mplus (zss) ss)))
((? state?) (cons ss zss))
(`(,result . ,zss1) (cons result (zzz (mplus (zss) zss1))))))
(define (take n ss)
(if (and n (zero? n)) '()
(match ss
(#f '())
((? procedure?) (take n (ss)))
((? state?) (list ss))
(`(,result . ,ss) (cons result (take (and n (- n 1)) ss))))))
(define (bind ss goal)
(match ss
(#f #f)
((? procedure?) (zzz (bind (ss) goal)))
((? state?) (goal ss))
(`(,result . ,zss) (mplus (goal result) (zzz (bind (zss) goal))))))
(define-syntax bind*
(syntax-rules ()
((_ e) e)
((_ e goal0 goal ...) (bind* (bind e goal0) goal ...))))
(define-syntax let/vars
(syntax-rules ()
((_ (vname ...) body ...)
(let ((vname (var (gensym (symbol->string 'vname)))) ...) body ...))))
(define-syntax fresh
(syntax-rules ()
((_ (vname ...) goal ...)
(let/vars (vname ...) (lambda (st) (bind* st goal ...))))))
(define (reify-var ix) (string->symbol (string-append "_." (number->string ix))))
(define (reify tm)
(lambda (st)
(let-values
(((st ixs tm)
(let loop ((st st) (ixs store-empty) (tm tm))
(let-values (((tm va) (walk st tm)))
(cond
((var? tm)
(let/if (ix (store-ref ixs tm #f))
(values st ixs (reify-var ix))
(let ((ix (hash-count ixs)))
(values st (store-set ixs tm ix) (reify-var ix)))))
((pair? tm)
(let*-values (((st ixs thd) (loop st ixs (car tm)))
((st ixs ttl) (loop st ixs (cdr tm))))
(values st ixs (cons thd ttl))))
(else (values st ixs tm)))))))
tm)))
(define-syntax run
(syntax-rules ()
((_ n (qv ...) goal ...)
(map (reify var-0)
(take n (zzz ((fresh (qv ...)
(== (list qv ...) var-0) goal ... state-resume)
state-empty)))))))
(define-syntax run* (syntax-rules () ((_ body ...) (run #f body ...))))
(define (quotable? v)
(match v
(`(,a . ,d) (and (quotable? a) (quotable? d)))
((? procedure?) #f)
(_ #t)))
(define (rev-append xs ys)
(if (null? xs) ys (rev-append (cdr xs) (cons (car xs) ys))))
(define-syntax let*/state
(syntax-rules ()
((_ () body ...) (begin body ...))
((_ (((st val) expr) bindings ...) body ...)
(let-values (((st val) expr))
(if st
(let*/state (bindings ...) body ...)
(values #f #f))))))
(define (goal-value val) (lambda (st) (values st val)))
(define (denote-value val) (lambda (env) (goal-value val)))
(define denote-true (denote-value #t))
(define denote-false (denote-value #f))
(define (denote-lambda params body senv)
(match params
((and (not (? symbol?)) params)
(let ((dbody (denote-term body (extend-env* params params senv)))
(nparams (length params)))
(lambda (env)
(goal-value
(lambda args
(let ((nargs (length args)))
(when (not (= nparams nargs))
(error
(format
"expected ~a args, given ~a; params=~v, body=~v, args=~v"
nparams nargs params body args))))
(dbody (rev-append args env)))))))
(sym
(let ((dbody (denote-term body `((val . (,sym . ,sym)) . senv))))
(lambda (env) (goal-value (lambda args (dbody (cons args env)))))))))
(define (denote-variable sym senv)
(let loop ((idx 0) (senv senv))
(match senv
(`((val . (,y . ,b)) . ,rest)
(if (equal? sym y)
(lambda (env) (goal-value (list-ref env idx)))
(loop (+ idx 1) rest)))
(`((rec . ,binding*) . ,rest)
(let loop-rec ((ridx 0) (binding* binding*))
(match binding*
('() (loop (+ idx 1) rest))
(`((,p-name ,_) . ,binding*)
(if (equal? sym p-name)
(lambda (env)
((list-ref (list-ref env idx) ridx) (drop env idx)))
(loop-rec (+ ridx 1) binding*))))))
('() (error (format "unbound variable: '~a'" sym))))))
(define (denote-qq qqterm senv)
(match qqterm
(`(,'unquote ,term) (denote-term term senv))
(`(,a . ,d) (let ((da (denote-qq a senv)) (dd (denote-qq d senv)))
(lambda (env)
(let ((ga (da env)) (gd (dd env)))
(lambda (st)
(let*/state (((st va) (ga st))
((st va) (actual-value st va #f #f))
((st vd) (gd st))
((st vd) (actual-value st vd #f #f)))
(values st `(,va . ,vd))))))))
((? quotable? datum) (denote-value datum))))
(define (denote-application proc a* senv)
(denote-apply (denote-term proc senv) (denote-term-list a* senv)))
(define (denote-apply dp da*)
(lambda (env)
(let ((gp (dp env)) (ga* (da* env)))
(lambda (st)
(let*/state (((st va*) (ga* st)) ((st vp) (gp st)))
((apply vp va*) st))))))
(define (denote-term-list terms senv)
(let ((d* (map (lambda (term) (denote-term term senv)) terms)))
(lambda (env)
(let ((g* (map (lambda (d0) (d0 env)) d*)))
(lambda (st)
(let loop ((st st) (xs '()) (g* g*))
(if (null? g*) (values st (reverse xs))
(let*/state (((st val) ((car g*) st))
((st val) (actual-value st val #f #f)))
(loop st (cons val xs) (cdr g*))))))))))
(define (denote-rhs-pattern-unknown env st v) st)
(define (denote-rhs-pattern-literal literal)
(lambda (env st v) (unify st literal v)))
(define (denote-rhs-pattern-var vname senv)
(let ((dv (denote-term vname senv)))
(lambda (env st rhs)
(let*/state (((st v) ((dv env) st))) (unify st v rhs)))))
(define (denote-rhs-pattern-qq qq senv)
(match qq
(`(,'unquote ,pat) (denote-rhs-pattern pat senv))
(`(,a . ,d)
(let ((da (denote-rhs-pattern-qq a senv))
(dd (denote-rhs-pattern-qq d senv)))
(lambda (env st v)
(let/vars (va vd)
(let ((v1 `(,va . ,vd)))
(let*/and ((st (unify st v v1)) (st (da env st va)))
(dd env st vd)))))))
((? quotable? datum) (denote-rhs-pattern-literal datum))))
(define denote-rhs-pattern-true (denote-rhs-pattern-literal #t))
(define denote-rhs-pattern-false (denote-rhs-pattern-literal #f))
(define (denote-rhs-pattern pat senv)
(match pat
(`(quote ,(? quotable? datum)) (denote-rhs-pattern-literal datum))
(`(quasiquote ,qq) (denote-rhs-pattern-qq qq senv))
((? symbol? vname) (denote-rhs-pattern-var vname senv))
((? number? datum) (denote-rhs-pattern-literal datum))
(#t denote-rhs-pattern-true)
(#f denote-rhs-pattern-false)
(_ denote-rhs-pattern-unknown)))
(define (extract-svs st v1 v2)
(let-values (((v1 va1) (walk st v1))
((v2 va2) (walk st v2)))
(match* (v1 v2)
(((? var?) (? var?)) (list v1 v2))
(((? var?) _) (list v1))
((_ (? var?)) (list v2))
((`(,a1 . ,d1) `(,a2 . ,d2))
(list-append-unique (extract-svs st a1 a2) (extract-svs st d1 d2)))
((_ _) '()))))
(define p-any '(_))
(define (p-lookup path) `(lookup ,path))
(define (p-literal datum) `(literal ,datum))
(define (p-type tag) `(type ,tag))
(define p-symbol (p-type 'symbol))
(define p-number (p-type 'number))
(define p-pair (p-type 'pair))
(define (p-car p) `(car ,p))
(define (p-cdr p) `(cdr ,p))
(define (p-and p1 p2) `(and ,p1 ,p2))
(define (p-or p1 p2) `(or ,p1 ,p2))
(define (p-not p) `(not ,p))
(define (p-? pred) `(? ,pred))
(define p-none (p-not p-any))
(define (p-and* p*)
(match p*
('() p-any)
(`(,p) p)
(`(,p . ,p*) (p-and p (p-and* p*)))))
(define (p-or* p*)
(match p*
('() p-none)
(`(,p) p)
(`(,p . ,p*) (p-or p (p-or* p*)))))
(define (datum->didx datum)
(match datum
(`(,_ . ,_) 0)
((? symbol?) 1)
((? number?) 2)
('() 3)
(#f 4)
(#t 5)))
(define (tag->didx tag)
(match tag
('pair 0)
('symbol 1)
('number 2)
('() 3)
(#f 4)
(#t 5)))
(define (p->domain parity p)
(define not-pair (pdomain-complement (pdomain-single (tag->didx 'pair))))
(define (paritize parity pd) (if parity pd (pdomain-complement pd)))
(define (paritize-pair parity ppd)
(if parity ppd (pdomain-join ppd not-pair)))
(match p
(`(literal ,datum)
(match datum
((or '() #f #t) (p->domain parity (p-type datum)))
(`(,dcar . ,dcdr)
(paritize-pair parity (pdomain-single-pair
(cons (p->domain parity (p-literal dcar))
(p->domain parity (p-literal dcdr))))))
(_ (if parity (pdomain-single (datum->didx datum)) pdomain-full))))
(`(type ,tag) (paritize parity (pdomain-single (tag->didx tag))))
(`(car ,p)
(paritize-pair parity (pdomain-single-pair
(cons (p->domain parity p) pdomain-full))))
(`(cdr ,p)
(paritize-pair parity (pdomain-single-pair
(cons pdomain-full (p->domain parity p)))))
(`(and ,p1 ,p2) ((if parity pdomain-meet pdomain-join)
(p->domain parity p1) (p->domain parity p2)))
(`(or ,p1 ,p2) ((if parity pdomain-join pdomain-meet)
(p->domain parity p1) (p->domain parity p2)))
(`(not ,p) (p->domain (not parity) p))
('(_) (if parity pdomain-full pdomain-empty))
(`(lookup ,_) pdomain-full)
(`(? ,_) pdomain-full)))
(define (pdomain pair symbol number nil f t)
(vector pair symbol number nil f t))
(define (pdomain-pair pd) (vector-ref pd 0))
(define (pdomain-set pd idx v)
(define pd1 (vector-copy pd))
(vector-set! pd1 idx v)
pd1)
(define (pdomain-add pd idx) (pdomain-set pd idx #t))
(define (pdomain-add-pair pd v)
(pdomain-set
pd 0 (and (not (or (equal? pdomain-empty (car v))
(equal? pdomain-empty (cdr v))))
(or (and (equal? pdomain-full (car v))
(equal? pdomain-full (cdr v)))
v))))
(define (pdomain-remove pd idx) (pdomain-set pd idx #f))
(define (pdomain-remove-pair pd) (pdomain-remove pd 0))
(define (pdomain-complement pd)
(let ((v1 (vector-map not pd)) (pr (pdomain-pair pd)))
(if (pair? pr)
(pdomain-add-pair v1 (cons (pdomain-complement (car pr))
(pdomain-complement (cdr pr))))
v1)))
(define (pdomain-meet pd1 pd2)
(let ((v1 (vector-map (lambda (a b) (not (not (and a b)))) pd1 pd2))
(pr1 (pdomain-pair pd1))
(pr2 (pdomain-pair pd2)))
(if (pdomain-pair v1)
(if (pair? pr1)
(if (pair? pr2)
(pdomain-add-pair v1 (cons (pdomain-meet (car pr1) (car pr2))
(pdomain-meet (cdr pr1) (cdr pr2))))
(pdomain-add-pair v1 pr1))
(if (pair? pr2)
(pdomain-add-pair v1 pr2)
v1))
v1)))
(define (pdomain-join pd1 pd2)
(let ((v1 (vector-map (lambda (a b) (not (not (or a b)))) pd1 pd2))
(pr1 (pdomain-pair pd1))
(pr2 (pdomain-pair pd2)))
(if (pair? pr1)
(pdomain-add-pair v1 (if (pair? pr2)
(cons (pdomain-join (car pr1) (car pr2))
(pdomain-join (cdr pr1) (cdr pr2)))
(if pr2 (cons pdomain-full pdomain-full) pr1)))
(if (pair? pr2)
(pdomain-add-pair v1 (if pr1 (cons pdomain-full pdomain-full) pr2))
v1))))
(define (pdomain-single idx) (pdomain-add pdomain-empty idx))
(define (pdomain-single-pair v) (pdomain-add-pair pdomain-empty v))
(define pdomain-empty (pdomain #f #f #f #f #f #f))
(define pdomain-full (pdomain-complement pdomain-empty))
(define tag*didx
'((pair . 0)
(symbol . 1)
(number . 2)
(() . 3)
(#f . 4)
(#t . 5)))
(define domain*-full (cons domain-full #t))
(define (pdomain->domain pd)
(let loop ((t*d tag*didx) (dmn domain-full))
(match t*d
(`((,tag . ,idx) . ,t*d)
(loop t*d (if (vector-ref pd idx) dmn
(domain-remove dmn tag))))
(_ dmn))))
(define (pdomain->domain* pd)
(define dmn (pdomain->domain pd))
(if (eq? domain-full dmn) domain*-full
(cons dmn
(let*/and ((pd-pair (vector-ref pd 0)))
(or (eq? #t pd-pair)
(cons (pdomain->domain* (car pd-pair))
(pdomain->domain* (cdr pd-pair))))))))
(define (lookup/access access st v)
(if (pair? v)
(values st (walk1 st (access v)))
(let/vars (va vd)
(let ((v1 `(,va . ,vd)))
(let ((st1 (unify st v1 v)))
(if st1
(values st1 (walk1 st1 (access v1)))
(values #f #f)))))))
(define (lookup/car st v) (lookup/access car st v))
(define (lookup/cdr st v) (lookup/access cdr st v))
(define (path-lookup path st v)
(if (null? path) (values st v)
(let-values (((st1 v1) ((car path) st v)))
(if st1
(path-lookup (cdr path) st1 v1)
(values #f #f)))))
(define (prhs-unknown env st rhs vtop) st)
(define (prhs-literal datum) (lambda (env st rhs vtop) (unify st datum rhs)))
(define (prhs-var dv)
(lambda (env st rhs vtop)
(let*/state (((st v) ((dv env) st))) (unify st v rhs))))
(define (prhs-cons pa pd)
(lambda (env st rhs vtop)
(let/vars (va vd)
(let ((rhs1 `(,va . ,vd)))
(let*/and ((st (unify st rhs1 rhs)) (st (pa env st va vtop)))
(pd env st vd vtop))))))
(define (prhs-lookup path)
(lambda (env st rhs vtop)
(let-values (((st1 v1) (path-lookup path st vtop)))
(and st1 (unify st1 v1 rhs)))))
(define p-any-assert (lambda (env st v vtop) (values st '())))
(define p-none-assert (lambda (env st v vtop) (values #f #f)))
(define (p->assert p parity)
(define (cx->assert cx ncx)
(define cx0 (if parity cx ncx))
(define cx1 (if parity ncx cx))
(lambda (arg)
(lambda (env st v vtop)
(let/if (st1 (cx0 st arg v))
(let/if (nst (cx1 st arg v))
(values st1 (extract-svs st arg v))
(values st '()))
(values #f #f)))))
(define (pair->assert tag trans p)
(define assert (p->assert p parity))
(lambda (env st v vtop)
(let/vars (va vd)
(let ((v1 `(,va . ,vd)))
(let/if (st1 (unify st v1 v))
(let-values (((st2 svs) (assert env st1 (trans v1) vtop)))
(values st2 (and svs (list-subtract svs (list va vd)))))
(if parity (values #f #f) (values st '())))))))
(define (and->assert p1 p2)
(define a1 (p->assert p1 parity))
(define a2 (p->assert p2 parity))
(lambda (env st v vtop)
(let-values (((st1 svs1) (a1 env st v vtop)))
(if st1
(let-values (((st2 svs2) (a2 env st1 v vtop)))
(if st2
(values st2 (list-append-unique svs1 svs2))
(values #f #f)))
(values #f #f)))))
(define (or->assert p1 p2)
(define or-rhs (cons prhs-unknown (rhs->drhs #t '() '())))
(define clause* `((,p1 . ,or-rhs) (,p2 . ,or-rhs)))
(define dmc (index->dmc (clauses->index clause*) #f))
(lambda (env st v vtop)
(let-values (((st mc) (dmc env st v vtop)))
(let-values (((st svs result) (mc-try-run mc st #f #t)))
(if (match-chain? result)
(values
(mc-suspend st #f result svs #t)
svs)
(values st svs))))
(values #f #f)))
(define (pred->assert dpred)
(define assert-not-false (p->assert (p-literal #f) (not parity)))
(lambda (env st v vtop)
(let-values (((st0 vpred) ((dpred env) #t)))
(if (not st0)
(error (format "invalid predicate: ~a" dpred))
(let-values (((st result) ((vpred v) st)))
(if (not st)
; TODO: if (not st), the entire computation needs to fail, not just this
; particular pattern assertion. This failure needs to cooperate with
; nondeterministic search, which makes things more complex and likely
; less efficient (negations of conjunctions containing predicates become
; mandatory, to verify that the predicate invocation, if reached, returns
; a value). For now, we'll assume a predicate can never fail in this
; manner.
(error (format "predicate failed: ~a" dpred))
(if (match-chain? result)
(let-values (((st svs result) (mc-try-run result st #f #f)))
(if (match-chain? result)
(let-values (((st rhs)
(if parity
(let/vars (notf)
(values (disunify st notf #f) notf))
(values st #f))))
(let-values (((st result)
(actual-value st result #t rhs)))
(if st (values st svs) (values #f #f))))
(assert-not-false st result)))
(assert-not-false st result))))))))
(match p
('(_) (if parity p-any-assert p-none-assert))
(`(lookup ,path)
(let ((arg->assert (cx->assert unify disunify)))
(lambda (env st v vtop)
(let-values (((st1 v1) (path-lookup path st vtop)))
(if st1
((arg->assert v1) env st1 v vtop)
(if parity (values #f #f) (values st '())))))))
(`(literal ,datum) ((cx->assert unify disunify) datum))
(`(type ,tag) ((cx->assert typify distypify) tag))
(`(car ,p) (pair->assert 'car car p))
(`(cdr ,p) (pair->assert 'cdr cdr p))
(`(and ,p1 ,p2) (if parity (and->assert p1 p2) (or->assert p1 p2)))
(`(or ,p1 ,p2) (if parity (or->assert p1 p2) (and->assert p1 p2)))
(`(not ,p) (p->assert p (not parity)))
(`(? ,dpred) (pred->assert dpred))))
(define (pat-prune p parity st v vtop)
(define always (if parity p-any p-none))
(define never (if parity p-none p-any))
(define (always? p) (eq? always p))
(define (never? p) (eq? never p))
(define (prune-cx st cx ncx arg)
(let/if (st1 ((if parity cx ncx) st arg v))
(let/if (nst ((if parity ncx cx) st arg v))
(values st1 p)
(values st always))
(values #f #f)))
(define (prune-pair tag trans p)
(let/vars (va vd)
(let ((v1 `(,va . ,vd)))
(let/if (st1 (unify st v1 v))
(let-values (((st2 p) (pat-prune p parity st1 (trans v1) vtop)))
(if st2
(if (always? p)
(if parity
(pat-prune p-pair #t st v vtop)
(values st p))
(values st2 `(,tag ,p)))
(values #f #f)))
(if parity
(values #f #f)
(pat-prune p-pair #f st v vtop))))))
(define (prune-and p1 p2)
(let-values (((st1 p1) (pat-prune p1 parity st v vtop)))
(if st1
(let-values (((st2 p2) (pat-prune p2 parity st1 v vtop)))
(if st2
(values
st2 (if (always? p2) p1
(let-values (((st2 _) (pat-prune p2 parity st v vtop)))
(let-values (((_ p1) (pat-prune p1 parity st2 v vtop)))
(if (always? p1) p2
`(,(if parity 'and 'or) ,p1 ,p2))))))
(values #f #f)))
(values #f #f))))
(define (prune-or p1 p2)
(let-values (((st1 p1-new) (pat-prune p1 parity st v vtop)))
(if st1
(let-values (((nst1 _) (pat-prune p1-new (not parity) st v vtop)))
(if nst1
(let-values (((st2 p2) (pat-prune p2 parity nst1 v vtop)))
(if st2
(if (always? p2) (values st always)
(let-values
(((nst2 _) (pat-prune p2 (not parity) st v vtop)))
(let-values (((st1 p1-new)
(pat-prune p1-new parity nst2 v vtop)))
(if st1
(if (always? p1-new) (values st always)
(values st `(,(if parity 'or 'and) ,p1-new ,p2)))
(values st2 p2)))))
(values st1 p1-new)))
(values st always)))
(pat-prune p2 parity st v vtop))))
(define (lookup->pat path st v1)
(let ((v1 (walk1 st v1)))
(and (not (var? v1))
(if (pair? v1)
(let* ((pcar (lookup->pat path st (car v1)))
(pcdr (lookup->pat path st (cdr v1))))
(match* (pcar pcdr)
((`(literal ,lcar) `(literal ,lcdr)) (p-literal (cons lcar lcdr)))
((_ _) #f)))
(p-literal v1)))))
(match p
('(_) (if parity (values st p) (values #f #f)))
(`(lookup ,path)
(let-values (((st1 v1) (path-lookup path st vtop)))
(let ((pat (lookup->pat path st1 v1)))
(if pat
(pat-prune pat parity st1 v vtop)
(prune-cx st1 unify disunify v1)))))
(`(literal ,datum) (prune-cx st unify disunify datum))
(`(type ,tag) (prune-cx st typify distypify tag))
(`(car ,p) (prune-pair 'car car p))
(`(cdr ,p) (prune-pair 'cdr cdr p))
(`(and ,p1 ,p2) (if parity (prune-and p1 p2) (prune-or p1 p2)))
(`(or ,p1 ,p2) (if parity (prune-or p1 p2) (prune-and p1 p2)))
(`(not ,p)
(let-values (((st1 p) (pat-prune p (not parity) st v vtop)))
(if st1
(values st1 (if (never? p) always `(not ,p)))
(values #f #f))))
(`(? ,_) (values st p))))
(define (simplify-clauses c*)
(let loop ((c* c*) (p-context p-any))
(match c*
(`((,pat . ,rhs) . ,c*1)
(let-values (((st pat1)
(pat-prune
(p-and pat p-context) #t state-empty var-0 var-0)))
(if st
(cons (cons pat1 rhs) (loop c*1 (p-and (p-not pat) p-context)))
(loop c*1 p-context))))
(_ '()))))
(define (clauses&domains c*)
(let-values
(((result _ __)
(let loop ((c* c*))
(match c*
(`((,pat . ,rhs) . ,c*1)
(let-values (((c*1 dmn pd1) (loop c*1)))
(let ((pd0 (p->domain #t pat)))
(let* ((pd1 (pdomain-join pd0 pd1))
(dmn-new (pdomain->domain* pd1))
(dmn-new (if (equal? dmn-new dmn) dmn dmn-new)))
(let ((clause `(,pat . ,rhs)))
(values `((,dmn-new ,clause) . ,c*1) dmn-new pd1))))))
(_ (values '() '() pdomain-empty))))))
result))
(define (clauses->index cs)
(define c* (simplify-clauses cs))
(define (ps->index cs st vs vtop)
(define (extract-pair cs st path v vs)
(let ((pr (walk1 st v)))
(ps->index cs st (list* (cons (cons 'car path) (car pr))
(cons (cons 'cdr path) (cdr pr)) vs) vtop)))
(define (extract-literals cs st path v vs)
;; TODO: profile to determine if partitioning on literals makes sense
(finish cs st path v vs))
(define (finish cs st path v vs)
(and (pair? vs) (ps->index cs st vs vtop)))
(let ((path (caar vs)) (v (cdar vs)) (v* (cdr vs)))
(let part ((cs cs)
(st st)
(parts '())
(tag*cont
`((pair ,extract-pair)
(symbol ,extract-literals)
(number ,extract-literals)
(() ,finish)
(#f ,finish)
(#t ,finish))))
(match (and (< 1 (length cs)) tag*cont)
(`((,tag ,cont) . ,t*c)
(let ((st0 (typify st tag v)) (nst0 (distypify st tag v)))
(if (and st0 nst0)
(let loop ((c* cs) (sc* '()) (nc* '()))
(match c*
(`((,p . ,rhs) . ,c*1)
(loop
c*1
(let-values (((st1 p1)
(pat-prune p #t st0 vtop vtop)))
(if st1 (cons (cons p1 rhs) sc*) sc*))
(let-values (((nst1 p1)
(pat-prune p #t nst0 vtop vtop)))
(if nst1 (cons (cons p1 rhs) nc*) nc*))))
(_ (if (or (null? sc*) (and (not (eq? 'pair tag))
(null? nc*))
(and (= (length cs) (length sc*))
(= (length cs) (length nc*))))
(part cs st parts '())
(let* ((sc* (reverse sc*))
(nc* (reverse nc*))
(scd* (clauses&domains sc*))
(more (and (< 1 (length sc*))
(cont sc* st0 path v v*))))
(part nc* nst0 (cons (list tag scd* more) parts)
t*c))))))
(part cs st v vtop parts t*c))))
(_ (and (pair? parts) (list (reverse path) (reverse parts) cs)))))))
(list (clauses&domains c*)
(ps->index c* state-empty (list (cons '() var-0)) var-0)))
;; TODO: update match-chain definition
(define (mc-try mc) (error "TODO: mc-try"))
(define (mc-guess mc) (error "TODO: mc-guess"))
(define (mc-try-run mc st rhs? rhs) ((mc-try mc) st rhs? rhs))
(define (run-rhs svs env st vtop drhs rhs? rhs)
(let-values (((st result) (drhs vtop env st)))
(if (match-chain? result)
(mc-try-run result st rhs? rhs)
(values (if rhs? (and st (unify st result rhs)) st) svs result))))
(define (mc-suspend st goal-ref mc svs rhs)
(let* ((rhs (walk1 st rhs))
(goal-ref (or goal-ref (goal-ref-new)))
(retry (lambda (st)
(let ((rhs (walk1 st rhs)))
(let-values (((st svs result) (mc-try-run mc st #t rhs)))
(if (match-chain? result)
(mc-suspend st goal-ref result svs rhs)
(and st (state-remove-goal st goal-ref)))))))
(guess (lambda (st) ((mc-guess mc) (goal-ref st (walk1 st rhs)))))
(goal (goal-suspended #f rhs svs retry guess (mc-active? mc))))
(state-suspend* st svs (value->vars st rhs) goal-ref goal)))
(define (false? x) (eq? #f x))
(define (true? x) (eq? #t x))
(define (index->dmc index active?)
(define (scan cs&ds)
(let loop ((cs&ds cs&ds))
(match cs&ds
(`((,dmn (,pat . (,prhs . ,drhs))) . ,cs&ds)
(cons (list dmn (p->assert pat #t) prhs drhs) (loop cs&ds)))
('() '()))))
(define (dispatch path parts cs)
(let ((find-part
(let loop ((parts parts))
(match parts
(`((,tag . (,cs&ds ,table)) . ,parts)
(let ((found? (match tag
('pair pair?)
('symbol symbol?)
('number number?)
('() null?)
(#f false?)
(#t true?)))
(yes (part cs&ds table))
(no (loop parts)))
(lambda (v) (if (found? v) yes (no v)))))
('()
(let ((yes (part (map (lambda (c) (list domain*-full c)) cs)
#f)))
(lambda (v) yes))))))
(path (map (lambda (tag)
(match tag
('car lookup/car)
('cdr lookup/cdr))) path)))
(lambda (env st v vtop rhs? rhs)
(let-values (((st1 v) (path-lookup path st vtop)))
(and st1 (part-continue (find-part v) env st1 v vtop rhs? rhs))))))
(define (part-continue part env st v vtop rhs? rhs)
(define a* (car part))
(define try (cadr part))
((try env v vtop a*) st rhs? rhs))
(define (mc-build env v vtop a* try guess)
(define retry
(lambda (st rhs? rhs)
(let* ((vtop (walk1 st vtop))
(v (walk1 st v))
(rhs (if rhs? (walk1 st rhs) rhs)))
((try env v vtop a*) st rhs? rhs))))
(mc-new retry
(guess env v vtop a*)
active?))
(define (part cs table)
(define all (scan cs))
(define dt (and table (dispatch (car table) (cadr table) (caddr table))))
(define try
(if dt
(lambda (env v vtop a*)
(lambda (st rhs? rhs)
(if (var? v)
(try-unknown a* env st v vtop rhs? rhs)
(dt env st v vtop rhs? rhs))))
(lambda (env v vtop a*)
(lambda (st rhs? rhs)
(try-unknown a* env st v vtop rhs? rhs)))))
(define (guess env v vtop a*)
(lambda (goal-ref st rhs)
(define vtop (walk1 st vtop))
(define v (walk1 st v))
(define rhs (walk1 st rhs))
(define (commit-without next-a* assert)
(let-values (((st svs result)
((try env v vtop next-a*) st #t rhs)))
(if (match-chain? result)
(mc-suspend st goal-ref result svs rhs)
(and st (state-remove-goal st goal-ref)))))
(define (commit-with assert drhs)
(let-values
(((st svs) (assert env (state-remove-goal st goal-ref) v vtop)))
(and st (let-values (((st svs result)
(run-rhs svs env st vtop drhs #t rhs)))
(if (match-chain? result)
(mc-suspend st #f result svs rhs)
st)))))
(and (pair? a*)
(zzz (let* ((next-a* (cdr a*))
(assert ((cadar a*) env))
(drhs (cadddr (car a*)))
(ss (reset-cost (commit-with assert drhs))))
(if (pair? next-a*)
(mplus ss (zzz (reset-cost
(commit-without next-a* assert))))
ss))))))
(define (try-unknown a* env st v vtop rhs? rhs)
(let loop ((a* a*))
(if (null? a*) (values #f #f #f)
(let ((dmn (caar a*))
(assert (cadar a*))
(prhs (caddar a*))
(drhs (cadddr (car a*))))
(let-values (((st1 svs1) (assert env st v vtop)))
(let ((commit (lambda ()
(run-rhs svs1 env st1 vtop drhs rhs? rhs))))
;; Is the first pattern satisfiable?
(if st1
;; If we only have a single option, commit to it.
(if (null? (cdr a*)) (commit)
(begin (det-pay 1)
;; If no vars were scrutinized (svs1) while checking
;; satisfiability, then we have an irrefutable match, so
;; commit to it.
(if (null? svs1) (commit)
(begin (det-pay 5)
;; Check whether we can rule out this clause by
;; matching its right-hand-side with the expected
;; result of the entire match expression.
(if (and rhs? (not (prhs env st1 rhs vtop)))
(loop (cdr a*))
;; Otherwise, we're not sure whether to commit to
;; this clause yet. If there are no other
;; satisfiable patterns, we can. If there is at
;; least one other satisfiable pattern, we should
;; wait until later, when we either have more
;; information, or we're forced to guess.
(let ambiguous ((a*2 (cdr a*)))
(let ((assert2 (cadar a*))
(prhs2 (caddar a*)))
;; Is the next pattern satisfiable?
(let-values (((st2 svs2)
(assert2 env st v vtop)))
(if st2
;; If it is, try ruling it out by matching
;; its right-hand-side with the expected
;; result.
(if (and rhs?
(not (prhs2 env st2 rhs vtop)))
;; If we rule it out and there are no
;; patterns left to try, the first clause
;; is the only option. Commit to it.
(if (null? (cdr a*2)) (commit)
(ambiguous (cdr a*2)))
;; If we can't rule it out, then we've
;; established ambiguity. Retry later.
(values
;; TODO: domainify* with dmn
st
(list-append-unique svs1 svs2)
(mc-build env v vtop (cons (car a*) a*2)
try guess)))
;; Otherwise, if we have no other clauses
;; available, then the first clause happens
;; to be the only option. Commit to it.
(if (null? (cdr a*2)) (commit)
;; If the there still are other clauses,
;; keep checking.
(ambiguous (cdr a*2))))))))))))
(loop (cdr a*)))))))))
(list all try guess))
(let* ((start (part (car index) (cadr index)))
(start-a* (car start))
(start-try (cadr start))
(start-guess (caddr start)))
(lambda (env st v vtop)
(values st (mc-build env v vtop start-a* start-try start-guess)))))
(define (pstx->p-var path b* vname penv)
(let loop ((b* b*))
(match b*
('() (values `((,vname ,(reverse path)) . ,penv) p-any))
(`((,name ,path) . ,b*)
(if (eq? name vname) (values penv (p-lookup path)) (loop b*))))))
(define (pstx->p-qq qqpat path penv senv)
(match qqpat
(`(,'unquote ,pat) (pstx->p pat path penv senv))
(`(,a . ,d)
(let*-values
(((penv pa) (pstx->p-qq a (cons lookup/car path) penv senv))
((penv pd) (pstx->p-qq d (cons lookup/cdr path) penv senv)))
(values penv (p-and (p-car pa) (p-cdr pd)))))
((? quotable? datum) (values penv (p-literal datum)))))
(define (pstx->p-cons apat dpat path penv senv)
(let*-values (((penv pa) (pstx->p apat (cons lookup/car path) penv senv))
((penv pd) (pstx->p dpat (cons lookup/cdr path) penv senv)))
(values penv (p-and (p-car pa) (p-cdr pd)))))
(define (pstx->p-or pat* path penv senv)
(match pat*
('() (values penv p-none))
(`(,pstx) (pstx->p pstx path penv senv))
(`(,pstx . ,pat*)
(let*-values (((_ p) (pstx->p pstx path penv senv))
((_ p*) (pstx->p-or pat* path penv senv)))
(values penv (p-and p p*))))))
(define (pstx->p-and pat* path penv senv)
(match pat*
('() (values penv p-any))
(`(,pstx) (pstx->p pstx path penv senv))
(`(,pstx . ,pat*)
(let*-values (((penv1 p) (pstx->p pstx path penv senv))
((penv2 p*) (pstx->p-and pat* path penv1 senv)))
(values penv2 (p-and p p*))))))
(define (pstx->p-not pat* path penv senv)
(define p* (map (lambda (pstx)
(let-values (((penv p) (pstx->p pstx path penv senv)))
(p-not p))) pat*))
(values penv (p-and* p*)))
(define (pstx->p-type type-tag pat* path penv senv)
(define pty (match type-tag ('symbol p-symbol) ('number p-number)))
(if (null? pat*) (values penv pty)
(let-values (((penv p*) (pstx->p-and pat* path penv senv)))
(values penv (p-and pty p*)))))
(define (pstx->p-? predicate pat* path penv senv)
(let ((dpred (denote-term predicate senv)))
(let-values (((penv1 p*) (pstx->p-and pat* path penv senv)))
(values penv1 (p-and (p-? dpred) p*)))))
(define (pstx->p pstx path penv senv)
(match pstx
(`(quote ,(? quotable? datum)) (values penv (p-literal datum)))
(`(quasiquote ,qqpat) (pstx->p-qq qqpat path penv senv))
(`(cons ,apat ,dpat) (pstx->p-cons apat dpat path penv senv))
(`(not . ,pat*) (pstx->p-not pat* path penv senv))
(`(and . ,pat*) (pstx->p-and pat* path penv senv))
(`(or . ,pat*) (pstx->p-or pat* path penv senv))
(`(symbol . ,pat*) (pstx->p-type 'symbol pat* path penv senv))
(`(number . ,pat*) (pstx->p-type 'number pat* path penv senv))
(`(? ,predicate . ,pat*) (pstx->p-? predicate pat* path penv senv))
('_ (values penv p-any))
((? symbol? vname) (pstx->p-var path penv vname penv))
((? quotable? datum) (values penv (p-literal datum)))))
(define (rhs->drhs rhs penv senv)
(define (drhs-complex)
(let-values (((ps paths) (split-bindings penv)))
(let* ((ps (reverse ps))
(paths (reverse paths))
(senv (extend-env* ps ps senv))
(drhs0 (denote-term rhs senv)))
(lambda (vtop env st)
(let loop ((paths paths) (env env) (st st))
(match paths
(`(,path . ,paths)
(let-values (((st1 v1) (path-lookup path st vtop)))
(loop paths (cons v1 env) st1)))
('() ((drhs0 env) st))))))))
(define (drhs-simple)
(let ((drhs0 (denote-term rhs senv)))
(lambda (vtop env st) ((drhs0 env) st))))
(match rhs
(`(quote ,(? quotable? datum)) (drhs-simple))
((? number? datum) (drhs-simple))
(#t (drhs-simple))
(#f (drhs-simple))
(_ (drhs-complex))))
(define prhs-true (prhs-literal #t))
(define prhs-false (prhs-literal #f))
(define (rhs->p-var vname penv senv)
(let/if (binding (assoc vname penv))
(prhs-lookup (cadr binding))
(prhs-var (denote-term vname senv))))
(define (rhs->p-qq qq penv senv)
(match qq
(`(,'unquote ,pat) (rhs->p pat penv senv))
(`(,a . ,d) (prhs-cons (rhs->p-qq a penv senv) (rhs->p-qq d penv senv)))
((? quotable? datum) (prhs-literal datum))))
(define (rhs->p rhs penv senv)
(match rhs
(`(quote ,(? quotable? datum)) (prhs-literal datum))
(`(quasiquote ,qq) (rhs->p-qq qq penv senv))
((? symbol? vname) (rhs->p-var vname penv senv))
((? number? datum) (prhs-literal datum))
(#t prhs-true)
(#f prhs-false)
(_ prhs-unknown)))
(define (pattern-clauses->dmc pt* senv active?)
(let* ((pc* (let loop ((pt* pt*))
(match pt*
('() '())
(`((,pat ,rhs) . ,clause*)
(let-values (((penv dpat) (pstx->p pat '() '() senv)))
(let* ((drhs (rhs->drhs rhs penv senv))
(drhspat (rhs->p rhs penv senv))
(pc* (loop clause*)))
(cons (cons dpat (cons drhspat drhs)) pc*))))))))
(index->dmc (clauses->index pc*) active?)))
(define (denote-pattern-match pt* vt senv active?)
(let* ((dv (denote-term vt senv))
(dmc (pattern-clauses->dmc pt* senv active?)))
(lambda (env)
(let ((gv (dv env)))
(lambda (st)
(let*/state (((st v) (gv st))
((st v) (actual-value st v #f #f)))
(dmc env st v v)))))))
(define (pattern-assert-any parity st penv v)
(if parity
(values st penv '())
(values #f #f #f)))
(define (pattern-assert-none parity st penv v)
(if parity
(values #f #f #f)
(values st penv '())))
(define (pattern-value-literal literal) (lambda (st penv) literal))
(define (pattern-value-ref index)
(lambda (st penv) (walk1 st (list-ref penv index))))
(define (pattern-var-extend parity st penv v)
(if parity
(values st (cons (walk1 st v) penv) '())
(values #f #f #f)))
(define (pattern-transform f assert)
(lambda (parity st penv v) (assert parity st penv (f v))))
(define (pattern-replace v assert) (pattern-transform (lambda (_) v) assert))
(define (pattern-assert-not assert)
(lambda (parity st penv v)
(let-values (((st _ svs) (assert (not parity) st penv v)))
(values st penv svs))))
(define (pattern-assert-== pvalue)
(lambda (parity st penv v)
(let ((pval (pvalue st penv)))
(let/if (st1 ((if parity unify disunify) st pval v))
(values st1 penv (extract-svs st pval v))
(values #f #f #f)))))
(define (pattern-assert-=/= pvalue)
(pattern-assert-not (pattern-assert-== pvalue)))
(define (pattern-assert-type-== type-tag)
(lambda (parity st penv v)
(let/if (st1 ((if parity typify distypify) st type-tag v))
(let ((v1 (walk1 st v)))
(values st1 penv (if (var? v1) (list v1) '())))
(values #f #f #f))))
(define pattern-assert-pair-== (pattern-assert-type-== 'pair))
(define pattern-assert-symbol-== (pattern-assert-type-== 'symbol))
(define pattern-assert-number-== (pattern-assert-type-== 'number))
(define (pattern-assert-pair assert-car assert-cdr)
(define assert (pattern-assert-and (pattern-transform car assert-car)
(pattern-transform cdr assert-cdr)))
(lambda (parity st penv v)
(let ((v (walk1 st v)))
((cond
((pair? v) assert)
((var? v)
(let/vars (va vd)
(let ((v1 `(,va . ,vd)))
(lambda (parity st penv v)
(let-values
(((st penv svs)
((pattern-assert-and
(lambda (parity st penv v)
((if parity
(pattern-assert-== (pattern-value-literal v1))
pattern-assert-pair-==)
parity st penv v))
(pattern-replace v1 assert))
parity st penv v)))
(values st penv (and svs (list-subtract
svs (list va vd)))))))))
(else pattern-assert-none))
parity st penv v))))
(define pattern-assert-false
(pattern-assert-== (pattern-value-literal #f)))
(define pattern-assert-not-false
(pattern-assert-=/= (pattern-value-literal #f)))
(define (pattern-assert-predicate pred)
(lambda (parity st penv v)
(let-values (((st result) (pred st v)))
; TODO: if (not st), the entire computation needs to fail, not just this
; particular pattern assertion. This failure needs to cooperate with
; nondeterministic search, which makes things more complex and likely
; less efficient (negations of conjunctions containing predicates become
; mandatory, to verify that the predicate invocation, if reached, returns
; a value). For now, we'll assume a predicate can never fail in this
; manner. In this implementation, such a failure leads to unsound
; behavior by being unpredictable in the granularity of failure.
(if (match-chain? result)
(let-values (((st svs result) (match-chain-try st result #f #f)))
(if (match-chain? result)
(let-values (((st rhs) (if parity
(let/vars (notf)
(values (disunify st notf #f) notf))
(values st #f))))
(let-values (((st result) (actual-value st result #t rhs)))
(if st
(values st penv svs)
(values #f #f #f))))
(pattern-assert-not-false parity st penv result)))
(pattern-assert-not-false parity st penv result)))))
(define (pattern-exec-and a1 a2 st penv v)
(let-values (((st penv svs1) (a1 #t st penv v)))
(if st
(let-values (((st penv svs2) (a2 #t st penv v)))
(if st
(values st penv (list-append-unique svs1 svs2))
(values #f #f #f)))
(values #f #f #f))))
(define (pattern-assert-and a1 a2)
(define (nassert)
(pattern-assert-or (pattern-assert-not a1)
(pattern-assert-and a1 (pattern-assert-not a2))))
(lambda (parity st penv v)
(if parity
(pattern-exec-and a1 a2 st penv v)
((nassert) #t st penv v))))
(define or-rhs (cons denote-true denote-rhs-pattern-unknown))
(define (pattern-assert-or a1 a2)
(define na1 (pattern-assert-not a1))
(define na2 (pattern-assert-not a2))
(define clause* (list (cons (lambda (env) a1) or-rhs)
(cons (lambda (env) a2) or-rhs)))
(lambda (parity st penv v)
(if parity
(let-values (((st svs result)
(match-chain-try st (mc-new penv '() v clause* #f) #f #t)))
(if (match-chain? result)
(values (match-chain-suspend st #f result svs #t) penv svs)
(values st penv svs)))
(pattern-exec-and na1 na2 st penv v))))
(define (denote-pattern-succeed env) pattern-assert-any)
(define (denote-pattern-fail env) pattern-assert-none)
(define (denote-pattern-literal literal penv)
(values penv (let ((assert (pattern-assert-==
(pattern-value-literal literal))))
(lambda (env) assert))))
(define (denote-pattern-var-extend env) pattern-var-extend)
(define (denote-pattern-var b* vname penv)
(let loop ((idx 0) (b* b*))
(match b*
('() (values `((,vname ,vname) . ,penv) denote-pattern-var-extend))
(`((,name ,x) . ,b*)
(if (eq? name vname)
(values penv (let ((assert (pattern-assert-==
(pattern-value-ref idx))))
(lambda (env) assert)))
(loop (+ idx 1) b*))))))
(define (denote-pattern-qq qqpattern penv senv)
(match qqpattern
(`(,'unquote ,pat) (denote-pattern pat penv senv))
(`(,a . ,d)
(let*-values (((penv da) (denote-pattern-qq a penv senv))
((penv dd) (denote-pattern-qq d penv senv)))
(values penv (lambda (env) (pattern-assert-pair (da env) (dd env))))))
((? quotable? datum) (denote-pattern-literal datum penv))))
(define (denote-pattern-cons apat dpat penv senv)
(let*-values (((penv da) (denote-pattern apat penv senv))
((penv dd) (denote-pattern dpat penv senv)))
(values penv (lambda (env) (pattern-assert-pair (da env) (dd env))))))
(define (denote-pattern-or pattern* penv senv)
(match pattern*
('() (values penv denote-pattern-fail))
(`(,pat) (denote-pattern pat penv senv))
(`(,pat . ,pat*)
(let*-values (((_ d0) (denote-pattern pat penv senv))
((_ d*) (denote-pattern-or pat* penv senv)))
(values penv (lambda (env) (pattern-assert-or (d0 env) (d* env))))))))
(define (denote-pattern* pattern* penv senv)
(match pattern*
('() (values penv denote-pattern-succeed))
(`(,pat) (denote-pattern pat penv senv))
(`(,pat . ,pat*)
(let*-values (((penv d0) (denote-pattern pat penv senv))
((penv d*) (denote-pattern* pat* penv senv)))
(values penv (lambda (env) (pattern-assert-and (d0 env) (d* env))))))))
;; TODO: This is wrong, (not a b ...) ==> (and (not a) (not b) ...)
(define (denote-pattern-not pat* penv senv)
(let-values (((_ dp) (denote-pattern* pat* penv senv)))
(values penv (lambda (env) (pattern-assert-not (dp env))))))
(define (denote-pattern-symbol env) pattern-assert-symbol-==)
(define (denote-pattern-number env) pattern-assert-number-==)
(define (denote-pattern-type type-tag pat* penv senv)
(define dty (match type-tag
('symbol denote-pattern-symbol)
('number denote-pattern-number)))
(if (null? pat*) (values penv dty)
(let-values (((penv d*) (denote-pattern* pat* penv senv)))
(values penv (lambda (env) (pattern-assert-and (dty env) (d* env)))))))
(define (denote-pattern-? predicate pat* penv senv)
(let ((dpred (denote-term predicate senv)))
(let-values (((penv d*) (denote-pattern* pat* penv senv)))
(values penv
(lambda (env)
(let-values (((st0 vpred) ((dpred env) #t)))
(if (not st0)
(error (format "invalid predicate: ~a" predicate))
(let* ((pred (lambda (st v)
(let-values (((st result) ((vpred v) st)))
(if (not st)
(error (format "predicate failed: ~a"
predicate))
(values st result)))))
(assert (pattern-assert-predicate pred)))
(if (null? pat*) assert
(pattern-assert-and assert (d* env)))))))))))
(define (denote-pattern pat penv senv)
(match pat
(`(quote ,(? quotable? datum)) (denote-pattern-literal datum penv))
(`(quasiquote ,qqpat) (denote-pattern-qq qqpat penv senv))
(`(cons ,apat ,dpat) (denote-pattern-cons apat dpat penv senv))
(`(not . ,pat*) (denote-pattern-not pat* penv senv))
(`(and . ,pat*) (denote-pattern* pat* penv senv))
(`(or . ,pat*) (denote-pattern-or pat* penv senv))
(`(symbol . ,pat*) (denote-pattern-type 'symbol pat* penv senv))
(`(number . ,pat*) (denote-pattern-type 'number pat* penv senv))
(`(? ,predicate . ,pat*) (denote-pattern-? predicate pat* penv senv))
('_ (values penv denote-pattern-succeed))
((? symbol? vname) (denote-pattern-var penv vname penv))
((? quotable? datum) (denote-pattern-literal datum penv))))
(defrec match-chain scrutinee penv env clauses active?)
(define (mc-new penv0 env scrutinee clauses active?)
(match-chain scrutinee penv0 env clauses active?))
(define mc-scrutinee match-chain-scrutinee)
(define mc-penv match-chain-penv)
(define mc-env match-chain-env)
(define mc-clauses match-chain-clauses)
(define mc-active? match-chain-active?)
(define (actual-value st result rhs? rhs)
(if (match-chain? result)
(let-values (((st svs result) (match-chain-try st result rhs? rhs)))
(if (match-chain? result)
(let ((rhs (if rhs? rhs (let/vars (rhs) rhs))))
(values (match-chain-suspend st #f result svs rhs) rhs))
(values st result)))
(values (if rhs? (and st (unify st result rhs)) st) result)))
(define (match-chain-suspend st goal-ref mc svs rhs)
(let* ((rhs (walk1 st rhs))
(goal-ref (or goal-ref (goal-ref-new)))
(retry (lambda (st)
(let ((rhs (walk1 st rhs)))
(let-values (((st svs result)
(match-chain-try st mc #t rhs)))
(if (match-chain? result)
(match-chain-suspend st goal-ref result svs rhs)
(and st (state-remove-goal st goal-ref)))))))
(guess (lambda (st)
(match-chain-guess goal-ref st mc (walk1 st rhs))))
(goal (goal-suspended
#f rhs svs retry guess (mc-active? mc))))
(state-suspend* st svs (value->vars st rhs) goal-ref goal)))
(define (rhs->goal rhs? rhs)
(lambda (svs penv env st drhs)
(let-values (((st result) ((drhs (append penv env)) st)))
(if (match-chain? result)
(match-chain-try st result rhs? rhs)
(values (if rhs? (and st (unify st result rhs)) st) svs result)))))
(define (match-chain-guess goal-ref st mc rhs)
(define v (walk1 st (mc-scrutinee mc)))
(define penv0 (mc-penv mc))
(define env (mc-env mc))
(define pc* (mc-clauses mc))
(define active? (mc-active? mc))
(define run-rhs (rhs->goal #t rhs))
(define (commit-without next-pc* assert)
(let-values (((st penv _) (assert #f st penv0 v)))
(and st
(let-values (((st svs result)
(match-chain-try
st (mc-new penv0 env v next-pc* active?) #t rhs)))
(if (match-chain? result)
(match-chain-suspend st goal-ref result svs rhs)
(and st (state-remove-goal st goal-ref)))))))
(define (commit-with assert drhs)
(let-values (((st penv svs)
(assert #t (state-remove-goal st goal-ref) penv0 v)))
(and st (let-values (((st svs result) (run-rhs svs penv env st drhs)))
(if (match-chain? result)
(match-chain-suspend st #f result svs rhs)
st)))))
(and (pair? pc*)
(zzz (let* ((next-pc* (cdr pc*))
(assert ((caar pc*) env))
(drhs (cadar pc*))
(ss (reset-cost (commit-with assert drhs))))
(if (pair? next-pc*)
(mplus ss (zzz (reset-cost (commit-without next-pc* assert))))
ss)))))
(define (match-chain-try st mc rhs? rhs)
(let* ((rhs (if rhs? (walk1 st rhs) rhs))
(run-rhs (rhs->goal rhs? rhs))
(v (mc-scrutinee mc))
(penv0 (mc-penv mc))
(env (mc-env mc))
(pc* (mc-clauses mc))
(active? (mc-active? mc)))
(let ((v (walk1 st v)))
(let loop ((st st) (pc* pc*))
(if (null? pc*) (values #f #f #f)
(let* ((assert ((caar pc*) env))
(drhs (cadar pc*))
(drhspat (cddar pc*)))
(let-values (((st1 penv1 svs) (assert #t st penv0 v)))
(let ((commit (lambda () (run-rhs svs penv1 env st1 drhs))))
;; Is the first pattern satisfiable?
(if st1
;; If we only have a single option, commit to it.
(if (null? (cdr pc*)) (commit)
(begin (det-pay 1)
;; If no vars were scrutinized (svs) while checking
;; satisfiability, then we have an irrefutable match, so
;; commit to it.
(if (null? svs) (commit)
;; If vars were scrutinized, there is room for doubt.
;; Check whether the negated pattern is satisfiable.
(begin (det-pay 5)
(let-values (((nst _ nsvs) (assert #f st penv0 v)))
(if nst
;; If the negation is also satisfiable, check whether
;; we can still rule out this clause by matching its
;; right-hand-side with the expected result of the
;; entire match expression.
(if (and rhs? (not (drhspat
(append penv1 env) st1 rhs)))
;; If we can rule it out, permanently learn the
;; negated state.
(loop nst (cdr pc*))
;; Otherwise, we're not sure whether to commit to
;; this clause yet. If there are no other
;; satisfiable patterns, we can. If there is at
;; least one other satisfiable pattern, we should
;; wait until later, when we either have more
;; information, or we're forced to guess.
(let ambiguous ((nst nst) (pc*1 (cdr pc*)) (nc* '()))
(let ((assert1 ((caar pc*1) env))
(drhspat1 (cddar pc*1)))
;; Is the next pattern satisfiable?
(let-values (((st1 penv1 svs1)
(assert1 #t nst penv0 v)))
(if st1
;; If it is, check whether we can rule it out
;; by matching its right-hand-side with the
;; expected result.
(if (and rhs?
(not (drhspat1
(append penv1 env) st1 rhs)))
;; If we rule it out and there are no
;; patterns left to try, the first clause
;; is the only option. Commit to it.
(if (null? (cdr pc*1)) (commit)
;; If we rule it out and there are other
;; patterns to try, learn the negation
;; and continue the search.
(let-values (((nst1 _ __)
(assert1 #f nst penv0 v)))
(if nst1
;; Clauses that were ruled out (nc*)
;; need to be tracked so that retries
;; can relearn their negated
;; patterns.
(ambiguous
nst1 (cdr pc*1) (cons (car pc*1)
nc*))
;; Unless the negation is impossible,
;; in which case nothing else could
;; succeed, meaning the first clause
;; is the only option after all!
;; Commit to it.
(commit))))
;; If we can't rule it out, then we've
;; established ambiguity. Try again later.
(values st
(list-append-unique
svs1 (list-append-unique
nsvs svs))
(mc-new
penv0 env v (cons (car pc*)
(rev-append
nc* pc*1))
active?)))
;; Otherwise, if we have no other clauses
;; available, then the first clause happens
;; to be the only option. Commit to it.
(if (null? (cdr pc*1)) (commit)
;; If the there still are other clauses,
;; keep checking.
(ambiguous nst (cdr pc*1) nc*)))))))
;; If the negated pattern wasn't satisfiable, this
;; pattern was irrefutable after all. Commit.
(commit)))))))
;; If the first pattern wasn't satisfiable, throw that clause
;; away and try the next.
(loop st (cdr pc*)))))))))))
(define (pattern-match penv dv pc* active?)
(lambda (env)
(let ((gv (dv env)))
(lambda (st)
(let*/state (((st v) (gv st))
((st v) (actual-value st v #f #f)))
(values st (mc-new penv env v pc* active?)))))))
;; TODO: compatible use of new patterns
(define (denote-match pt*-all vt senv active?)
(let ((dv (denote-term vt senv))
(pc* (let loop ((pt* pt*-all))
(match pt*
('() '())
(`((,pat ,rhs) . ,clause*)
(let*-values
(((penv dpat) (denote-pattern pat '() senv))
((ps vs) (split-bindings penv)))
(let* ((senv (extend-env* (reverse ps) (reverse vs) senv))
(drhs (denote-term rhs senv))
(drhspat (denote-rhs-pattern rhs senv))
(pc* (loop clause*)))
(cons (cons dpat (cons drhs drhspat)) pc*))))))))
(pattern-match '() dv pc* active?)))
;; TODO: fix mc construction
(define and-rhs (cons denote-false denote-rhs-pattern-false))
(define (denote-and t* senv)
(match t*
('() (denote-value #t))
(`(,t) (denote-term t senv))
(`(,t . ,t*)
(let* ((d0 (denote-term t senv))
(d* (denote-and t* senv))
(clause* (list (cons (lambda (env) pattern-assert-false) and-rhs)
(cons (lambda (env) pattern-assert-any)
(cons d* denote-rhs-pattern-unknown)))))
(lambda (env)
(let ((g0 (d0 env)))
(lambda (st)
(let*/state (((st v0) (g0 st))
((st v0) (actual-value st v0 #f #f)))
(values st (mc-new '() env v0 clause* #t))))))))))
(define or-rhs-var (gensym 'or-rhs-var))
(define or-rhs-params (list or-rhs-var))
(define (denote-or t* senv)
(match t*
('() (denote-value #f))
(`(,t) (denote-term t senv))
(`(,t . ,t*)
(let* ((d0 (denote-term t senv))
(d* (denote-or t* senv))
(senv1 (extend-env* or-rhs-params or-rhs-params senv))
(or-2 (denote-term or-rhs-var senv1))
(or-2-pat (denote-rhs-pattern or-rhs-var senv1))
(clause* (list (cons (lambda (env) pattern-assert-false)
(cons d* denote-rhs-pattern-unknown))
(cons (lambda (env) pattern-var-extend)
(cons or-2 or-2-pat)))))
(lambda (env)
(let ((g0 (d0 env)))
(lambda (st)
(let*/state (((st v0) (g0 st))
((st v0) (actual-value st v0 #f #f)))
(values st (mc-new '() env v0 clause* #t))))))))))
(define (denote-fresh vsyms body senv)
(let ((db (denote-term body (extend-env* vsyms vsyms senv))))
(lambda (env)
(let ((vs (map (lambda (vsym) (var (gensym (symbol->string vsym))))
vsyms)))
(db (rev-append vs env))))))
(define (denote-term term senv)
(let ((bound? (lambda (sym) (in-env? senv sym))))
(match term
(#t (denote-value #t))
(#f (denote-value #f))
((? number? num) (denote-value num))
((? symbol? sym) (denote-variable sym senv))
((and `(,op . ,_) operation)
(match operation
(`(,(or (? bound?) (not (? symbol?))) . ,rands)
(denote-application op rands senv))
(`(quote ,(? quotable? datum)) (denote-value datum))
(`(quasiquote ,qqterm) (denote-qq qqterm senv))
(`(if ,condition ,alt-true ,alt-false)
(denote-match `((#f ,alt-false) (_ ,alt-true)) condition senv #t))
(`(lambda ,params ,body) (denote-lambda params body senv))
(`(let ,binding* ,let-body)
(let-values (((ps vs) (split-bindings binding*)))
(denote-apply (denote-lambda ps let-body senv)
(denote-term-list vs senv))))
(`(letrec ,binding* ,letrec-body)
(let* ((rsenv `((rec . ,binding*) . ,senv))
(dbody (denote-term letrec-body rsenv))
(db* (let loop ((binding* binding*))
(match binding*
('() '())
(`((,_ (lambda ,params ,body)) . ,b*)
(cons (denote-lambda params body rsenv)
(loop b*)))))))
(lambda (env) (dbody (cons db* env)))))
(`(and . ,t*) (denote-and t* senv))
(`(or . ,t*) (denote-or t* senv))
(`(match ,scrutinee . ,pt*) (denote-match pt* scrutinee senv #t))
(`(match/lazy ,scrutinee . ,pt*) (denote-match pt* scrutinee senv #f))
(`(fresh ,vars ,body) (denote-fresh vars body senv)))))))
(define (in-env? env sym)
(match env
('() #f)
(`((val . (,a . ,_)) . ,d) (or (equal? a sym) (in-env? d sym)))
(`((rec . ,binding*) . ,d) (in-env-rec? binding* d sym))))
(define (in-env-rec? binding* env sym)
(match binding*
('() (in-env? env sym))
(`((,a . ,_) . ,d) (or (equal? a sym) (in-env-rec? d env sym)))))
(define (extend-env* params args env)
(match `(,params . ,args)
(`(() . ()) env)
(`((,x . ,dx*) . (,a . ,da*))
(extend-env* dx* da* `((val . (,x . ,a)) . ,env)))))
(define (not-in-params? ps sym)
(match ps
('() #t)
(`(,a . ,d)
(and (not (equal? a sym)) (not-in-params? d sym)))))
(define (param-list? x)
(match x
('() #t)
(`(,(? symbol? a) . ,d)
(and (param-list? d) (not-in-params? d a)))
(_ #f)))
(define (params? x)
(match x
((? param-list?) #t)
(x (symbol? x))))
(define (bindings? b*)
(match b*
('() #t)
(`((,p ,v) . ,b*) (bindings? b*))
(_ #f)))
(define (split-bindings b*)
(match b*
('() (values '() '()))
(`((,param ,val) . ,b*)
(let-values (((ps vs) (split-bindings b*)))
(values (cons param ps) (cons val vs))))))
(define (match-clauses? pt* env)
(define (pattern-var? b* vname ps)
(match b*
('() `(,vname . ,ps))
(`(,name . ,b*) (if (eq? name vname) ps (pattern-var? b* vname ps)))))
(define (pattern-qq? qqpattern ps env)
(match qqpattern
(`(,'unquote ,pat) (pattern? pat ps env))
(`(,a . ,d) (let*/and ((ps (pattern-qq? a ps env)))
(pattern-qq? d ps env)))
((? quotable?) ps)))
(define (pattern-or? pattern* ps env)
(match pattern*
('() ps)
(`(,pattern . ,pattern*)
(and (pattern? pattern ps env) (pattern-or? pattern* ps env)))))
(define (pattern*? pattern* ps env)
(match pattern*
('() ps)
(`(,pattern . ,pattern*)
(let*/and ((ps (pattern? pattern ps env)))
(pattern*? pattern* ps env)))))
(define (pattern? pattern ps env)
(match pattern
(`(quote ,(? quotable?)) ps)
(`(quasiquote ,qqpat) (pattern-qq? qqpat ps env))
(`(not . ,pat*) (and (pattern*? pat* ps env) ps))
(`(and . ,pat*) (pattern*? pat* ps env))
(`(or . ,pat*) (pattern-or? pat* ps env))
(`(symbol . ,pat*) (pattern*? pat* ps env))
(`(number . ,pat*) (pattern*? pat* ps env))
(`(? ,predicate . ,pat*)
(and (term? predicate env) (pattern*? pat* ps env)))
('_ ps)
((? symbol? vname) (pattern-var? ps vname ps))
((? quotable?) ps)))
(match pt*
('() #t)
(`((,pat ,rhs) . ,pt*)
(let*/and ((ps (pattern? pat '() env)))
(term? rhs (extend-env* ps ps env)) (match-clauses? pt* env)))))
(define (term-qq? qqterm env)
(match qqterm
(`(,'unquote ,term) (term? term env))
(`(,a . ,d) (and (term-qq? a env) (term-qq? d env)))
(datum (quotable? datum))))
(define (term? term env)
(letrec ((term1? (lambda (v) (term? v env)))
(terms? (lambda (ts env)
(match ts
('() #t)
(`(,t . ,ts) (and (term? t env) (terms? ts env))))))
(binding-lambdas?
(lambda (binding* env)
(match binding*
('() #t)
(`((,_ ,(and `(lambda ,_ ,_) t)) . ,b*)
(and (term? t env) (binding-lambdas? b* env)))))))
(match term
(#t #t)
(#f #t)
((? number?) #t)
((and (? symbol? sym)) (in-env? env sym))
(`(,(? term1?) . ,rands) (terms? rands env))
(`(quote ,datum) (quotable? datum))
(`(quasiquote ,qqterm) (term-qq? qqterm env))
(`(if ,c ,t ,f) (and (term1? c) (term1? t) (term1? f)))
(`(lambda ,params ,body)
(and (params? params)
(let ((res (match params
((not (? symbol? params))
(extend-env* params params env))
(sym `((val . (,sym . ,sym)) . ,env)))))
(term? body res))))
(`(let ,binding* ,let-body)
(and (bindings? binding*)
(let-values (((ps vs) (split-bindings binding*)))
(and (terms? vs env)
(term? let-body (extend-env* ps ps env))))))
(`(letrec ,binding* ,letrec-body)
(let ((res `((rec . ,binding*) . ,env)))
(and (binding-lambdas? binding* res) (term? letrec-body res))))
(`(and . ,t*) (terms? t* env))
(`(or . ,t*) (terms? t* env))
(`(match ,s . ,pt*) (and (term1? s) (match-clauses? pt* env)))
(`(fresh ,vars ,body) (term? body (extend-env* vars vars env)))
(_ #f))))
(define (eval-denoted-term dterm env) (dterm (map cddr env)))
(define (eval-term term env) (eval-denoted-term (denote-term term env) env))
;; 'dk-term' must be a valid dKanren program, *not* just any miniKanren term.
;; 'result' is a miniKanren term.
(define (dk-evalo dk-term expected)
(let ((dk-goal (eval-term dk-term initial-env)))
(lambda (st)
(reset-cost
(let-values (((st result) (dk-goal st)))
(and st (let-values (((st _) (actual-value st result #t expected)))
st)))))))
(define (primitive params body)
(let-values (((st v) (((denote-lambda params body '()) '()) #t)))
(if (not st)
(error (format "invalid primitive: ~a" `(lambda ,params ,body)))
v)))
(define empty-env '())
(define initial-env `((val . (cons . ,(primitive '(a d) '`(,a . ,d))))
(val . (car . ,(primitive '(x) '(match x
(`(,a . ,d) a)))))
(val . (cdr . ,(primitive '(x) '(match x
(`(,a . ,d) d)))))
(val . (null? . ,(primitive '(x) '(match x
('() #t)
(_ #f)))))
(val . (pair? . ,(primitive '(x) '(match x
(`(,a . ,d) #t)
(_ #f)))))
(val . (symbol? . ,(primitive '(x) '(match x
((symbol) #t)
(_ #f)))))
(val . (number? . ,(primitive '(x) '(match x
((number) #t)
(_ #f)))))
(val . (not . ,(primitive '(x) '(match x
(#f #t)
(_ #f)))))
(val . (equal? . ,(primitive '(x y) '(match `(,x . ,y)
(`(,a . ,a) #t)
(_ #f)))))
(val . (list . ,(primitive 'x 'x)))
. ,empty-env))
(module+ test
(require racket/pretty)
(define-syntax test
(syntax-rules ()
((_ name expr expected)
(let ((actual expr))
(when (not (equal? actual expected))
(display name)
(newline)
(pretty-print actual)
(newline))
(check-equal? actual expected)))))
(test "basic-0"
(run* (x y))
'((_.0 _.1)))
(test "basic-1"
(run* (q) (== q 3))
'((3)))
(test "basic-2"
(run* (q) (== q 4) (== q 4))
'((4)))
(test "basic-3"
(run* (q) (== q 4) (== q 5))
'())
(test "basic-4"
(run* (q) (== '(1 2) q))
'(((1 2))))
(test "basic-5"
(run* (q) (not-numbero q) (== q 3))
'())
(test "basic-6"
(run* (q) (== q 3) (not-numbero q))
'())
(test "basic-7"
(run* (q) (not-numbero q) (== q 'ok))
'((ok)))
(test "basic-8"
(run* (q) (== q 'ok) (not-numbero q))
'((ok)))
(test "basic-9"
(run* (q) (not-symbolo q) (== q 'ok))
'())
(test "basic-10"
(run* (q) (== q 'ok) (not-symbolo q))
'())
(test "basic-11"
(run* (q) (not-symbolo q) (== q 3))
'((3)))
(test "basic-12"
(run* (q) (== q 3) (not-symbolo q))
'((3)))
(test "basic-13"
(run* (q) (not-pairo q) (== '(1 2) q))
'())
(test "basic-14"
(run* (q) (== '(1 2) q) (not-pairo q))
'())
(test "basic-15"
(run* (q) (not-numbero q) (== '(1 2) q))
'(((1 2))))
(test "basic-16"
(run* (q) (== '(1 2) q) (not-numbero q))
'(((1 2))))
(test "basic-17"
(run* (q) (=/= #f q) (== #f q))
'())
(test "basic-18"
(run* (q) (== #f q) (=/= #f q))
'())
(test "basic-19"
(run* (q) (=/= #t q) (== #f q))
'((#f)))
(test "basic-20"
(run* (q) (== #f q) (=/= #t q))
'((#f)))
(test "closed-world-1"
(run* (q) (=/= '() q) (=/= #f q) (not-pairo q) (not-numbero q) (not-symbolo q))
'((#t)))
(test "closed-world-2"
(run* (q) (=/= '() q) (=/= #t q) (=/= #f q) (not-numbero q) (not-symbolo q))
'(((_.0 . _.1))))
(test "absento-ground-1"
(run* (q) (== q 'ok) (absento 5 '(4 ((3 2) 4))))
'((ok)))
(test "absento-ground-2"
(run* (q) (== q 'ok) (absento 5 '(4 ((3 5) 4))))
'())
(test "absento-var-1"
(run* (q) (== q 'ok) (fresh (r) (== r '(4 ((3 2) 4))) (absento 5 r)))
'((ok)))
(test "absento-var-2"
(run* (q) (== q 'ok) (fresh (r) (== r '(4 ((3 5) 4))) (absento 5 r)))
'())
(test "absento-partial-1"
(run* (q) (== q 2) (absento 5 `(4 ((3 ,q) 4))))
'((2)))
(test "absento-partial-2"
(run* (q) (== q 5) (absento 5 `(4 ((3 ,q) 4))))
'())
(test "absento-partial-nested-1"
(run* (q r) (== q `(1 ,r)) (== r 2) (absento 5 `(4 ((3 ,q) 4))))
'(((1 2) 2)))
(test "absento-partial-nested-2"
(run* (q r) (== q `(1 ,r)) (== r 5) (absento 5 `(4 ((3 ,q) 4))))
'())
(test "absento-delayed-var-1"
(run* (q) (== q 'ok) (fresh (r) (absento 5 r) (== r '(4 ((3 2) 4)))))
'((ok)))
(test "absento-delayed-var-2"
(run* (q) (== q 'ok) (fresh (r) (absento 5 r) (== r '(4 ((3 5) 4)))))
'())
(test "absento-delayed-partial-1"
(run* (q) (absento 5 `(4 ((3 ,q) 4))) (== q 2))
'((2)))
(test "absento-delayed-partial-2"
(run* (q) (absento 5 `(4 ((3 ,q) 4))) (== q 5))
'())
;(test "absento-unknown-1"
;(run* (q) (absento 5 q))
;'((ok)))
;(test "absento-unknown-2"
;(run* (q) (absento 5 `(4 ((3 ,q) 4))))
;'((ok)))
;(test "absento-=/=-1"
;(run* (q) (=/= q 5) (absento 5 q))
;'((ok)))
;(test "absento-=/=-2"
;(run* (q) (=/= q 5) (absento 5 `(4 ((3 ,q) 4))))
;'((ok)))
(test "=/=-1"
(run* (q)
(=/= 3 q)
(== q 3))
'())
(test "=/=-2"
(run* (q)
(== q 3)
(=/= 3 q))
'())
(test "=/=-3"
(run* (q)
(fresh (x y)
(=/= x y)
(== x y)))
'())
(test "=/=-4"
(run* (q)
(fresh (x y)
(== x y)
(=/= x y)))
'())
(test "=/=-5"
(run* (q)
(fresh (x y)
(=/= x y)
(== 3 x)
(== 3 y)))
'())
(test "=/=-6"
(run* (q)
(fresh (x y)
(== 3 x)
(=/= x y)
(== 3 y)))
'())
(test "=/=-7"
(run* (q)
(fresh (x y)
(== 3 x)
(== 3 y)
(=/= x y)))
'())
(test "=/=-8"
(run* (q)
(fresh (x y)
(== 3 x)
(== 3 y)
(=/= y x)))
'())
(test "=/=-9"
(run* (q)
(fresh (x y z)
(== x y)
(== y z)
(=/= x 4)
(== z (+ 2 2))))
'())
(test "=/=-10"
(run* (q)
(fresh (x y z)
(== x y)
(== y z)
(== z (+ 2 2))
(=/= x 4)))
'())
(test "=/=-11"
(run* (q)
(fresh (x y z)
(=/= x 4)
(== y z)
(== x y)
(== z (+ 2 2))))
'())
(test "=/=-12"
(run* (q)
(fresh (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))))
'((_.0)))
(test "=/=-13"
(run* (q)
(fresh (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))
(== z 1)
(== `(,x ,y) q)))
'())
(test "=/=-14"
(run* (q)
(fresh (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))
(== z 0)))
'((_.0)))
(test "=/=-15"
(run* (q)
(fresh (x y z)
(== z 0)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))))
'((_.0)))
(test "=/=-16"
(run* (q)
(fresh (x y z)
(== x `(0 ,z 1))
(== y `(0 1 1))
(=/= x y)))
'((_.0)))
(test "=/=-17"
(run* (q)
(fresh (x y z)
(== z 1)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))))
'())
(test "=/=-18"
(run* (q)
(fresh (x y z)
(== z 1)
(== x `(0 ,z 1))
(== y `(0 1 1))
(=/= x y)))
'())
(test "=/=-19"
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)))
'((_.0)))
(test "=/=-20"
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== y 1)))
'((_.0)))
(test "=/=-21"
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 1)))
'())
(test "=/=-24"
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 9)
(== `(,x ,y) q)))
'(((2 9))))
(test "=/=-24b"
(run* (q)
(fresh (a d)
(== `(,a . ,d) q)
(=/= q `(5 . 6))
(== a 5)
(== d 6)))
'())
(test "=/=-25"
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 1)
(== `(,x ,y) q)))
'())
(test "=/=-26"
(run* (q)
(fresh (a x z)
(=/= a `(,x 1))
(== a `(,z 1))
(== x z)))
'())
(test "=/=-28"
(run* (q)
(=/= 3 4))
'((_.0)))
(test "=/=-29"
(run* (q)
(=/= 3 3))
'())
(test "=/=-30"
(run* (q) (=/= 5 q)
(=/= 6 q)
(== q 5))
'())
(test "=/=-32"
(run* (q)
(fresh (a)
(== 3 a)
(=/= a 4)))
'((_.0)))
(test "=/=-35"
(let ((foo (lambda (x)
(fresh (a)
(=/= x a)))))
(run* (q) (fresh (a) (foo a))))
'((_.0)))
(test "=/=-36"
(let ((foo (lambda (x)
(fresh (a)
(=/= x a)))))
(run* (q) (fresh (b) (foo b))))
'((_.0)))
(test "=/=-37c"
(run* (q)
(fresh (a d)
(== `(,a . ,d) q)
(=/= q `(5 . 6))
(== a 3)))
'(((3 . _.0))))
(test "=/=-47"
(run* (x)
(fresh (y z)
(=/= x `(,y 2))
(== x `(,z 2))))
'(((_.0 2))))
(test "=/=-48"
(run* (x)
(fresh (y z)
(=/= x `(,y 2))
(== x `((,z) 2))))
'((((_.0) 2))))
(test "=/=-49"
(run* (x)
(fresh (y z)
(=/= x `((,y) 2))
(== x `(,z 2))))
'(((_.0 2))))
(test "numbero-2"
(run* (q) (numbero q) (== 5 q))
'((5)))
(test "numbero-3"
(run* (q) (== 5 q) (numbero q))
'((5)))
(test "numbero-4"
(run* (q) (== 'x q) (numbero q))
'())
(test "numbero-5"
(run* (q) (numbero q) (== 'x q))
'())
(test "numbero-6"
(run* (q) (numbero q) (== `(1 . 2) q))
'())
(test "numbero-7"
(run* (q) (== `(1 . 2) q) (numbero q))
'())
(test "numbero-8"
(run* (q) (fresh (x) (numbero x)))
'((_.0)))
(test "numbero-9"
(run* (q) (fresh (x) (numbero x)))
'((_.0)))
(test "numbero-14-b"
(run* (q) (fresh (x) (numbero q) (== 5 x) (== x q)))
'((5)))
(test "numbero-15"
(run* (q) (fresh (x) (== q x) (numbero q) (== 'y x)))
'())
(test "numbero-24-a"
(run* (q)
(fresh (w x y z)
(=/= `(,w . ,x) `(,y . ,z))
(numbero w)
(numbero z)))
'((_.0)))
(test "symbolo-2"
(run* (q) (symbolo q) (== 'x q))
'((x)))
(test "symbolo-3"
(run* (q) (== 'x q) (symbolo q))
'((x)))
(test "symbolo-4"
(run* (q) (== 5 q) (symbolo q))
'())
(test "symbolo-5"
(run* (q) (symbolo q) (== 5 q))
'())
(test "symbolo-6"
(run* (q) (symbolo q) (== `(1 . 2) q))
'())
(test "symbolo-7"
(run* (q) (== `(1 . 2) q) (symbolo q))
'())
(test "symbolo-8"
(run* (q) (fresh (x) (symbolo x)))
'((_.0)))
(test "symbolo-9"
(run* (q) (fresh (x) (symbolo x)))
'((_.0)))
(test "symbolo-14-b"
(run* (q) (fresh (x) (symbolo q) (== 'y x) (== x q)))
'((y)))
(test "symbolo-15"
(run* (q) (fresh (x) (== q x) (symbolo q) (== 5 x)))
'())
(test "symbolo-24-a"
(run* (q)
(fresh (w x y z)
(=/= `(,w . ,x) `(,y . ,z))
(symbolo w)
(symbolo z)))
'((_.0)))
(test "symbolo-numbero-1"
(run* (q) (symbolo q) (numbero q))
'())
(test "symbolo-numbero-2"
(run* (q) (numbero q) (symbolo q))
'())
(test "symbolo-numbero-3"
(run* (q)
(fresh (x)
(numbero x)
(symbolo x)))
'())
(test "symbolo-numbero-4"
(run* (q)
(fresh (x)
(symbolo x)
(numbero x)))
'())
(test "symbolo-numbero-5"
(run* (q)
(numbero q)
(fresh (x)
(symbolo x)
(== x q)))
'())
(test "symbolo-numbero-6"
(run* (q)
(symbolo q)
(fresh (x)
(numbero x)
(== x q)))
'())
(test "symbolo-numbero-7"
(run* (q)
(fresh (x)
(numbero x)
(== x q))
(symbolo q))
'())
(test "symbolo-numbero-7"
(run* (q)
(fresh (x)
(symbolo x)
(== x q))
(numbero q))
'())
(test "symbolo-numbero-8"
(run* (q)
(fresh (x)
(== x q)
(symbolo x))
(numbero q))
'())
(test "symbolo-numbero-9"
(run* (q)
(fresh (x)
(== x q)
(numbero x))
(symbolo q))
'())
(test "symbolo-numbero-32"
(run* (q)
(fresh (x y)
(=/= `(,x ,y) q)
(numbero x)
(symbolo y)))
'((_.0)))
(test "symbolo-numbero-33"
(run* (q)
(fresh (x y)
(numbero x)
(=/= `(,x ,y) q)
(symbolo y)))
'((_.0)))
(test "symbolo-numbero-34"
(run* (q)
(fresh (x y)
(numbero x)
(symbolo y)
(=/= `(,x ,y) q)))
'((_.0)))
(test "test 24"
(run* (q) (== 5 q) (absento 5 q))
'())
(test "test 25"
(run* (q) (== q `(5 6)) (absento 5 q))
'())
(test "test 25b"
(run* (q) (absento 5 q) (== q `(5 6)))
'())
(test "test 26"
(run* (q) (absento 5 q) (== 5 q))
'())
(test "test 33"
(run* (q)
(fresh (a b c)
(== `(,a ,b) c)
(== `(,c ,c) q)
(symbolo b)
(numbero c)))
'())
(test "test 40"
(run* (q)
(fresh (d a c)
(== `(3 . ,d) q)
(=/= `(,c . ,a) q)
(== '(3 . 4) d)))
'(((3 3 . 4))))
(test "test 41"
(run* (q)
(fresh (a)
(== `(,a . ,a) q)))
'(((_.0 . _.0))))
(test "test 63"
(run* (q) (fresh (a b c) (=/= a b) (=/= b c) (=/= c q) (symbolo a)))
'((_.0)))
(test "test 64"
(run* (q) (symbolo q) (== 'tag q))
'((tag)))
(test "test 66"
(run* (q) (absento 6 5))
'((_.0)))
(test "absento 'closure-1a"
(run* (q) (absento 'closure q) (== q 'closure))
'())
(test "absento 'closure-1b"
(run* (q) (== q 'closure) (absento 'closure q))
'())
(test "absento 'closure-2a"
(run* (q) (fresh (a d) (== q 'closure) (absento 'closure q)))
'())
(test "absento 'closure-2b"
(run* (q) (fresh (a d) (absento 'closure q) (== q 'closure)))
'())
(test "absento 'closure-4a"
(run* (q) (fresh (a d) (absento 'closure q) (== `(,a . ,d) q) (== 'closure a)))
'())
(test "absento 'closure-4b"
(run* (q) (fresh (a d) (absento 'closure q) (== 'closure a) (== `(,a . ,d) q)))
'())
(test "absento 'closure-4c"
(run* (q) (fresh (a d) (== 'closure a) (absento 'closure q) (== `(,a . ,d) q)))
'())
(test "absento 'closure-4d"
(run* (q) (fresh (a d) (== 'closure a) (== `(,a . ,d) q) (absento 'closure q)))
'())
(test "absento 'closure-5a"
(run* (q) (fresh (a d) (absento 'closure q) (== `(,a . ,d) q) (== 'closure d)))
'())
(test "absento 'closure-5b"
(run* (q) (fresh (a d) (absento 'closure q) (== 'closure d) (== `(,a . ,d) q)))
'())
(test "absento 'closure-5c"
(run* (q) (fresh (a d) (== 'closure d) (absento 'closure q) (== `(,a . ,d) q)))
'())
(test "absento 'closure-5d"
(run* (q) (fresh (a d) (== 'closure d) (== `(,a . ,d) q) (absento 'closure q)))
'())
(test "absento 'closure-6"
(run* (q)
(== `(3 (closure x (x x) ((y . 7))) #t) q)
(absento 'closure q))
'())
)
(define (letrec-append body)
`(letrec ((append
(lambda (xs ys)
(if (null? xs) ys (cons (car xs) (append (cdr xs) ys))))))
,body))
(module+ test
(define-syntax test-eval
(syntax-rules ()
((_ tm result)
(let ((tm0 tm))
(check-true (term? tm0 initial-env))
(check-equal? (run 1 (answer) (dk-evalo tm0 answer))
(list (list result)))))))
(test-eval 3 3)
(test-eval '3 3)
(test-eval ''x 'x)
(test-eval ''(1 (2) 3) '(1 (2) 3))
(test-eval '(car '(1 (2) 3)) 1)
(test-eval '(cdr '(1 (2) 3)) '((2) 3))
(test-eval '(cons 'x 4) '(x . 4))
(test-eval '(null? '()) #t)
(test-eval '(null? '(0)) #f)
(test-eval '(list 5 6) '(5 6))
(test-eval '(and 8 9) 9)
(test-eval '(and #f 9 10) #f)
(test-eval '(and #f (letrec ((loop (lambda (x) (loop x))))
(loop 'forever))) #f)
(test-eval '(and 8 9 10) 10)
(test-eval '(or #f 11 12) 11)
(test-eval '(or #t (letrec ((loop (lambda (x) (loop x))))
(loop 'forever))) #t)
(test-eval '(let ((p (cons 8 9))) (cdr p)) 9)
(define (letrec-append body)
`(letrec ((append
(lambda (xs ys)
(if (null? xs) ys (cons (car xs) (append (cdr xs) ys))))))
,body))
(define ex-append
(letrec-append
'(list (append '() '()) (append '(foo) '(bar)) (append '(1 2) '(3 4)))))
(define ex-append-answer '(() (foo bar) (1 2 3 4)))
(test-eval ex-append ex-append-answer)
(test-eval '`(1 ,(car `(,(cdr '(b 2)) 3)) ,'a) '(1 (2) a))
(test-eval
'(match '(1 (b 2))
(`(1 (a ,x)) 3)
(`(1 (b ,x)) x)
(_ 4))
2)
(test-eval
'(match '(1 1 2)
(`(,a ,b ,a) `(first ,a ,b))
(`(,a ,a ,b) `(second ,a ,b))
(_ 4))
'(second 1 2))
(define ex-match
'(match '(1 2 1)
(`(,a ,b ,a) `(first ,a ,b))
(`(,a ,a ,b) `(second ,a ,b))
(_ 4)))
(test-eval ex-match '(first 1 2))
(test-eval
'(match '(1 b 3)
((or `(0 ,x ,y) `(1 ,x ,y)) 'success)
(_ 'fail))
'success)
(test-eval
'(match '(1 b 3)
((or `(0 ,x ,y) `(1 ,y ,x)) 'success)
(_ 'fail))
'success)
(test-eval
'(match '(0 b 3)
((or `(0 ,x ,y) `(1 ,y ,x)) 'success)
(_ 'fail))
'success)
(define-syntax run-det
(syntax-rules ()
((_ n (qv ...) goal ...)
(map (reify var-0)
(take n (zzz ((fresh (qv ...)
(== (list qv ...) var-0) goal ...
(lambda (st) (reset-cost (state-resume-det1 st))))
state-empty)))))))
(define-syntax run*-det
(syntax-rules () ((_ body ...) (run-det #f body ...))))
(define-syntax test-dk-evalo
(syntax-rules ()
((_ tm result)
(let ((tm0 tm) (res0 result))
(when (not (term? tm0 initial-env))
(error (format "not a term: ~a" tm0)))
(dk-evalo tm0 res0)))))
(test "match-simple-0"
(run* (q r)
(test-dk-evalo
`(match ',q)
r))
'())
(test "match-simple-1"
(run* (q r)
(test-dk-evalo
`(match ',q
(_ #t))
r))
'((_.0 #t)))
(test "match-simple-2"
(run* (q r)
(test-dk-evalo
`(match ',q
(x x)
(_ #t))
r))
'((_.0 _.0)))
(test "match-simple-3"
(run* (q r)
(test-dk-evalo
`(match ',q
((not x) #f)
(_ #t))
r))
'((_.0 #t)))
(test "match-simple-4"
(run* (q r)
(test-dk-evalo
`(match ',q
(_ #f)
(_ #t))
r))
'((_.0 #f)))
(test "match-simple-5"
(run* (q r)
(test-dk-evalo
`(match ',q
((not _) #f)
(_ #t))
r))
'((_.0 #t)))
(test "match-simple-6"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
(12 'twelve)
(#t 'true)
(#f 'false)
('sym 'symbol)
('() 'nil)
('(a b) 'pair))
r))
'((8 eight)
(12 twelve)
(#t true)
(#f false)
(sym symbol)
(() nil)
((a b) pair)))
(test "match-simple-7"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
(12 'twelve)
(#t 'true)
(_ (match ',q
(#f 'false)
('sym 'symbol)
('() 'nil)
('(a b) 'pair))))
r))
'((8 eight)
(12 twelve)
(#t true)
(#f false)
(sym symbol)
(() nil)
((a b) pair)))
(test "match-simple-8"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
(12 'twelve)
(#t 'true)
(8 (match ',q
(#f 'false)
('sym 'symbol)
('() 'nil)
('(a b) 'pair))))
r))
'((8 eight) (12 twelve) (#t true)))
(test "match-simple-9"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
((number) 'number)
((symbol) 'symbol)
(12 'twelve)
(#t 'true)
(`(,x ,y . ,z) 'pair-2)
(`(,x . ,y) 'pair)
(`(,w ,x ,y . ,z) 'pair-3)
(#f 'false)
('sym 'symbol)
('() 'nil)
('(a b) 'pair)
(_ 'anything))
r))
'((8 eight)
(_.0 number)
(_.0 symbol)
(#t true)
((_.0 _.1 . _.2) pair-2)
((_.0 . _.1) pair)
(#f false)
(() nil)))
(test "match-simple-10"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
((number) 'number)
((symbol) 'symbol)
(12 'twelve)
(#t 'true)
(`(,x ,y . ,z) 'pair-2)
(`(,x . ,y) 'pair)
(`(,w ,x ,y . ,z) 'pair-3)
(#f 'false)
('sym 'symbol)
('(a b) 'pair)
(_ 'anything))
r))
'((8 eight)
(_.0 number)
(_.0 symbol)
(#t true)
((_.0 _.1 . _.2) pair-2)
((_.0 . _.1) pair)
(#f false)
(() anything)))
(test "match-simple-11"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
((number) 'number)
((symbol) 'symbol)
(12 'twelve)
(#t 'true)
(`(,x ,y . ,z) 'pair-2)
(`(,x . ,y) 'pair)
(`(,w ,x ,y . ,z) 'pair-3)
('sym 'symbol)
('(a b) 'pair)
((not '()) 'anything))
r))
'((8 eight)
(_.0 number)
(_.0 symbol)
(#t true)
((_.0 _.1 . _.2) pair-2)
((_.0 . _.1) pair)
(#f anything)))
(test "match-simple-12"
(run* (q r)
(test-dk-evalo
`(match ',q
(8 'eight)
((number) 'number)
((symbol) 'symbol)
(12 'twelve)
(#t 'true)
(`(,x ,y . ,z) 'pair-2)
(`(,x . ,y) 'pair)
(`(,w ,x ,y . ,z) 'pair-3)
('sym 'symbol)
('(a b) 'pair)
((not '()) 'anything))
r))
'((8 eight)
(_.0 number)
(_.0 symbol)
(#t true)
((_.0 _.1 . _.2) pair-2)
((_.0 . _.1) pair)
(#f anything)))
(test "match-compound-1"
(run* (q r)
(test-dk-evalo
`(match ',q
((and #t #f #t) 'impossible))
r))
'())
(test "match-compound-2"
(run* (q r)
(test-dk-evalo
`(match ',q
((and #t #t #t) 'possible)
(#t 'true)
(#f 'false))
r))
'((#t possible) (#f false)))
(test "match-compound-3"
(run* (q r)
(test-dk-evalo
`(match ',q
((or #t #f #t) 'possible)
(#t 'true)
(#f 'false))
r))
'((#t possible) (#f possible)))
(test "match-compound-4"
(run* (q r)
(test-dk-evalo
`(match ',q
((not (or #t #f #t)) 'possible)
(#t 'true)
(#f 'false))
r))
'((_.0 possible) (#t true) (#f false)))
(test "match-compound-5"
(run* (q r)
(test-dk-evalo
`(match ',q
((and (not (or #t #f #t)) #t) 'impossible)
(#t 'true)
(#f 'false))
r))
'((#t true) (#f false)))
(test "match-compound-6"
(run* (q r)
(test-dk-evalo
`(match ',q
((not (not (and #t #t #t))) 'possible)
(#t 'true)
(#f 'false))
r))
'((#t possible) (#f false)))
(test "match-compound-7"
(run* (q r)
(test-dk-evalo
`(match ',q
((not (not (and #t (not #t) #t))) 'impossible)
(#t 'true)
(#f 'false))
r))
'((#t true) (#f false)))
(test "match-compound-8"
(run* (q r)
(test-dk-evalo
`(match ',q
((or #t #f #t 5) 'possible)
(#t 'true)
(#f 'false))
r))
'((#t possible) (#f possible) (5 possible)))
(test "match-compound-8b"
(run* (q r)
(=/= #t q)
(test-dk-evalo
`(match ',q
((or #t #f #t 5) 'possible)
(#t 'true)
(#f 'false))
r))
'((#f possible) (5 possible)))
(test "match-compound-8c"
(run* (q r)
(test-dk-evalo
`(match ',q
((or #t #f #t 5) 'possible)
(#t 'true)
(#f 'false))
r)
(=/= #t q))
'((#f possible) (5 possible)))
(test "match-qq-1"
(run* (q r)
(test-dk-evalo
`(match ',q
(`(,(and 1 1 1) . ,(and 2 2 2)) 'ok))
r))
'(((1 . 2) ok)))
(test "match-qq-2a"
(run* (q r)
(test-dk-evalo
`(match ',q
(`(,(and 1 (not 1) 1) . ,(and 2 2 2)) 'ok))
r))
'())
(test "match-qq-2b"
(run* (q r)
(test-dk-evalo
`(match ',q
(`(,(and 1 (not 2) 1) . ,(and 2 2 2)) 'ok))
r))
'(((1 . 2) ok)))
(test "match-qq-3"
(run* (q r)
(test-dk-evalo
`(match ',q
(`(,(and 1 x 1) . ,(and 2 y 2)) 'ok))
r))
'(((1 . 2) ok)))
(test "match-qq-4"
(run* (q r)
(test-dk-evalo
`(match ',q
(`(,(and 1 x 1) . ,(and 2 x 2)) 'ok))
r))
'())
(test "match-qq-5"
(run* (q r)
(test-dk-evalo
`(match ',q
((and `(1 . ,x) `(,y . 2)) 'ok))
r))
'(((1 . 2) ok)))
(test "match-qq-6"
(run* (q r)
(test-dk-evalo
`(match ',q
((and `(1 . ,x) `(,x . 2)) 'ok))
r))
'())
(test "match-?-0"
(run* (q r)
(test-dk-evalo
`(let ((ok? (lambda (x) #f)))
(match ',q
((? ok?) 'ok)))
r))
'())
(test "match-?-1"
(run* (q r)
(test-dk-evalo
`(let ((ok? (lambda (x) #t)))
(match ',q
((? ok?) 'ok)))
r))
'((_.0 ok)))
(test "match-?-2"
(run* (q r)
(test-dk-evalo
`(let ((ok? (lambda (x) #f)))
(match ',q
((? ok?) 'ok)
(3 'three)))
r))
'((3 three)))
(test "match-?-4"
(run* (q r)
(test-dk-evalo
`(let ((number? (lambda (x) (match x
((number) #t)
(_ #f)))))
(match ',q
((? number?) 'ok)))
r))
'((_.0 ok)))
(test "match-?-5"
(run* (q r)
(test-dk-evalo
`(let ((number? (lambda (x) (match x
((number) #t)
(_ #f)))))
(match ',q
((? number?) 'ok)
(4 'four)
(#t 'true)
))
r))
'((_.0 ok) (#t true)))
(test "match-match-0"
(run* (q r)
(test-dk-evalo
`(match (match ',q
('a 15)
('b 16)
('c 19)
('d 16)
('e 15)
('f 14))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
r))
'())
(test "match-match-1"
(run* (q r)
(test-dk-evalo
`(match (match ',q
('a 5)
('b 6)
('c 9)
('d 6)
('e 5)
('f 4))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
r))
'((a 2) (b 3) (d 3) (e 2) (f 1)))
(test "match-match-2"
(run* (q)
(test-dk-evalo
`(match (match ',q
('a 5)
('b 6)
('c 9)
('d 6)
('e 5)
('f 7)
('g 4))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
2))
'((a) (e) (f)))
(test "match-match-3"
(run* (q r)
(test-dk-evalo
`(match (match ',q
('a 5)
('b 6)
('c 9)
('d 6)
('e 5)
('f 7)
('g 4))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
r)
(== 2 r))
'((a 2) (e 2) (f 2)))
(test "match-match-4"
(run* (q r)
(== 2 r)
(test-dk-evalo
`(match (match ',q
('a 5)
('b 6)
('c 9)
('d 6)
('e 5)
('f 7)
('g 4))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
r))
'((a 2) (e 2) (f 2)))
(test "match-match-det-1"
(run*-det (q)
(test-dk-evalo
`(match (match ',q
('a 5)
('b 6)
('c 9)
('d 8)
('d 6)
('e 5)
('f 7)
('g 4))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
3))
'((b)))
(test "match-match-det-2"
(run*-det (q r)
(test-dk-evalo
`(match (match ',q
('a 5)
('b 6)
('c 9)
('d 8)
('d 6)
('e 5)
('f 7)
('g 4))
(4 1)
(5 2)
(6 3)
(7 2)
(8 1))
r)
(== r 3))
'((b 3)))
(test "append-deterministic-1"
(run*-det (q)
(test-dk-evalo (letrec-append `(append '(1 2 3) ',q)) '(1 2 3 4 5)))
'(((4 5))))
(test "append-deterministic-2"
(run*-det (q)
(fresh (a b c) (== `(,a ,b ,c) q))
(test-dk-evalo (letrec-append `(append ',q '(4 5))) '(1 2 3 4 5)))
'(((1 2 3))))
(test "append-deterministic-3"
(run*-det (q)
(test-dk-evalo (letrec-append `(append ',q '(4 5))) '(1 2 3 4 5))
(fresh (a b c) (== `(,a ,b ,c) q)))
'(((1 2 3))))
(test "append-nondet-1"
(run* (q)
(test-dk-evalo (letrec-append `(append ',q '(4 5))) '(1 2 3 4 5)))
'(((1 2 3))))
(test "append-nondet-2"
(run* (q r)
(test-dk-evalo (letrec-append `(append ',q ',r)) '(1 2 3 4 5)))
'((() (1 2 3 4 5))
((1) (2 3 4 5))
((1 2) (3 4 5))
((1 2 3) (4 5))
((1 2 3 4) (5))
((1 2 3 4 5) ())))
)
| true |
f9b36e102d7ae25a45527906b6e33a405f2d2450 | 964bb56e1e21091cf07a49b51394d02fcdb018f7 | /ch02/2_13.rkt | b836b3e7fa09e69c86eb158e7df5d443fc0655ac | []
| no_license | halee99/SICP | fa7758f96c6363b3b262e3b695f11f1c1072c628 | de282c9f595b3813d3f6b162e560b0a996150bd2 | refs/heads/master | 2020-04-06T14:52:39.639013 | 2019-10-10T09:14:56 | 2019-10-10T09:14:56 | 157,557,554 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 307 | rkt | 2_13.rkt | ; 设 x,y 分别是两个区间中间值,e,r 分别为精度
; 有
; (x-xe, x+xe) (y-yr, y+yr)
; 相乘得 (假设所有数为正数)
; ((x-xe)(y-yr), (x+xe)(y+yr))
; 由 p = 1 - lower / c 得
; p = 1 - (x-xe)(y-yr) / {[(x-xe)(y-yr) + (x+xe)(y+yr)] / 2}
; p = 1 - 2(1-e)(1-r) / [(1-e)(1-r) + (1+e)(1+r)]
| false |
e61dc74490dea8096304ea05bc955507f2c0a453 | 00ff1a1f0fe8046196c043258d0c5e670779009b | /doc/guide/scribble/datatypes/vectors.scrbl | 0cb7c89a8f9e6f6d72b97ac5e17193b7177f913b | [
"BSD-2-Clause"
]
| permissive | edbutler/rosette | 73364d4e5c25d156c0656b8292b6d6f3d74ceacf | 55dc935a5b92bd6979e21b5c12fe9752c8205e7d | refs/heads/master | 2021-01-14T14:10:57.343419 | 2014-10-26T05:12:03 | 2014-10-26T05:12:03 | 27,899,312 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,805 | scrbl | vectors.scrbl | #lang scribble/manual
@(require (for-label
rosette/base/define rosette/query/tools rosette/query/eval
rosette/base/term rosette/base/primitive
(only-in rosette/base/safe assert)
racket)
scribble/core scribble/html-properties scribble/eval racket/sandbox
"../util/lifted.rkt")
@(define rosette-eval (rosette-evaluator))
@(define vector-ops (select '(vector? make-vector vector vector-immutable vector-length vector-ref vector-set! vector->list list->vector vector->immutable-vector vector-fill! vector-copy! vector->values build-vector immutable?)))
@(define more-vector-ops (select '(vector-set*! vector-map vector-map! vector-append vector-take vector-take-right vector-drop vector-drop-right vector-split-at vector-split-at-right vector-copy vector-filter vector-filter-not vector-count vector-argmin vector-argmax vector-member vector-memv vector-memq)))
@title[#:tag "sec:vec"]{Vectors}
A vector is a fixed-length (im)mutable array.
Vectors may be concrete or symbolic, and they may be accessed using concrete
or symbolic indices. A concrete vector supports constant-time access for
concrete slot indices, and linear-time access for symbolic slot indices.
A symbolic vector supports (worst-case) linear- and quadratic-time access for concrete and
symbolic indices, respectively. Access time for symbolic vectors is given with
respect to the longest possible concrete array to which any symbolic vector
could @racket[evaluate] under any @racket[solution?].
Like @seclink["sec:pair"]{pairs and lists}, immutable vectors are values: two such vectors are @racket[eq?] if
they have the same length and @racket[eq?] contents. Mutable vectors are references
rather than values, and two mutable vectors are @racket[eq?] if and only if they
point to the same array object. Two vectors (regardless of mutability) are @racket[equal?]
if they have the same length and @racket[equal?] contents.
@examples[#:eval rosette-eval
(define v1 (vector 1 2 #f))
(define v2 (vector 1 2 #f))
(eq? v1 v2)
(equal? v1 v2)
(define v3 (vector-immutable 1 2 #f))
(define v4 (vector-immutable 1 2 #f))
(eq? v3 v4)
(equal? v1 v3)
]
@examples[#:eval rosette-eval
(define-symbolic x y z n number?)
(code:line (define xs (take (list x y z) n)) (code:comment "xs is a symbolic list"))
(code:line (define vs (list->vector xs)) (code:comment "vs is a symbolic vector"))
(define sol (solve (assert (= 4 (vector-ref vs (sub1 n))))))
(evaluate vs sol)
(evaluate xs sol)]
The following vector operations are lifted to work on both concrete and symbolic values:
@tabular[#:style (style #f (list (attributes '((id . "lifted")(class . "boxed")))))
(list (list @elem{@vector-ops, @more-vector-ops}))]
@(kill-evaluator rosette-eval) | false |
58aee159cac66751707eb09382e5d0a91042e492 | 0ac2d343bad7e25df1a2f2be951854d86b3ad173 | /pycket/pycket-lang/set-export.rkt | ce5dc81f633f13a29dbae01a86d71625a0058598 | [
"MIT"
]
| permissive | pycket/pycket | 8c28888af4967b0f85c54f83f4ccd536fc8ac907 | 05ebd9885efa3a0ae54e77c1a1f07ea441b445c6 | refs/heads/master | 2021-12-01T16:26:09.149864 | 2021-08-08T17:01:12 | 2021-08-08T17:01:12 | 14,119,907 | 158 | 14 | MIT | 2021-08-08T17:01:12 | 2013-11-04T18:39:34 | Python | UTF-8 | Racket | false | false | 50 | rkt | set-export.rkt | #lang pycket
(define x 1)
(set! x #f)
(provide x)
| false |
b38f5d228e2c50eaa00554e6bedd02ae3ab94c0c | 5bbc152058cea0c50b84216be04650fa8837a94b | /experimental/postmortem/experiments/adaptor/many-adaptor/gregor/both/moment-base-adapted.rkt | 1960efd9203edaff4d97af7874eff6e0fd302f32 | []
| no_license | nuprl/gradual-typing-performance | 2abd696cc90b05f19ee0432fb47ca7fab4b65808 | 35442b3221299a9cadba6810573007736b0d65d4 | refs/heads/master | 2021-01-18T15:10:01.739413 | 2018-12-15T18:44:28 | 2018-12-15T18:44:28 | 27,730,565 | 11 | 3 | null | 2018-12-01T13:54:08 | 2014-12-08T19:15:22 | Racket | UTF-8 | Racket | false | false | 440 | rkt | moment-base-adapted.rkt | #lang typed/racket/base
(require
benchmark-util
"datetime-adapted.rkt"
)
(require/typed/check "moment-base.rkt"
[#:struct Moment ([datetime/local : DateTime] [utc-offset : Integer] [zone : (U String #f)])]
( moment->iso8601/tzid (-> Moment String))
( moment->iso8601 (-> Moment String))
( make-moment (-> DateTime Integer (U String #f) Moment))
)
(provide
moment->iso8601
moment->iso8601/tzid
make-moment
(struct-out Moment)
)
| false |
5fb5a383ea5d38daca918fad291dacd785de761b | 2bee16df872240d3c389a9b08fe9a103f97a3a4f | /racket/P113.rkt | 82a5463a51a071733f4e36e7f0770bb68397e926 | []
| no_license | smrq/project-euler | 3930bd5e9b22f2cd3b802e36d75db52a874bd542 | 402419ae87b7180011466d7443ce22d010cea6d1 | refs/heads/master | 2021-01-16T18:31:42.061121 | 2016-07-29T22:23:05 | 2016-07-29T22:23:05 | 15,920,800 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 533 | rkt | P113.rkt | #lang racket
(require "math.rkt")
(define (increasing-count digits)
(for/sum ([k (in-range 1 10)])
(simplex-number k (- digits 1))))
(define (decreasing-count digits)
(sub1 (for/sum ([k (in-range 1 11)])
(simplex-number k (- digits 1)))))
(define (not-bouncy-count digits)
; overlap between increasing and decreasing is 9 numbers per digit count (1111, 2222, ..., 9999)
(+ (increasing-count digits)
(decreasing-count digits)
-9))
(for/sum ([digits (in-range 1 (add1 100))])
(not-bouncy-count digits))
| false |
efdd1381c459cb2b13a94a1bb019a90dff3e3632 | 1a57d2f221dac189fa407998a1821e4dc5998f4c | /bf/info.rkt | 0070f93a76da4a957723d6110dc846bb2e2c5331 | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | thulsadum/racket-language-boilerplates | 90ba2afa0f4620891ff2f57392e33acf4ea5678d | e0f73daa889e32a7fc7295dd4510eef69ae15003 | refs/heads/master | 2021-07-08T00:43:03.397218 | 2017-10-04T20:48:35 | 2017-10-04T20:48:35 | 105,070,024 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 118 | rkt | info.rkt | #lang info
(define collection "brainfuck")
(define pkg-desc "An implementation of the esoteric language in racket.")
| false |
9f27fba958979574517f4a63e340e0e1324a1834 | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/ast/meta-functions.rkt | 70d86bed075738d5ae809e3fabd17b88f7e3b9ee | [
"MIT"
]
| permissive | philnguyen/soft-contract | 263efdbc9ca2f35234b03f0d99233a66accda78b | 13e7d99e061509f0a45605508dd1a27a51f4648e | refs/heads/master | 2021-07-11T03:45:31.435966 | 2021-04-07T06:06:25 | 2021-04-07T06:08:24 | 17,326,137 | 33 | 7 | MIT | 2021-02-19T08:15:35 | 2014-03-01T22:48:46 | Racket | UTF-8 | Racket | false | false | 9,271 | rkt | meta-functions.rkt | #lang typed/racket/base
(provide meta-functions@)
(require racket/match
racket/set
racket/string
(only-in racket/function curry)
racket/list
racket/bool
typed/racket/unit
set-extras
unreachable
"../utils/main.rkt"
"signatures.rkt")
(define-unit meta-functions@
(import static-info^ ast-macros^)
(export meta-functions^)
(: fv : -e → (℘ Symbol))
;; Compute free variables for expression. Return set of variable names.
(define (fv e)
(match e
[(-x x _) (if (symbol? x) {seteq x} ∅eq)]
[(-λ xs e _) (set-subtract (fv e) (formals->names xs))]
[(-case-λ cases _) (apply ∪ ∅eq (map fv cases))]
[(-@ f xs _) (apply ∪ (fv f) (map fv xs))]
[(-begin es) (apply ∪ ∅eq (map fv es))]
[(-begin0 e₀ es) (apply ∪ (fv e₀) (map fv es))]
[(-let-values bnds e _)
(define-values (bound rhs:fv)
(for/fold ([bound : (℘ Symbol) ∅eq] [rhs:fv : (℘ Symbol) ∅eq])
([bnd bnds])
(match-define (cons xs rhs) bnd)
(values (set-add* bound xs) (∪ rhs:fv (fv rhs)))))
(∪ rhs:fv (set-subtract (fv e) bound))]
[(-letrec-values bnds e _)
(define bound (for/fold ([bound : (℘ Symbol) ∅eq]) ([bnd bnds])
(set-add* bound (car bnd))))
(set-subtract (apply ∪ (fv e) (map (compose1 fv (inst cdr Any -e)) bnds)) bound)]
[(-set! x e _) (if (symbol? x) (set-add (fv e) x) (fv e))]
[(-if e e₁ e₂ _) (∪ (fv e) (fv e₁) (fv e₂))]
[(-parameterize bs e _)
(define-values (ls rs) (unzip bs))
(apply ∪ (apply ∪ (fv e) (map fv ls)) (map fv rs))]
[(-contract c e _ _ _) (∪ (fv c) (fv e))]
[(-rec/c (-x x _)) (if (symbol? x) {set x} ∅eq)]
[(-->i (-var cs c) d)
(define dom-fv : (-dom → (℘ Symbol))
(match-lambda
[(-dom _ ?xs d _) (set-subtract (fv d) (if ?xs (list->seteq ?xs) ∅eq))]))
(∪ (apply ∪ (if c (dom-fv c) ∅eq) (map dom-fv cs))
(if d (apply ∪ ∅eq (map dom-fv d)) ∅eq))]
[(case--> cases) (apply ∪ ∅eq (map fv cases))]
[_ (log-debug "FV⟦~a⟧ = ∅~n" e) ∅eq]))
(: fv-count : -e Symbol → Natural)
(define (fv-count e z)
(let go ([e : -e e])
(match e
[(-x x _) (if (equal? x z) 1 0)]
[(-λ (-var xs x) e _)
(define bound? (or (and x (eq? x z)) (memq z xs)))
(if bound? 0 (go e))]
[(-case-λ cases _) (apply + (map go cases))]
[(-@ f xs _) (apply + (go f) (map go xs))]
[(-begin es) (apply + (map go es))]
[(-begin0 e₀ es) (apply + (go e₀) (map go es))]
[(-let-values bnds e _)
(define-values (sum₀ bound?)
(for/fold ([sum : Natural 0] [bound? : Any #f])
([bnd : (Pairof (Listof Symbol) -e) (in-list bnds)])
(match-define (cons xs eₓ) bnd)
(values (+ sum (go eₓ)) (or bound? (memq z xs)))))
(+ sum₀ (if bound? 0 (go e)))]
[(-letrec-values bnds e _)
(define bound? (for/or : Any ([bnd (in-list bnds)]) (memq z (car bnd))))
(if bound?
0
(apply + (go e) (map (λ ([bnd : (Pairof Any -e)]) (go (cdr bnd))) bnds)))]
[(-set! x e _) (go e)]
[(-if e e₁ e₂ _) (+ (go e) (go e₁) (go e₂))]
[(-parameterize bs e _)
(define-values (ls rs) (unzip bs))
(apply + (apply + (go e) (map go ls)) (map go rs))]
[(-contract c e _ _ _) (+ (go c) (go e))]
[(-rec/c (-x x _)) (if (equal? x z) 1 0)]
[(-->i (-var cs c) d)
(define dom-count : (-dom → Natural)
(match-lambda [(-dom x _ eₓ _) (if (equal? x z) 0 (go eₓ))]))
(+ (apply + (if c (dom-count c) 0) (map dom-count cs))
(if d (apply + (map dom-count d)) 0))]
[(case--> cases) (apply + (map go cases))]
[_ 0])))
#;(: find-calls : -e (U -𝒾 -•) → (℘ (Listof -e)))
;; Search for all invocations of `f-id` in `e`
#;(define (find-calls e f-id)
(define-set calls : (Listof -e))
(let go! : Void ([e e])
(match e
[(-@ f xs _)
(go! f)
(for-each go! xs)
(when (equal? f f-id)
(calls-add! xs))]
[_ (void)]))
calls)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; Substitution
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (e/map [m : Subst] [e : -e])
(: go-list : Subst (Listof -e) → (Listof -e))
(define (go-list m es)
(for/list : (Listof -e) ([e es]) (go m e)))
(: go--->i : Subst -->i → -->i)
(define (go--->i m c)
(define go/dom : (-dom → -dom)
(match-lambda
[(-dom x ?xs d ℓ)
(define d* (if ?xs (go (remove-keys m (list->seteq ?xs)) d) (go m d)))
(-dom x ?xs d* ℓ)]))
(match-define (-->i cs d) c)
(-->i (var-map go/dom cs) (and d (map go/dom d))))
(: go : Subst -e → -e)
(define (go m e)
(with-debugging/off
((ans)
(cond
[(hash-empty? m) e]
[else
(match e
[(-x x _) (hash-ref m x (λ () e))]
[(-λ xs e* ℓ)
(-λ xs (go (remove-keys m (formals->names xs)) e*) ℓ)]
[(-case-λ cases ℓ)
(-case-λ (cast (go-list m cases) (Listof -λ)) ℓ)]
[(-@ f xs ℓ)
(-@/simp (go m f) (go-list m xs) ℓ)]
[(-if e₀ e₁ e₂ ℓ)
(-if (go m e₀) (go m e₁) (go m e₂) ℓ)]
[(-wcm k v b)
(-wcm (go m k) (go m v) (go m b))]
[(-begin es)
(-begin (go-list m es))]
[(-begin0 e₀ es)
(-begin0 (go m e₀) (go-list m es))]
[(-let-values bnds body ℓ)
(define-values (bnds*-rev locals)
(for/fold ([bnds*-rev : (Assoc (Listof Symbol) -e) '()]
[locals : (℘ Symbol) ∅eq])
([bnd bnds])
(match-define (cons xs eₓ) bnd)
(values (cons (cons xs (go m eₓ)) bnds*-rev)
(set-add* locals xs))))
(define body* (go (remove-keys m locals) body))
(-let-values (reverse bnds*-rev) body* ℓ)]
[(-letrec-values bnds body ℓ)
(define locals
(for/fold ([locals : (℘ Symbol) ∅eq])
([bnd bnds])
(match-define (cons xs _) bnd)
(set-add* locals xs)))
(define m* (remove-keys m locals))
(define bnds* : (Assoc (Listof Symbol) -e)
(for/list ([bnd bnds])
(match-define (cons xs eₓ) bnd)
(cons xs (go m* eₓ))))
(define body* (go m* body))
(-letrec-values bnds* body* ℓ)]
[(-set! x e* ℓ)
(assert (not (hash-has-key? m x)))
(-set! x (go m e*) ℓ)]
[(-parameterize bs e ℓ)
(define-values (xs es) (unzip bs))
(define bs*
(for/list : (Listof (Pairof -e -e)) ([x (in-list xs)] [e (in-list es)])
(cons (go m x) (go m e))))
(-parameterize bs* (go m e) ℓ)]
[(-contract c e l+ l- ℓ)
(-contract (go m c) (go m e) l+ l- ℓ)]
[(-rec/c (-x x _)) (if (hash-has-key? m x) !!! e)]
[(? -->i? c) (go--->i m c)]
[(case--> cases) (case--> (map (curry go--->i m) cases))]
[_
;(printf "unchanged: ~a @ ~a~n" (show-e e) (show-subst m))
e])]))
(printf "go: ~a ~a -> ~a~n" (show-subst m) (show-e e) (show-e ans))))
(go m e))
(: e/ : Symbol -e -e → -e)
(define (e/ x eₓ e) (e/map (hasheq x eₓ) e))
(: remove-keys : Subst (℘ Symbol) → Subst)
(define (remove-keys m xs)
(for/fold ([m : Subst m]) ([x (in-set xs)])
(hash-remove m x)))
(: formals->names ([-formals] [#:eq? Boolean] . ->* . (℘ Symbol)))
(define (formals->names xs #:eq? [use-eq? #t]) (var->set xs #:eq? use-eq?))
(: first-forward-ref : (Listof -dom) → (Option Symbol))
(define (first-forward-ref doms)
(define-set seen : Symbol #:eq? #t #:mutable? #t)
(for/or : (Option Symbol) ([dom (in-list doms)])
(match-define (-dom x ?xs _ _) dom)
(seen-add! x)
(and ?xs
(for/or : (Option Symbol) ([x (in-list ?xs)] #:unless (seen-has? x))
x))))
(: +x! : (U Symbol Integer) * → Symbol)
(define (+x! . prefixes)
(define (stuff->string x) (format "~a" x))
(define prefix (string-join (map stuff->string prefixes) "_" #:after-last "_"))
(gensym prefix))
(: +x!/memo : (U Symbol Integer) * → Symbol)
(define +x!/memo
(let ([m : (HashTable (Listof (U Symbol Integer)) Symbol) (make-hash)])
(λ [xs : (U Symbol Integer) *]
(hash-ref! m xs (λ () (apply +x! xs))))))
(define (any/c? x) (equal? x 'any/c))
)
| false |
2bed9e5468d1979a4931b7428cfb012949d318c0 | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/fail/bad-prop-procedure8.rkt | 9654867b5988f932e8c12c210ea5330feb2c0a06 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/typed-racket | 2cde60da289399d74e945b8f86fbda662520e1ef | f3e42b3aba6ef84b01fc25d0a9ef48cd9d16a554 | refs/heads/master | 2023-09-01T23:26:03.765739 | 2023-08-09T01:22:36 | 2023-08-09T01:22:36 | 27,412,259 | 571 | 131 | NOASSERTION | 2023-08-09T01:22:41 | 2014-12-02T03:00:29 | Racket | UTF-8 | Racket | false | false | 221 | rkt | bad-prop-procedure8.rkt | #;
(exn-pred #rx"type mismatch.*expected: \\(-> adder Number Number\\).*given: String")
#lang typed/racket/base
(struct adder ([num : Number])
#:property prop:procedure
(ann "hello"
(-> adder Number Number)))
| false |
1404dec86d4c99638ed8c02bd66808cc5082f3d9 | 6c60c8d1303f357c2c3d137f15089230cb09479b | /compatibility-test/tests/mzlib/ttt/uinc4.rktl | bd0a77131118e25908729c88d9ed5e2cd0a4f592 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/compatibility | 6f96569a3e98909e1e89260eeedf4166b5e26890 | 5b2509e30e3b93ca9d6c9d6d8286af93c662d9a8 | refs/heads/master | 2023-08-23T06:41:14.503854 | 2022-07-08T02:43:36 | 2022-07-14T18:00:20 | 27,431,360 | 6 | 10 | NOASSERTION | 2022-07-14T18:00:21 | 2014-12-02T12:23:20 | Racket | UTF-8 | Racket | false | false | 66 | rktl | uinc4.rktl |
(define also-unused 'ok)
(include (build-path up "uinc.rktl"))
| false |
6d52584e43f4420199c94b70d1ebc714dae0f0b2 | 9dc73e4725583ae7af984b2e19f965bbdd023787 | /eopl-solutions/chap3/3-02.rkt | 0c7f32c77fbabf1bf3d36ae0c7e6ff022f01e930 | []
| no_license | hidaris/thinking-dumps | 2c6f7798bf51208545a08c737a588a4c0cf81923 | 05b6093c3d1239f06f3657cd3bd15bf5cd622160 | refs/heads/master | 2022-12-06T17:43:47.335583 | 2022-11-26T14:29:18 | 2022-11-26T14:29:18 | 83,424,848 | 6 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 126 | rkt | 3-02.rkt | ;; b = (bool-val #t), (expval->num (num-val b)) != b
;; due to expval->num, num-val is undefined for expressed value bool-val
| false |
585838f46e1591a5187add26db27df82c6e2393a | 3cb889e26a8e94782c637aa1126ad897ccc0d7a9 | /Lisp/ProjectEuler/43.rkt | afaeda42a99a72e25a3bf8439d10305dd6c39d2b | []
| no_license | GHScan/DailyProjects | 1d35fd5d69e574758d68980ac25b979ef2dc2b4d | 52e0ca903ee4e89c825a14042ca502bb1b1d2e31 | refs/heads/master | 2021-04-22T06:43:42.374366 | 2020-06-15T17:04:59 | 2020-06-15T17:04:59 | 8,292,627 | 29 | 10 | null | null | null | null | UTF-8 | Racket | false | false | 657 | rkt | 43.rkt | #lang racket
(require "utils.rkt")
(define (var-permutation l divisors)
(let iter ([l l][result empty][divisors divisors])
(cond
[(empty? l) (list (reverse result))]
[else
(flatten-map
(lambda (v)
(let* ([new-result (cons v result)][should-check (>= (length new-result) 3)])
(if (or (not should-check) (divisible? (list->number (reverse (take new-result 3))) (car divisors)))
(iter (remove v l) new-result (if should-check (cdr divisors) divisors))
empty)))
l)]))
)
(apply + (map list->number (var-permutation (range 10) '(1 2 3 5 7 11 13 17))))
| false |
361caaeee23c10392b38536076691a7d9fbfd157 | b544188e9e7517a216abeb93f2aec6d7bb64acd5 | /twitter/data/places.rkt | fcd17e40da15075a866ae2bf61e827134ab2d152 | []
| no_license | lyons/twitter | fc6818cb76ce783a21229415d35179eac7b5f2d5 | ba109f18d78d9a2957ff465fac32b687cef354de | refs/heads/master | 2016-09-05T23:36:03.862956 | 2014-08-21T02:52:06 | 2014-08-21T02:52:06 | 23,165,047 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,539 | rkt | places.rkt | #lang typed/racket/base
(provide (except-out (all-defined-out)
list-list-of-pair-of-float?))
(require racket/match
(only-in typed/net/url
[url URL]
string->url))
(require "../types/types.rkt"
"../types/json.rkt")
(require "private/data-helpers.rkt")
;; ---------------------------------------------------------------------------------------------------
;; Places
(: place/attributes (-> Twitter-Place
(U 'iso3 'locality 'phone 'postal_code 'region 'street_address 'twitter 'url)
(Perhaps String)))
(define (place/attributes place attribute)
(let ([x (hash-ref (Twitter-Place-data place) 'attributes JSON-Null)])
(cond
[(hash? x) (let ([y (hash-ref (json-hash x) attribute JSON-Null)])
(cond
[(string? y) y]
[else (Nothing)]))]
[else (Nothing)])))
(: place/bounding-box (-> Twitter-Place (Listof Coördinates)))
(define (place/bounding-box place)
(let ([x (hash-ref (Twitter-Place-data place) 'bounding-box JSON-Null)])
(cond
[(hash? x) (let ([y (hash-ref (json-hash x) 'coordinates JSON-Null)])
(cond
[(list-list-of-pair-of-float? y)
(map (λ ([ls : (List Inexact-Real Inexact-Real)])
(match ls [`(,lat ,long) (Coördinates lat long)]))
(car y))]
[else (unpack-error 'place/bounding-box (Listof Coördinates) y)]))]
[else (unpack-error 'place/bounding-box (HashTable Symbol JSON) x)])))
(: place/country (-> Twitter-Place String))
(define (place/country place)
(let ([x (hash-ref (Twitter-Place-data place) 'country JSON-Null)])
(cond
[(string? x) x]
[else (unpack-error 'place/country String x)])))
(: place/country-code (-> Twitter-Place String))
(define (place/country-code place)
(let ([x (hash-ref (Twitter-Place-data place) 'country_code JSON-Null)])
(cond
[(string? x) x]
[else (unpack-error 'place/country-code String x)])))
(: place/full-name (-> Twitter-Place String))
(define (place/full-name place)
(let ([x (hash-ref (Twitter-Place-data place) 'full_name JSON-Null)])
(cond
[(string? x) x]
[else (unpack-error 'place/full-name String x)])))
(: place/id (-> Twitter-Place Twitter-PlaceID))
(define (place/id place)
(let ([x (hash-ref (Twitter-Place-data place) 'id JSON-Null)])
(cond
[(string? x) (Twitter-PlaceID x)]
[else (unpack-error 'place/id Twitter-PlaceID x)])))
(: place/name (-> Twitter-Place String))
(define (place/name place)
(let ([x (hash-ref (Twitter-Place-data place) 'name JSON-Null)])
(cond
[(string? x) x]
[else (unpack-error 'place/name String x)])))
(: place/type (-> Twitter-Place String))
(define (place/type place)
(let ([x (hash-ref (Twitter-Place-data place) 'type JSON-Null)])
(cond
[(string? x) x]
[else (unpack-error 'place/type String x)])))
(: place/url (-> Twitter-Place URL))
(define (place/url place)
(let ([x (hash-ref (Twitter-Place-data place) 'url JSON-Null)])
(cond
[(string? x) (string->url x)]
[else (unpack-error 'place/url URL x)])))
;; ---------------------------------------------------------------------------------------------------
;; Helper functions
;; (╯°□°)╯︵ ┻━┻
(define-predicate list-list-of-pair-of-float? (List (Listof (List Inexact-Real Inexact-Real)))) | false |
503ffaff476d73abf6948bb985f82b6de728d276 | 7adac4df6fcfe05c55468f5497bd7a2e7d55849c | /Queen 1.rkt | c9e579d1937d109302342a221e55aafa2e5f4850 | []
| no_license | abriggs914/CS3383 | 6ec150531b173ae5013e03b5d8cda50d06d1ac11 | 8b3b2b3616310ca85a241810e705d5f3d83c957e | refs/heads/master | 2020-05-06T13:56:00.919020 | 2019-04-27T02:13:17 | 2019-04-27T02:13:17 | 180,163,979 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,025 | rkt | Queen 1.rkt | #lang racket
(struct Q (x y) #:transparent)
(define-syntax-rule (lcons x y) (cons x (lazy y)))
(define (lazy-filter p? lst)
(define flst (force lst))
(if (null? flst) '()
(let ([x (car flst)])
(if (p? x)
(lcons x (lazy-filter p? (cdr flst)))
(lazy-filter p? (cdr flst))))))
(define (lazy-foldr f base lst)
(define flst (force lst))
(if (null? flst) base
(f (car flst) (lazy (lazy-foldr f base (cdr flst))))))
(define (tails lst)
(if (null? lst) '(())
(cons lst (tails (cdr lst)))))
(define (safe? q1 q2)
(match* (q1 q2)
[((Q x1 y1) (Q x2 y2))
(not (or (= x1 x2) (= y1 y2)
(= (abs (- x1 x2)) (abs (- y1 y2)))))]))
(define (safe-lst? lst)
(or (null? lst)
(let ([q1 (car lst)])
(for/and ([q2 (cdr lst)]) (safe? q1 q2)))))
(define (valid? lst) (andmap safe-lst? (tails lst)))
(define (nqueens n)
(define all-possible-solutions
(for/fold ([qss-so-far '(())]) ([row (in-range n)])
(lazy-foldr
(λ (qs new-qss)
(append (for/list ([col (in-range n)]) (cons (Q row col) qs))
new-qss))
'() qss-so-far)))
(lazy-filter valid? all-possible-solutions))
;===========
(car (nqueens 4))
;; => (list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 2) (Q 3 5) (Q 2 7) (Q 1 4) (Q 0 0))
;---==
(define (force-and-print qs)
(define forced (force qs))
(unless (null? forced)
(printf "~v\n" (car forced))
(force-and-print (cdr forced))))
(force-and-print (nqueens 4))
; =>
;(list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 2) (Q 3 5) (Q 2 7) (Q 1 4) (Q 0 0))
;(list (Q 7 4) (Q 6 1) (Q 5 3) (Q 4 6) (Q 3 2) (Q 2 7) (Q 1 5) (Q 0 0))
;(list (Q 7 2) (Q 6 4) (Q 5 1) (Q 4 7) (Q 3 5) (Q 2 3) (Q 1 6) (Q 0 0))
;(list (Q 7 2) (Q 6 5) (Q 5 3) (Q 4 1) (Q 3 7) (Q 2 4) (Q 1 6) (Q 0 0))...
;(list (Q 7 5) (Q 6 3) (Q 5 6) (Q 4 0) (Q 3 2) (Q 2 4) (Q 1 1) (Q 0 7))
;(list (Q 7 3) (Q 6 6) (Q 5 4) (Q 4 1) (Q 3 5) (Q 2 0) (Q 1 2) (Q 0 7))
;(list (Q 7 4) (Q 6 6) (Q 5 1) (Q 4 5) (Q 3 2) (Q 2 0) (Q 1 3) (Q 0 7)) | true |
f5799c99c623639adfd56168b5f0862e2f23c663 | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/file-size.rkt | 77829e7c0eb5d6c5039279066e6ac851d5b94dc0 | []
| no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867677 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 62 | rkt | file-size.rkt | #lang racket
(file-size "input.txt")
(file-size "/input.txt")
| false |
ac434d5a702fad671538c5f01ab7ada34e5214d2 | 65c1f9548ad23d102a42be54ae7ef16f54767dba | /gregor-lib/gregor/private/pattern/l10n/named-trie.rkt | 4ac433c16792624e19ec1553a145c03cd98a7a88 | [
"MIT"
]
| permissive | 97jaz/gregor | ea52754ce7aa057941a5a7080415768687cc4764 | 2d20192e8795e01a1671869dddaf1984f0cbafee | refs/heads/master | 2022-07-20T12:52:15.088073 | 2022-06-28T09:48:59 | 2022-07-19T16:01:18 | 32,499,398 | 45 | 11 | null | 2022-06-28T09:50:43 | 2015-03-19T03:47:23 | Racket | UTF-8 | Racket | false | false | 910 | rkt | named-trie.rkt | #lang racket/base
(require memoize
cldr/core
cldr/dates-modern
cldr/bcp47/timezone
tzinfo
"trie.rkt")
(provide (all-defined-out))
(define/memo* (era-trie loc ci? size)
(common-trie loc ci? (list 'eras size)))
(define/memo* (quarter-trie loc ci? kind size)
(common-trie loc ci? (list 'quarters kind size)))
(define/memo* (month-trie loc ci? kind size)
(common-trie loc ci? (list 'months kind size)))
(define/memo* (weekday-trie loc ci? kind size)
(common-trie loc ci? (list 'days kind size)))
(define/memo* (period-trie loc ci? size)
(common-trie loc ci? (list 'dayPeriods 'format size)))
(define/memo* (zone-short-id-trie ci?)
(list->trie (bcp47-timezone-ids) ci?))
(define/memo* (zone-long-id-trie ci?)
(list->trie (all-tzids) ci?))
(define (common-trie loc ci? key)
(invert-hash->trie
(cldr-ref (ca-gregorian loc) key)
ci?))
| false |
97ddaf3dcbc4ac09a03372a2b4a2a8aa9a9aea90 | c51ffc5d03df9b93ae24813c3ae8566c7d29a7c6 | /examples/legacy/02-nothing.rkt | e859428bfc7705706a35623a716acba4298a2123 | []
| no_license | dedbox/racket-graphics-engine | d5b08f3ee66ed77ad7f328d389f840d086db1879 | 94d492f057e1fa712ceab1823afca31ffc80f04d | refs/heads/master | 2020-08-13T03:42:50.631983 | 2019-10-23T17:11:05 | 2019-10-23T17:11:05 | 214,898,834 | 5 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 74 | rkt | 02-nothing.rkt | #lang graphics-engine
#:verbose? #t
#:on-key-press (μ ('escape) (quit))
| false |
73a7fd7d1231b6fb0fb5563a601dc2d4845d6480 | 7c1d9600d97f65d0c5fd9ea3ac7d9d5dca3d5a19 | /rsa/rsa.rkt | 50f426bc4afbe53f22b6fb16ff20253550f6f9ef | []
| no_license | pnwamk/encryp-misc | b07149c4b57ac8d3714e9ea2247e33744c3868e0 | 7612d66c1dd67c6b28bfd9c13ff77134cbbf5367 | refs/heads/master | 2021-05-29T20:10:12.422814 | 2014-03-21T02:43:57 | 2014-03-21T02:43:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,521 | rkt | rsa.rkt | #lang racket
(require rackunit)
(require math/number-theory)
(require math/base)
; ********************************************************************
; moduler exponentiation
; b = base
; p = power
; m = modulo
(define (mod^ b p m)
(let loop ([result 1] [pow p] [base b])
(if (> pow 0)
(loop (if (odd? pow)
(modulo (* result base) m)
result)
(arithmetic-shift pow -1)
(modulo (sqr base) m))
result)))
(define a1 (random-natural 10000))
(define b1 (random-natural 10000))
(define c1 (random-natural 10000))
(define a2 (random-natural 10000))
(define b2 (random-natural 10000))
(define c2 (random-natural 10000))
(define a3 (random-natural 10000))
(define b3 (random-natural 10000))
(define c3 (random-natural 10000))
(check-equal? (mod^ a1 a2 a3) (modulo (expt a1 a2) a3))
(check-equal? (mod^ b1 b2 b3) (modulo (expt b1 b2) b3))
(check-equal? (mod^ c1 c2 c3) (modulo (expt c1 c2) c3))
; ********************************************************************
; find a prime greater than num
(define (find-prime> num)
(if (prime? num)
num
(find-prime> (add1 num))))
; ********************************************************************
; gcd
(define (gcd* a b)
(if (zero? b)
a
(gcd* b (modulo a b))))
(check-equal? (gcd 2 67) (gcd* 2 67))
(check-equal? (gcd 76 238) (gcd* 76 238))
(check-equal? (gcd 324 1984) (gcd* 324 1984))
; ********************************************************************
; Calculating d
; Extended Euclidean algorithm
(define (egcd a b)
(if (zero? b)
'(1 . 0)
(let* ([q (quotient a b)]
[r (remainder a b)]
[acc (egcd b r)]
[s (car acc)]
[t (cdr acc)])
(cons t (- s (* q t))))))
; extracts correct d from extended-eucl
(define (calc-d e phin)
(let ([d (car (egcd e phin))])
(cond
[(< 0 d phin)
d]
[(< d 0)
(+ phin d)]
[else
(error 'calc-d "invalid egcd result ~a\n" d)])))
(check-equal? (calc-d 5 72) 29)
(check-equal? (calc-d 17 3120) 2753)
(check-equal? (calc-d 17 43) 38)
; ********************************************************************
; Some big picture tests
(define range-delta (- (expt 2 512) (expt 2 511)))
(define p (find-prime> (+ (random-natural range-delta) (expt 2 511))))
(define q (find-prime> (add1 p)))
(check-equal? (and (prime? p) (prime? q) (not (= p q))) #t)
(check-equal? (< (expt 2 511 ) p (expt 2 512)) #t)
(check-equal? (< (expt 2 511 ) q (expt 2 512)) #t)
(define n (* p q))
(define e 65537)
(check-equal? (gcd* n e) 1)
(define phin (* (sub1 p) (sub1 q)))
(check-equal? (gcd* e phin) 1)
(define d (calc-d e phin))
(check-equal? (modulo (* d e) phin) 1)
(define t1 (random-natural n))
(define t2 (random-natural n))
(define t3 (random-natural n))
(check-equal? (mod^ (mod^ t1 e n) d n) t1)
(check-equal? (mod^ (mod^ t2 e n) d n) t2)
(check-equal? (mod^ (mod^ t3 e n) d n) t3)
; ********************************************************************
; Encryption w/ randomly generated values for this run(above)
(define (rsa-encr m)
(if (< m n)
(mod^ m e n)
#f))
; ********************************************************************
; Decryption w/ randomly generated values for this run(above)
(define (rsa-decr m)
(if (< m n)
(mod^ m d n)
#f))
; print out cryptographic values
(printf "p: ~a \n" p)
(printf "q: ~a \n" q)
(printf "n: ~a \n" n)
(printf "phi(n): ~a \n" phin)
(printf "e: ~a \n" e)
(printf "d: ~a \n" d) | false |
a613419c55011d80349228384050c8beec31f18a | 5bbc152058cea0c50b84216be04650fa8837a94b | /data/6.5/zombie-v6.5-2017-05-05T19:48:44.rktd | 14e251fff15299f8a5ed6e5227629d9a8fac3069 | []
| no_license | nuprl/gradual-typing-performance | 2abd696cc90b05f19ee0432fb47ca7fab4b65808 | 35442b3221299a9cadba6810573007736b0d65d4 | refs/heads/master | 2021-01-18T15:10:01.739413 | 2018-12-15T18:44:28 | 2018-12-15T18:44:28 | 27,730,565 | 11 | 3 | null | 2018-12-01T13:54:08 | 2014-12-08T19:15:22 | Racket | UTF-8 | Racket | false | false | 1,758 | rktd | zombie-v6.5-2017-05-05T19:48:44.rktd | ;; data0
;; #(-v 6.5 -i 6 benchmarks/acquire benchmarks/dungeon benchmarks/forth benchmarks/fsm benchmarks/fsmoo benchmarks/gregor benchmarks/kcfa benchmarks/lnm benchmarks/mbta benchmarks/morsecode benchmarks/sieve benchmarks/snake benchmarks/stack benchmarks/suffixtree benchmarks/synth benchmarks/take5 benchmarks/tetris benchmarks/zombie benchmarks/zordoz.6.5)
;; 6.5
;; binaries in /home/ben/code/racket/6.5/bin/
;; base @ <unknown-commit>
;; typed-racket @ 495da1bd
;; 2017-04-20T15:59:15
;; #(-v 6.5 -i 6 benchmarks/acquire benchmarks/dungeon benchmarks/forth benchmarks/fsm benchmarks/fsmoo benchmarks/gregor benchmarks/kcfa benchmarks/lnm benchmarks/mbta benchmarks/morsecode benchmarks/sieve benchmarks/snake benchmarks/stack benchmarks/suffixtree benchmarks/synth benchmarks/take5 benchmarks/tetris benchmarks/zombie benchmarks/zordoz.6.5)
;; 6.5
;; binaries in /home/ben/code/racket/6.5/bin/
;; base @ <unknown-commit>
;; typed-racket @ 495da1bd
;; 2017-04-23T00:21:54
#(
( 11 11 11 11 11 12 #| data0 |# 11)
( 10878 10801 10795 10756 10171 10255 #| data0 |# 10804)
( 79 78 79 78 77 77 #| data0 |# 78)
( 10831 10682 10872 10806 10540 10760 #| data0 |# 10687)
( 10445 10254 11027 11023 10540 11056 #| data0 |# 10885)
( 250 252 253 254 250 249 #| data0 |# 254)
( 10402 10321 11056 10477 11039 11007 #| data0 |# 11052)
( 250 250 248 252 250 248 #| data0 |# 251)
( 79 80 74 78 74 74 #| data0 |# 80)
( 10846 10944 10797 10634 10718 10884 #| data0 |# 10833)
( 77 83 82 77 83 77 #| data0 |# 77)
( 10773 10687 10877 10125 10941 10720 #| data0 |# 10718)
( 10944 11079 10324 10801 10902 10986 #| data0 |# 11063)
( 250 251 252 250 248 250 #| data0 |# 249)
( 10408 11078 10850 11206 11059 10939 #| data0 |# 10956)
( 239 227 243 229 243 242 #| data0 |# 243)
)
| false |
b32102fa7eb6f0fd1965d89676ee833d6552fbbe | 7910d52662d066da04056101721d080888562f39 | /server.rkt | 1a46df4a7f4e327baec09cd7b9510286c70e9ab3 | []
| no_license | sgpthomas/light-tunnel-rkt | 2c9d005b95b7e9bf275084f80eaacc3a84d3327c | 700b2be342aeac1f32ecd46596136756bcdf5aff | refs/heads/master | 2020-06-29T02:10:16.552339 | 2019-09-08T23:28:53 | 2019-09-08T23:28:53 | 200,407,108 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 643 | rkt | server.rkt | #lang racket/base
(require web-server/servlet
web-server/servlet-env
racket/match)
(define ns (make-base-namespace))
(define worker
(thread
(lambda ()
(let loop ()
(match (thread-receive)
[x (println (eval (read (open-input-string x)) ns))]
['stop (kill-thread (current-thread))])
(loop)))))
(define (my-app req)
(define prog (bytes->string/locale (request-post-data/raw req)))
(thread-send worker prog)
;; (eval (read (open-input-string prog)))
(response/xexpr
`(html)))
(serve/servlet my-app
#:servlet-path "/main"
#:command-line? #t)
| false |
e5a2a81fa5206dcc4caea548650bce4afeeedd63 | bbc6f7b30f79e1f8faff58ab3c27ae59ebf788fe | /slideshow-doc/scribblings/slideshow/aspect.scrbl | 34a9370a37c9a8eacceb53b5b651a57703c4df00 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | racket/slideshow | f84c101d84b8ae37bf3e9eb6358beb05014f0cdc | ad38bd11ccc0882500f1b9c8e391450c381fea4e | refs/heads/master | 2023-08-21T03:22:26.575238 | 2023-07-21T15:25:45 | 2023-07-21T17:07:33 | 27,411,846 | 36 | 21 | NOASSERTION | 2023-07-21T17:07:35 | 2014-12-02T02:47:47 | Racket | UTF-8 | Racket | false | false | 1,746 | scrbl | aspect.scrbl | #lang scribble/doc
@(require "ss.rkt")
@title[#:tag "aspect"]{Fullscreen vs. Widescreen Aspect Ratio}
Fullscreen (4:3, 1024 by 768) versus widescreen (16:9, 1360 by 766) aspect mode is a property of
an individual slide that can be selected using the @racket[#:aspect]
argument to @racket[slide]. The @racketmodname[slideshow/widescreen]
language provides a variant of @racket[slide] that makes
@racket['widescreen] the default value of @racket[#:aspect], while
@racketmodname[slideshow/fullscreen] provides a variant of
@racket[slide] that makes @racket['fullscreen] the default.
When a slide's aspect is not specified, then it adopts an aspect that
can be selected via the @DFlag{widescreen} or @DFlag{fullscreen} flag
when Slideshow starts. (That selection can be made ``sticky'' as the
default for future runs by using the @DFlag{save-aspect} flag.)
Selecting an aspect also affects the values of @racket[client-w],
@racket[client-h], @racket[full-page], and @racket[titleless-page]
from @racketmodname[slideshow], but it does not affect the bindings
from @racketmodname[slideshow/widescreen] or
@racketmodname[slideshow/fullscreen]. Keep in mind that specifying
@racket[#:aspect] for @racket[slide] does not affect the value of
@racket[client-w], etc., for constructing the slide's content, but you
can use @racket[get-client-w], etc., to obtain the aspect-specific
metrics.
Use the @racketmodname[slideshow] language for slides and libraries
that are meant to adapt to a user's selected aspect, and use
@racketmodname[slideshow/fullscreen] or
@racketmodname[slideshow/widescreen] for slides and libraries that
assume specific values for a slide's drawing area.
@include-section["fullscreen.scrbl"]
@include-section["widescreen.scrbl"]
| false |
4b1bc8e39832d5bf5cece1173d1780b8e882dad4 | 681f5c7c0ff0ba9d671556db409622595c935a68 | /demos/demo2/debug.rkt | 34bf05f331da527b22a2f22990078e84e75d0209 | []
| no_license | lixiangqi/medic | 60f7ad8ee9fc9437b1e569f12e3f90752c9805a6 | 0920090d3c77d6873b8481841622a5f2d13a732c | refs/heads/master | 2021-01-04T14:07:20.607887 | 2015-11-08T23:26:25 | 2015-11-08T23:26:25 | 29,596,045 | 14 | 4 | null | 2015-09-11T16:03:40 | 2015-01-21T15:27:17 | Racket | UTF-8 | Racket | false | false | 118 | rkt | debug.rkt | #lang racket
(require medic/core)
(medic "src2-medic.rkt")
(debug "src2.rkt")
| false |
4b69091eaaa88697e3c927a9fc630977e8fb7ee3 | c844f6dbdc3673032526ed2479798f02d027674e | /Assignment/A1/plastic-sample-tests.rkt | 73e2f7f6adda04d6a52a9d6bd904bd5cede041f9 | []
| no_license | MandyZ0/CSC324 | 48bb03ee76c4a90c2df61f9c6955762e346e3b6f | a686854debe7332898be3c1bbd22cc0068fabc2b | refs/heads/master | 2022-05-03T00:34:41.060526 | 2018-12-21T18:54:36 | 2018-12-21T18:54:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,941 | rkt | plastic-sample-tests.rkt | #lang racket #| ★ CSC324 Fall 2018: Assignment 1 Sample Tests ★ |#
; This file contains some additional sample tests for Assignment 1.
; Please note that these tests are NOT comprehensive, but instead are meant
; to give you a sense of the kinds of tests we'll be running, and to point
; out some key ideas on the assignment.
(require rackunit)
(require "plastic.rkt")
(define defn-Bool '(data Bool = (True) (False)))
(define defn-PairOfBools '(data PairOfBools = (Pair Bool Bool)))
(define defn-pair-and
'(define pair-and (case-lambda [(Pair (True) (True)) -> (True)]
[(Pair _ _) -> (False)])))
(define definitions (list defn-Bool defn-PairOfBools defn-pair-and))
(define tests
(test-suite
"Sample tests"
(test-equal? "pair-and: True True"
(run-interpreter (append definitions
'((pair-and (Pair (True) (True))))))
'(True))
(test-exn "pair-and: non-exhaustive patterns"
(regexp "Error: non-exhaustive patterns.")
(thunk (run-interpreter (append definitions
'((pair-and (True)))))))
(test-exn "Pair: invalid type argument"
(regexp (format "Error: constructor ~a called incorrectly." 'Pair))
(thunk (run-interpreter (append definitions
'((Pair (True) (Pair (True) (True))))))))
; The following two tests can replace the "unbound name" test in the starter code.
(test-exn "Error: unbound identifier (lowercase)"
(regexp (format "Error: identifier ~a could not be found." 'blah))
(thunk (run-interpreter (append definitions (list 'blah)))))
(test-exn "Error: unbound identifier (capitalized)"
(regexp (format "Error: identifier ~a could not be found." 'Blah))
(thunk (run-interpreter (append definitions (list '(Blah))))))
(test-equal? "Lexical scoping (1)"
(run-interpreter (list defn-Bool
'(define b (True))
'(define f (case-lambda [-> b]))
'(define g (case-lambda [b -> (f)]))
'(g (False))))
; The 'b in (f) should be bound to (True), not (False)
'(True))
(test-exn "Lexical scoping (2)"
(regexp (format "Error: identifier ~a could not be found." 'b))
; In this case, the 'b in (f) should not be bound.
(thunk (run-interpreter (list defn-Bool
'(define f (case-lambda [-> b]))
'(define g (case-lambda [b -> (f)]))
'(g (False))))))))
(require rackunit/text-ui)
(run-tests tests)
| false |
2769f8a10479d436d21715ae79b922e77b76f841 | 24338514b3f72c6e6994c953a3f3d840b060b441 | /cur-lib/cur/stdlib/sigma.rkt | dd1ac2c2d0dde6785bef9b132e7b851c54f0182b | [
"BSD-2-Clause"
]
| permissive | graydon/cur | 4efcaec7648e2bf6d077e9f41cd2b8ce72fa9047 | 246c8e06e245e6e09bbc471c84d69a9654ac2b0e | refs/heads/master | 2020-04-24T20:49:55.940710 | 2018-10-03T23:06:33 | 2018-10-03T23:06:33 | 172,257,266 | 1 | 0 | BSD-2-Clause | 2019-02-23T19:53:23 | 2019-02-23T19:53:23 | null | UTF-8 | Racket | false | false | 2,927 | rkt | sigma.rkt | #lang s-exp "../main.rkt"
(require
(only-in "../main.rkt" [Type typed-Type] [#%app typed-app])
"sugar.rkt")
(provide
Σ0
Σ1
Σ
pair0
pair1
pair
fst0
fst1
fst
snd0
snd1
snd)
(data Σ0 : 2 (-> (A : (Type 0)) (P : (-> A (Type 0))) (Type 0))
(pair0 : (-> (A : (Type 0)) (P : (-> A (Type 0))) (a : A) (b : (P a)) (Σ0 A P))))
(data Σ1 : 2 (-> (A : (Type 1)) (P : (-> A (Type 1))) (Type 1))
(pair1 : (-> (A : (Type 1)) (P : (-> A (Type 1))) (a : A) (b : (P a)) (Σ1 A P))))
;; TODO: As demo, write macro that generates version of Σ for every universe level
(define-syntax (Σ syn)
(syntax-parse syn
#:datum-literals (:)
#:literals (typed-Type)
[(_ (x:id : A) B)
#:with (typed-Type i) (cur-type-infer #'A)
#:with name (format-id syn "Σ~a" (syntax->datum #'i))
#`(name A (λ (x : A) B))]
[(_ A B)
#:with (typed-Type i) (cur-type-infer #'A)
#:with name (format-id syn "Σ~a" (syntax->datum #'i))
#`(name A B)]))
(define-syntax (pair syn)
(syntax-parse syn
#:datum-literals ()
#:literals (typed-Type)
[(pair P a b)
#:with A (cur-type-infer #'a)
#:with (typed-Type i) (cur-type-infer #'A)
#:with name (format-id syn "pair~a" (syntax->datum #'i))
#`(name A P a b)]))
(define (fst0 (A : (Type 0)) (P : (-> A (Type 0))) (p : (Σ A P)))
(new-elim p (λ (x : (Σ A P)) A)
(λ (a : A) (b : (P a)) a)))
(define (snd0 (A : (Type 0)) (P : (-> A (Type 0))) (p : (Σ A P)))
(new-elim p (λ (x : (Σ A P)) (P (fst0 A P x)))
(λ (a : A) (b : (P a)) b)))
(define (fst1 (A : (Type 0)) (P : (-> A (Type 0))) (p : (Σ1 A P)))
(new-elim p (λ (x : (Σ1 A P)) A)
(λ (a : A) (b : (P a)) a)))
(define (snd1 (A : (Type 0)) (P : (-> A (Type 0))) (p : (Σ1 A P)))
(new-elim p (λ (x : (Σ1 A P)) (P (fst1 A P x)))
(λ (a : A) (b : (P a)) b)))
;; TODO: Gosh there is a pattern here... but probably amounts to trying to invent universe templates
;; and I should just add universe polymorphism.
;; TODO: There is also some pattern here for implicit parameters...
(define-syntax (fst syn)
(syntax-parse syn
#:literals (typed-Type typed-app)
[(_ p)
#:with (typed-app (typed-app _ A) P) (cur-type-infer #'p)
#:with (typed-Type i) (cur-type-infer #'A)
#:with name (format-id syn "fst~a" (syntax->datum #'i))
#`(name A P p)]))
(define-syntax (snd syn)
(syntax-parse syn
#:literals (typed-Type typed-app)
[(_ p)
#:with (typed-app (typed-app _ A) P) (cur-type-infer #'p)
#:with (typed-Type i) (cur-type-infer #'A)
#:with name (format-id syn "snd~a" (syntax->datum #'i))
#`(name A P p)]))
#;(define (fst0 (A : (Type 1)) (P : (-> A (Type 1))) (p : (Σ0 A P)))
(match p
#:return A
[(pair1 a _) a]))
#;(define (fst1 (A : (Type 1)) (P : (-> A (Type 1))) (p : (Σ1 A P)))
(match p
#:return A
[(pair1 a _) a]))
| true |
271b489d5586b5ec749874827cbd6d05233294e9 | 12075ec3d7e5bf3905f506a585680d7d756b578b | /hp-path.rkt | 2d3eda5cad6774d051b61e4ca84ac2f5e8b6ace3 | []
| no_license | cosmez/Racket-Stuff | ad5683ff12bf6b6057d9c7f62d8eb04c6a269a6e | fc34f8deffdccf54a662f5700baa441e26d40df9 | refs/heads/master | 2021-01-15T10:50:48.960585 | 2015-01-15T07:08:27 | 2015-01-15T07:08:27 | 25,495,436 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 772 | rkt | hp-path.rkt | #lang racket
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
result
(sum-of-squared-digits (quotient number 10)
(+ result (expt (remainder number 10) 2)))))
(define (happy-path-stream n)
(stream-cons
(sum-of-squared-digits n)
(stream-map sum-of-squared-digits (happy-path-stream n))))
(define (happy-list n)
(for/fold ([so-far '()]) ([s (happy-path-stream n)] #:final (or (= s 1) (memq s so-far)) ) (cons s so-far)))
(define (happy-numbers)
(stream-filter
(λ (happy-path) (= (first happy-path) 1))
(stream-map happy-list (in-naturals))))
(for/list ([i (happy-numbers)] [stop 10]) i)
;((1) (1 10 130 97 49) (1) (1 10) (1 100 68 82) (1 10 13) (1 100 68) (1 10) (1 10 13) (1 10 13 32)) | false |
155b284d5b6a541085e33140391ba2de42509950 | ecfd9ed1908bdc4b099f034b121f6e1fff7d7e22 | /old1/eopl/2/lib.rkt | 8f506e6815024a096275fbe681466cbbc247cdba | [
"MIT"
]
| permissive | sKabYY/palestra | 36d36fc3a03e69b411cba0bc2336c43b3550841c | 06587df3c4d51961d928bd8dd64810c9da56abf4 | refs/heads/master | 2021-12-14T04:45:20.661697 | 2021-11-25T08:29:30 | 2021-11-25T08:29:30 | 12,856,067 | 6 | 3 | null | null | null | null | UTF-8 | Racket | false | false | 336 | rkt | lib.rkt | #lang eopl
(#%provide (all-defined))
(define (displayln o)
(eopl:pretty-print o) (newline))
(define-syntax run-disp
(syntax-rules
()
((_) 'done)
((_ a rest ...)
(begin
(displayln a)
(run-disp rest ...)))))
(define (pair a b) (cons a b))
(define (pair-fst p) (car p))
(define (pair-snd p) (cdr p))
| true |
cc6bc5a5577268657bc6e28419f29eb86bb634ff | 099418d7d7ca2211dfbecd0b879d84c703d1b964 | /whalesong/lang/private/match/parse.rkt | d881cd9b0180f6d85d4718758bb3bff97e770df8 | []
| no_license | vishesh/whalesong | f6edd848fc666993d68983618f9941dd298c1edd | 507dad908d1f15bf8fe25dd98c2b47445df9cac5 | refs/heads/master | 2021-01-12T21:36:54.312489 | 2015-08-19T19:28:25 | 2015-08-19T20:34:55 | 34,933,778 | 3 | 0 | null | 2015-05-02T03:04:54 | 2015-05-02T03:04:54 | null | UTF-8 | Racket | false | false | 7,254 | rkt | parse.rkt | #lang racket/base
(require racket/struct-info
"patterns.rkt"
"parse-helper.rkt"
"parse-quasi.rkt"
(for-template (only-in "runtime.rkt" matchable? mlist? mlist->list)
racket/base))
(provide parse)
(define (ht-pat-transform p)
(syntax-case p ()
[(a b) #'(list a b)]
[x (identifier? #'x) #'x]))
(define orig-insp (variable-reference->module-declaration-inspector
(#%variable-reference)))
;; parse : syntax -> Pat
;; compile stx into a pattern, using the new syntax
(define (parse stx)
(define (rearm new-stx) (syntax-rearm new-stx stx))
(define (rearm+parse new-stx) (parse (rearm new-stx)))
(define disarmed-stx (syntax-disarm stx orig-insp))
(syntax-case* disarmed-stx (not var struct box cons list vector ? and or quote app
regexp pregexp list-rest list-no-order hash-table
quasiquote mcons list* mlist)
(lambda (x y) (eq? (syntax-e x) (syntax-e y)))
[(expander args ...)
(and (identifier? #'expander)
(match-expander? (syntax-local-value #'expander
(lambda () #f))))
(match-expander-transform
rearm+parse #'expander disarmed-stx match-expander-proc
"This expander only works with the legacy match syntax")]
[(var v)
(identifier? #'v)
(Var (rearm #'v))]
[(and p ...)
(And (map rearm+parse (syntax->list #'(p ...))))]
[(or)
(Not (Dummy stx))]
[(or p ps ...)
(let ([ps (map rearm+parse (syntax->list #'(p ps ...)))])
(all-vars ps stx)
(Or ps))]
[(not p ...)
;; nots are conjunctions of negations
(let ([ps (map (compose Not rearm+parse) (syntax->list #'(p ...)))])
(And ps))]
[(regexp r)
(trans-match #'matchable?
(rearm #'(lambda (e) (regexp-match r e)))
(Pred #'values))]
[(regexp r p)
(trans-match #'matchable? #'(lambda (e) (regexp-match r e)) (parse #'p))]
[(pregexp r)
(trans-match #'matchable?
(rearm
#'(lambda (e)
(regexp-match (if (pregexp? r) r (pregexp r)) e)))
(Pred #'values))]
[(pregexp r p)
(trans-match #'matchable?
(rearm
#'(lambda (e)
(regexp-match (if (pregexp? r) r (pregexp r)) e)))
(rearm+parse #'p))]
[(box e) (Box (parse #'e))]
[(vector es ...)
(ormap ddk? (syntax->list #'(es ...)))
(trans-match #'vector?
#'vector->list
(rearm+parse (syntax/loc stx (list es ...))))]
[(vector es ...)
(Vector (map rearm+parse (syntax->list #'(es ...))))]
[(hash-table p ... dd)
(ddk? #'dd)
(trans-match
#'hash?
#'(lambda (e) (hash-map e list))
(with-syntax ([(elems ...)
(map ht-pat-transform (syntax->list #'(p ...)))])
(rearm+parse (syntax/loc stx (list-no-order elems ... dd)))))]
[(hash-table p ...)
(ormap ddk? (syntax->list #'(p ...)))
(raise-syntax-error
'match "dot dot k can only appear at the end of hash-table patterns" stx
(ormap (lambda (e) (and (ddk? e) e)) (syntax->list #'(p ...))))]
[(hash-table p ...)
(trans-match #'hash?
#'(lambda (e) (hash-map e list))
(with-syntax ([(elems ...)
(map ht-pat-transform
(syntax->list #'(p ...)))])
(rearm+parse (syntax/loc stx (list-no-order elems ...)))))]
[(hash-table . _)
(raise-syntax-error 'match "syntax error in hash-table pattern" stx)]
[(list-no-order p ... lp dd)
(ddk? #'dd)
(let* ([count (ddk? #'dd)]
[min (if (number? count) count #f)]
[max (if (number? count) count #f)]
[ps (syntax->list #'(p ...))])
(GSeq (cons (list (rearm+parse #'lp))
(for/list ([p ps]) (list (parse p))))
(cons min (map (lambda _ 1) ps))
(cons max (map (lambda _ 1) ps))
;; vars in lp are lists, vars elsewhere are not
(cons #f (map (lambda _ #t) ps))
(Null (Dummy (syntax/loc stx _)))
#f))]
[(list-no-order p ...)
(ormap ddk? (syntax->list #'(p ...)))
(raise-syntax-error
'match "dot dot k can only appear at the end of unordered match patterns"
stx
(ormap (lambda (e) (and (ddk? e) e)) (syntax->list #'(p ...))))]
[(list-no-order p ...)
(let ([ps (syntax->list #'(p ...))])
(GSeq (for/list ([p ps]) (list (rearm+parse p)))
(map (lambda _ 1) ps)
(map (lambda _ 1) ps)
;; all of these patterns get bound to only one thing
(map (lambda _ #t) ps)
(Null (Dummy (syntax/loc stx _)))
#f))]
[(list) (Null (Dummy (syntax/loc stx _)))]
[(mlist) (Null (Dummy (syntax/loc stx _)))]
[(list ..)
(ddk? #'..)
(raise-syntax-error 'match "incorrect use of ... in pattern" stx #'..)]
[(mlist ..)
(ddk? #'..)
(raise-syntax-error 'match "incorrect use of ... in pattern" stx #'..)]
[(list p .. . rest)
(ddk? #'..)
(dd-parse rearm+parse #'p #'.. (syntax/loc stx (list . rest)) #'list?)]
[(mlist p .. . rest)
(ddk? #'..)
(dd-parse rearm+parse #'p #'.. (syntax/loc stx (list . rest)) #'mlist? #:to-list #'mlist->list #:mutable #t)]
[(list e es ...)
(Pair (rearm+parse #'e) (rearm+parse (syntax/loc stx (list es ...))))]
[(mlist e es ...)
(MPair (rearm+parse #'e) (rearm+parse (syntax/loc stx (mlist es ...))))]
[(list* . rest)
(rearm+parse (syntax/loc stx (list-rest . rest)))]
[(list-rest e)
(rearm+parse #'e)]
[(list-rest p dd . rest)
(ddk? #'dd)
(dd-parse rearm+parse #'p #'dd (syntax/loc stx (list-rest . rest)) #'list?)]
[(list-rest e . es)
(Pair (rearm+parse #'e) (rearm+parse (syntax/loc #'es (list-rest . es))))]
[(cons e1 e2) (Pair (rearm+parse #'e1) (rearm+parse #'e2))]
[(mcons e1 e2) (MPair (rearm+parse #'e1) (rearm+parse #'e2))]
[(struct s pats)
(parse-struct disarmed-stx rearm+parse #'s #'pats)]
[(s . pats)
(and (identifier? #'s) (struct-info? (syntax-local-value #'s (lambda () #f))))
(parse-struct disarmed-stx rearm+parse #'s #'pats)]
[(? p q1 qs ...)
(OrderedAnd
(list (Pred (rearm #'p))
(And (map rearm+parse (syntax->list #'(q1 qs ...))))))]
[(? p)
(Pred (rearm #'p))]
[(app f ps ...) ;; only make a list for more than one pattern
(App #'f (map rearm+parse (syntax->list #'(ps ...))))]
[(quasiquote p)
(parse-quasi #'p rearm+parse)]
[(quasiquote . _)
(raise-syntax-error 'match "illegal use of quasiquote")]
[(quote . _)
(parse-quote disarmed-stx rearm+parse)]
[x
(identifier? #'x)
(parse-id (rearm #'x))]
[v
(or (parse-literal (syntax-e #'v))
(raise-syntax-error 'match "syntax error in pattern" disarmed-stx))]))
;; (trace parse)
| false |
213962ab33f7fc12ef0e5dd711263fc68ad41fdd | ca308b30ee025012b997bb8a6106eca1568e4403 | /analysis-trees/primes-five.rkt | f53d5ad33868cb834f1c0b1e3c5e3a069ca31bb6 | [
"MIT"
]
| permissive | v-nys/cclp | 178d603c6980922d0fe3f13ee283da61809e0a99 | c20b33972fdc3b1f0509dd6b9e4ece4f5f3192b3 | refs/heads/master | 2022-02-18T07:12:28.750665 | 2017-10-30T06:55:45 | 2017-10-30T06:55:45 | 64,598,287 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 653 | rkt | primes-five.rkt | #lang cclp/at
(.1.*primes(g1,a1)*
(.2.*integers(g2,a6)*,sift(a6,a5),length(a5,g1) [integers(g1,a1) < sift(a1,a2), integers(g1,a1) < length(a1,g1)]
{a4/g1, a1/a5} primes(N,Primes) :- integers(2,I),sift(I,Primes),length(Primes,N).
(.3.*sift([],a5)*,length(a5,g1) [sift([],a1) < length(a1,g1)]
{a7/g2, a6/[]} integers(N,[]).
(.4.*length([],g1)*
{a5/[]} sift([],[]).
(.□
{g1/g2} length([],0).)))
(.5.*plus(g2,g3,a9)*,integers(a9,a8),sift([g2|a8],a5),length(a5,g1)
{a7/g2, a6/[g2|a8]} integers(N,[N|I]) :- plus(N,1,M),integers(M,I).
(.integers(g6,a8),sift([g4|a8],a5),length(a5,g1)
{g2/g4, g3/g5, a9/g6} plus(g1,g2,a1) -> {a1/g3})))) | false |
5bffe9b029cadbda93df99fad7a1442c16a7b72f | fc6465100ab657aa1e31af6a4ab77a3284c28ff0 | /results/all/let-poly-4-grammar-extra.rktd | 1d08023e0eb3193f488ac68054a2da2e0e984d8e | []
| no_license | maxsnew/Redex-Enum-Paper | f5ba64a34904beb6ed9be39ff9a5e1e5413c059b | d77ec860d138cb023628cc41f532dd4eb142f15b | refs/heads/master | 2020-05-21T20:07:31.382540 | 2017-09-04T14:42:13 | 2017-09-04T14:42:13 | 17,602,325 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 14,525 | rktd | let-poly-4-grammar-extra.rktd | (start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(start 2015-06-30T21:13:49 (#:model "let-poly-4" #:type grammar))
(counterexample 2015-06-30T21:46:04 (#:model "let-poly-4" #:type grammar #:counterexample (let ((s 1)) ((λ E (E E)) cons)) #:iterations 866238 #:time 1933777))
(new-average 2015-06-30T21:46:04 (#:model "let-poly-4" #:type grammar #:average 1933776.0 #:stderr +nan.0))
(counterexample 2015-06-30T21:54:01 (#:model "let-poly-4" #:type grammar #:counterexample ((λ G (G G)) +) #:iterations 1142654 #:time 2413345))
(new-average 2015-06-30T21:54:01 (#:model "let-poly-4" #:type grammar #:average 2413345.0 #:stderr +nan.0))
(counterexample 2015-06-30T22:08:17 (#:model "let-poly-4" #:type grammar #:counterexample (let ((V (let ((Ec (λ v +))) new))) (λ n (λ N (V n)))) #:iterations 1475090 #:time 3268552))
(new-average 2015-06-30T22:08:17 (#:model "let-poly-4" #:type grammar #:average 3268551.0 #:stderr +nan.0))
(counterexample 2015-06-30T22:31:07 (#:model "let-poly-4" #:type grammar #:counterexample (let ((t (let ((Qc +)) +))) (t t)) #:iterations 2152172 #:time 4639890))
(new-average 2015-06-30T22:31:07 (#:model "let-poly-4" #:type grammar #:average 4639889.0 #:stderr +nan.0))
(counterexample 2015-06-30T22:52:57 (#:model "let-poly-4" #:type grammar #:counterexample (let ((s (let ((GBD set)) new))) ((let ((dm cons)) s) (λ U s))) #:iterations 1216123 #:time 2680506))
(new-average 2015-06-30T22:52:57 (#:model "let-poly-4" #:type grammar #:average 2974528.5 #:stderr 294022.5))
(counterexample 2015-07-01T00:17:12 (#:model "let-poly-4" #:type grammar #:counterexample ((λ m (λ J (m J))) hd) #:iterations 2280113 #:time 5055805))
(new-average 2015-07-01T00:17:12 (#:model "let-poly-4" #:type grammar #:average 3668287.3333333335 #:stderr 714225.2648827105))
(counterexample 2015-07-01T00:53:15 (#:model "let-poly-4" #:type grammar #:counterexample (let ((wd +)) ((λ G (G G)) hd)) #:iterations 5758175 #:time 13174231))
(new-average 2015-07-01T00:53:15 (#:model "let-poly-4" #:type grammar #:average 13174230.0 #:stderr +nan.0))
(counterexample 2015-07-01T02:22:04 (#:model "let-poly-4" #:type grammar #:counterexample (let ((i (let ((t +)) set))) (let ((TCs set)) (i i))) #:iterations 7225461 #:time 16089445))
(new-average 2015-07-01T02:22:04 (#:model "let-poly-4" #:type grammar #:average 9251395.0 #:stderr 6838050.0))
(counterexample 2015-07-01T03:38:42 (#:model "let-poly-4" #:type grammar #:counterexample ((let ((i 0)) (λ D (D D))) hd) #:iterations 10877593 #:time 23106567))
(new-average 2015-07-01T03:38:42 (#:model "let-poly-4" #:type grammar #:average 23106566.0 #:stderr +nan.0))
(counterexample 2015-07-01T03:43:20 (#:model "let-poly-4" #:type grammar #:counterexample ((λ a (let ((I tl)) (a a))) set) #:iterations 10513282 #:time 23381351))
(new-average 2015-07-01T03:43:20 (#:model "let-poly-4" #:type grammar #:average 23381350.0 #:stderr +nan.0))
(counterexample 2015-07-01T04:16:45 (#:model "let-poly-4" #:type grammar #:counterexample (let ((e (let ((r hd)) cons))) (λ H (e H))) #:iterations 3297770 #:time 6883398))
(new-average 2015-07-01T04:16:45 (#:model "let-poly-4" #:type grammar #:average 8462062.666666666 #:stderr 4026084.3011473874))
(counterexample 2015-07-01T04:25:04 (#:model "let-poly-4" #:type grammar #:counterexample ((let ((Y (let ((E hd)) set))) (λ m (m m))) +) #:iterations 6954215 #:time 14877932))
(new-average 2015-07-01T04:25:04 (#:model "let-poly-4" #:type grammar #:average 6470698.5 #:stderr 2847554.6020324905))
(counterexample 2015-07-01T04:35:52 (#:model "let-poly-4" #:type grammar #:counterexample ((λ j (let ((x (λ G (j j)))) +)) hd) #:iterations 1497459 #:time 3430925))
(new-average 2015-07-01T04:35:52 (#:model "let-poly-4" #:type grammar #:average 13268745.5 #:stderr 9837820.5))
(counterexample 2015-07-01T04:47:32 (#:model "let-poly-4" #:type grammar #:counterexample (let ((s (let ((l (λ l (λ L 1)))) +))) ((let ((FO tl)) s) s)) #:iterations 6537103 #:time 14064822))
(new-average 2015-07-01T04:47:32 (#:model "let-poly-4" #:type grammar #:average 13619526.0 #:stderr 445295.99999999994))
(counterexample 2015-07-01T06:11:07 (#:model "let-poly-4" #:type grammar #:counterexample ((λ P (P P)) hd) #:iterations 13533181 #:time 30313262))
(new-average 2015-07-01T06:11:07 (#:model "let-poly-4" #:type grammar #:average 16123519.0 #:stderr 14189742.999999998))
(counterexample 2015-07-01T07:06:26 (#:model "let-poly-4" #:type grammar #:counterexample ((λ L (λ v (λ o (L o)))) hd) #:iterations 5442548 #:time 12192209))
(new-average 2015-07-01T07:06:26 (#:model "let-poly-4" #:type grammar #:average 17786779.5 #:stderr 5594570.499999999))
(counterexample 2015-07-01T07:20:51 (#:model "let-poly-4" #:type grammar #:counterexample ((λ j (j j)) +) #:iterations 4316014 #:time 9901033))
(new-average 2015-07-01T07:20:51 (#:model "let-poly-4" #:type grammar #:average 12146174.666666666 #:stderr 5789738.278994781))
(counterexample 2015-07-01T08:31:32 (#:model "let-poly-4" #:type grammar #:counterexample (((λ T (T T)) get) new) #:iterations 17132531 #:time 36042249))
(new-average 2015-07-01T08:31:32 (#:model "let-poly-4" #:type grammar #:average 20341069.0 #:stderr 15701179.999999998))
(counterexample 2015-07-01T09:05:04 (#:model "let-poly-4" #:type grammar #:counterexample ((λ W (λ p (hd W))) nil) #:iterations 19088641 #:time 42691570))
(new-average 2015-07-01T09:05:04 (#:model "let-poly-4" #:type grammar #:average 42691569.0 #:stderr +nan.0))
(counterexample 2015-07-01T09:25:01 (#:model "let-poly-4" #:type grammar #:counterexample ((λ U (U U)) get) #:iterations 1595320 #:time 3211323))
(new-average 2015-07-01T09:25:01 (#:model "let-poly-4" #:type grammar #:average 14631153.666666668 #:stderr 10713487.647725575))
(counterexample 2015-07-01T10:10:07 (#:model "let-poly-4" #:type grammar #:counterexample ((λ s (λ p (s p))) get) #:iterations 8555766 #:time 19365094))
(new-average 2015-07-01T10:10:07 (#:model "let-poly-4" #:type grammar #:average 15534715.333333334 #:stderr 1932368.070111328))
(counterexample 2015-07-01T10:52:27 (#:model "let-poly-4" #:type grammar #:counterexample ((λ l (λ a (l a))) hd) #:iterations 10691265 #:time 23747251))
(new-average 2015-07-01T10:52:27 (#:model "let-poly-4" #:type grammar #:average 12283359.75 #:stderr 4765185.075006485))
(counterexample 2015-07-01T11:20:07 (#:model "let-poly-4" #:type grammar #:counterexample ((let ((bOmRF +)) (λ q (q q))) +) #:iterations 694403 #:time 1659056))
(new-average 2015-07-01T11:20:07 (#:model "let-poly-4" #:type grammar #:average 10158499.0 #:stderr 4259017.079835357))
(counterexample 2015-07-01T12:10:37 (#:model "let-poly-4" #:type grammar #:counterexample ((λ c (c c)) new) #:iterations 8183414 #:time 17394895))
(new-average 2015-07-01T12:10:37 (#:model "let-poly-4" #:type grammar #:average 13458354.75 #:stderr 4299110.517389079))
(counterexample 2015-07-01T13:06:36 (#:model "let-poly-4" #:type grammar #:counterexample (let ((c (let ((As +)) tl))) (λ Q (λ s (c c)))) #:iterations 11266624 #:time 24943100))
(new-average 2015-07-01T13:06:36 (#:model "let-poly-4" #:type grammar #:average 19063379.333333332 #:stderr 8703967.347222937))
(counterexample 2015-07-01T13:08:58 (#:model "let-poly-4" #:type grammar #:counterexample ((λ T (new (T T))) (let ((j 0)) +)) #:iterations 3005505 #:time 6532943))
(new-average 2015-07-01T13:08:58 (#:model "let-poly-4" #:type grammar #:average 9554239.666666666 #:stderr 3529581.703187123))
(counterexample 2015-07-01T13:10:11 (#:model "let-poly-4" #:type grammar #:counterexample ((λ p (λ DX (λ N (p p)))) get) #:iterations 91624 #:time 215852))
(new-average 2015-07-01T13:10:11 (#:model "let-poly-4" #:type grammar #:average 14351497.5 #:stderr 7751216.304687817))
(counterexample 2015-07-01T13:35:13 (#:model "let-poly-4" #:type grammar #:counterexample (let ((hr cons)) ((λ N (N N)) get)) #:iterations 10691227 #:time 23336439))
(new-average 2015-07-01T13:35:13 (#:model "let-poly-4" #:type grammar #:average 19636666.0 #:stderr 3722251.0782283796))
(counterexample 2015-07-01T14:07:55 (#:model "let-poly-4" #:type grammar #:counterexample ((λ J (let ((VEz +)) (J J))) +) #:iterations 3124415 #:time 7039039))
(new-average 2015-07-01T14:07:55 (#:model "let-poly-4" #:type grammar #:average 12174491.6 #:stderr 3568993.6021745903))
(counterexample 2015-07-01T14:09:02 (#:model "let-poly-4" #:type grammar #:counterexample ((λ M (set (M M))) hd) #:iterations 1557239 #:time 3531315))
(new-average 2015-07-01T14:09:02 (#:model "let-poly-4" #:type grammar #:average 12187461.0 #:stderr 6382152.18359506))
(counterexample 2015-07-01T14:10:32 (#:model "let-poly-4" #:type grammar #:counterexample (let ((B ((λ f (f f)) +))) +) #:iterations 15758667 #:time 35142581))
(new-average 2015-07-01T14:10:32 (#:model "let-poly-4" #:type grammar #:average 12205075.0 #:stderr 6143957.533274957))
(counterexample 2015-07-01T14:35:43 (#:model "let-poly-4" #:type grammar #:counterexample ((λ N (let ((Iu tl)) (N N))) set) #:iterations 648034 #:time 1510221))
(new-average 2015-07-01T14:35:43 (#:model "let-poly-4" #:type grammar #:average 10422599.333333334 #:stderr 5323785.834915743))
(counterexample 2015-07-01T16:03:08 (#:model "let-poly-4" #:type grammar #:counterexample ((λ Z (λ e (Z Z))) (let ((Q hd)) set)) #:iterations 11613581 #:time 25093323))
(new-average 2015-07-01T16:03:08 (#:model "let-poly-4" #:type grammar #:average 33892446.0 #:stderr 8799123.0))
(counterexample 2015-07-01T16:19:49 (#:model "let-poly-4" #:type grammar #:counterexample ((λ k (let ((n (λ f +))) (k k))) hd) #:iterations 5320361 #:time 11455632))
(new-average 2015-07-01T16:19:49 (#:model "let-poly-4" #:type grammar #:average 9825867.142857142 #:stderr 2995382.2889364175))
(counterexample 2015-07-01T16:54:03 (#:model "let-poly-4" #:type grammar #:counterexample ((λ f tl) ((λ O (O O)) tl)) #:iterations 1379158 #:time 3056264))
(new-average 2015-07-01T16:54:03 (#:model "let-poly-4" #:type grammar #:average 23613718.333333336 #:stderr 11465619.519613486))
(counterexample 2015-07-01T17:41:47 (#:model "let-poly-4" #:type grammar #:counterexample (let ((r (let ((P (λ Zpf 0))) get))) (let ((d 1)) (r r))) #:iterations 5136247 #:time 11168769))
(new-average 2015-07-01T17:41:47 (#:model "let-poly-4" #:type grammar #:average 10529195.0 #:stderr 4500682.750321846))
(counterexample 2015-07-01T18:20:12 (#:model "let-poly-4" #:type grammar #:counterexample (let ((Lq cons)) ((λ Y (Y Y)) set)) #:iterations 2331448 #:time 5170443))
(new-average 2015-07-01T18:20:12 (#:model "let-poly-4" #:type grammar #:average 19002899.5 #:stderr 9326835.787022963))
(counterexample 2015-07-01T18:25:15 (#:model "let-poly-4" #:type grammar #:counterexample ((λ b (b b)) hd) #:iterations 3484690 #:time 7528459))
(new-average 2015-07-01T18:25:15 (#:model "let-poly-4" #:type grammar #:average 9538691.125 #:stderr 2609924.588544229))
(counterexample 2015-07-01T18:31:16 (#:model "let-poly-4" #:type grammar #:counterexample (let ((U (let ((oB ((λ o (o o)) +))) get))) hd) #:iterations 283359 #:time 664586))
(new-average 2015-07-01T18:31:16 (#:model "let-poly-4" #:type grammar #:average 15335236.8 #:stderr 8102201.5008160975))
(counterexample 2015-07-01T19:18:08 (#:model "let-poly-4" #:type grammar #:counterexample (let ((J (let ((A 0)) nil))) ((cons J) J)) #:iterations 2732654 #:time 5785459))
(new-average 2015-07-01T19:18:08 (#:model "let-poly-4" #:type grammar #:average 9936228.0 #:stderr 3942552.3176455707))
(counterexample 2015-07-01T19:24:49 (#:model "let-poly-4" #:type grammar #:counterexample ((λ G (λ In (G G))) hd) #:iterations 8578318 #:time 19021872))
(new-average 2015-07-01T19:24:49 (#:model "let-poly-4" #:type grammar #:average 13315721.666666666 #:stderr 3129571.262431876))
(counterexample 2015-07-01T19:44:53 (#:model "let-poly-4" #:type grammar #:counterexample (((λ Y (λ J (Y Y))) set) 3) #:iterations 10248734 #:time 22191287))
(new-average 2015-07-01T19:44:53 (#:model "let-poly-4" #:type grammar #:average 20275321.25 #:stderr 2708404.8945899373))
(counterexample 2015-07-01T20:39:44 (#:model "let-poly-4" #:type grammar #:counterexample ((λ j (cons (j j))) cons) #:iterations 1984759 #:time 4498307))
(new-average 2015-07-01T20:39:44 (#:model "let-poly-4" #:type grammar #:average 12056091.0 #:stderr 2929596.933466811))
(counterexample 2015-07-01T20:58:06 (#:model "let-poly-4" #:type grammar #:counterexample ((let ((N cons)) (λ K (K K))) new) #:iterations 17510933 #:time 38895922))
(new-average 2015-07-01T20:58:06 (#:model "let-poly-4" #:type grammar #:average 21375017.0 #:stderr 5998011.89869296))
(finished 2015-07-01T21:13:05 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 38787352 #:num-counterexamples 4 #:rate-terms/s 448.92767998926297 #:attempts/cexp 9696838.0))
(finished 2015-07-01T21:13:09 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 38891628 #:num-counterexamples 5 #:rate-terms/s 450.1345781234424 #:attempts/cexp 7778325.6))
(finished 2015-07-01T21:13:10 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 39287815 #:num-counterexamples 4 #:rate-terms/s 454.72007575555466 #:attempts/cexp 9821953.75))
(finished 2015-07-01T21:13:11 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 39427615 #:num-counterexamples 7 #:rate-terms/s 456.33813129238274 #:attempts/cexp 5632516.428571428))
(finished 2015-07-01T21:13:16 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 39318053 #:num-counterexamples 8 #:rate-terms/s 455.07005260335586 #:attempts/cexp 4914756.625))
(finished 2015-07-01T21:13:17 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 39102720 #:num-counterexamples 5 #:rate-terms/s 452.5777725396091 #:attempts/cexp 7820544.0))
(finished 2015-07-01T21:13:22 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 39610433 #:num-counterexamples 8 #:rate-terms/s 458.4540803419667 #:attempts/cexp 4951304.125))
(finished 2015-07-01T21:13:22 (#:model "let-poly-4" #:type grammar #:time-ms 86400001 #:attempts 40129428 #:num-counterexamples 3 #:rate-terms/s 464.4609668465166 #:attempts/cexp 13376476.0))
| false |
4ace42b577e0f9fdaf955a801a48a133493f0511 | 9101470cfbfc3c91e240e2a963fb3760744d9d25 | /guide/ch13/13.0.rkt | cda35c00a96ff8cc88c309f096993126926a6b5d | [
"MIT"
]
| permissive | sylsaint/racket | 49e2fc01ccec8538d0d9b9d35f73b4b6772bfd93 | 5c11113e5247502e6e0ea877f2538dce508c36f2 | refs/heads/master | 2020-12-21T22:17:32.873776 | 2016-12-19T09:32:14 | 2016-12-19T09:43:25 | 59,442,778 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 983 | rkt | 13.0.rkt | #lang racket
; (class superclass-expr decl-or-expr ...)
; instead of a method-like constructor, a class has initialization expressions interleaved with field and method declarations
; By convention, class names end with %. The built-in root class is object%
; class with public method `get-size`, `grow` and `eat`
(define fish% (class object%
(init size) ; initialization argument
(define current-size size) ; field
(super-new) ; super class initialization
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))))
(define charlie (new fish% [size 10]))
; super-new must be used, anyway, because a class must always invoke its superclass’s initialization.
; Initialization arguments, field declarations, and expressions such as (super-new) can appear in any order within a class
(provide fish%) | false |
d317a921c23dc82531ba8dd4edcd58f83d033267 | ea6bb0279a8f37f9efb145104ff5df8fa2bae289 | /Programming Language/HW4/HW4.rkt | b6ca0ba36a99c49d52d81394ab904413c2ab6ef2 | []
| no_license | ILAL1/Portfolio | e008d3dd71bfdaf2e415d0b717aae513abb3597f | dd42d2816d7f44733bc8bd9120294912af1c5185 | refs/heads/master | 2020-12-30T15:41:44.598824 | 2017-05-13T12:56:55 | 2017-05-13T12:56:55 | 91,162,599 | 0 | 3 | null | null | null | null | UTF-8 | Racket | false | false | 20,013 | rkt | HW4.rkt | #lang plai
(require (for-syntax racket/base) racket/match racket/list racket/string
(only-in mzlib/string read-from-string-all))
;; build a regexp that matches restricted character expressions, can use only
;; {}s for lists, and limited strings that use '...' (normal racket escapes
;; like \n, and '' for a single ')
(define good-char "(?:[ \t\r\na-zA-Z0-9_{}!?*/<=>:+-]|[.][.][.]|[@$%&~^])")
;; this would make it awkward for students to use \" for strings
;; (define good-string "\"[^\"\\]*(?:\\\\.[^\"\\]*)*\"")
(define good-string "[^\"\\']*(?:''[^\"\\']*)*")
(define expr-re
(regexp (string-append "^"
good-char"*"
"(?:'"good-string"'"good-char"*)*"
"$")))
(define string-re
(regexp (string-append "'("good-string")'")))
(define (string->sexpr str)
(unless (string? str)
(error 'string->sexpr "expects argument of type <string>"))
(unless (regexp-match expr-re str)
(error 'string->sexpr "syntax error (bad contents)"))
(let ([sexprs (read-from-string-all
(regexp-replace*
"''" (regexp-replace* string-re str "\"\\1\"") "'"))])
(if (= 1 (length sexprs))
(car sexprs)
(error 'string->sexpr "bad syntax (multiple expressions)"))))
(test/exn (string->sexpr 1) "expects argument of type <string>")
(test/exn (string->sexpr ".") "syntax error (bad contents)")
(test/exn (string->sexpr "{} {}") "bad syntax (multiple expressions)")
;FunDef abstract syntax trees
(define-type FunDef
(fundef (fun-name symbol?) (arg-name (listof symbol?)) (body FnWAE?)))
;FnWAE-Value abstract syntax trees
(define-type FnWAE-Value
(numV (n number?))
(recV (r rec?)))
;RecPair abstract syntax trees
(define-type RecPair
(recPair (name symbol?)(expr FnWAE?)))
;FnWAE abstract syntax trees
(define-type FnWAE
(num (n number?))
(add (lhs FnWAE?) (rhs FnWAE?))
(sub (lhs FnWAE?) (rhs FnWAE?))
(with (name symbol?) (named-expr FnWAE?) (body FnWAE?))
(id (name symbol?))
(rec (arg (listof RecPair?)))
(get (r FnWAE?) (name symbol?))
(app (ftn symbol?) (arg (listof FnWAE?))))
;uniq?: list-of-symbol -> bool
;to check list-of-volume has duplicates or not
;If it is, then return false
;If it's not, return true
(define (uniq? x)
(cond ((not (list? x)) (error 'uniq? "bad syntax: ~a" x))
((not (listof symbol?)) (error 'uniq? "bad syntax: ~a" x))
((empty? x) #t)
(else (cond ((andmap (lambda (list) (not (symbol=? (first x) list))) (rest x)) (uniq? (rest x)))
(else #f)))))
;parse: sexp -> FnWAE
;to convert s-expressions into FnWAEs
(define (parse sexp)
(match sexp
[(? number?) (num sexp)]
[(list '+ l r) (add (parse l) (parse r))]
[(list '- l r) (sub (parse l) (parse r))]
[(list 'with (list x i) b) (with x (parse i) (parse b))]
[(? symbol?) (id sexp)]
[(list 'rec a ...) (cond ((not (andmap (lambda (e) (list? e)) a)) (error 'parse "bad syntax: ~a" sexp))
((not (andmap (lambda (e) (= (length e) 2)) a)) (error 'parse "bad syntax: ~a" sexp))
(else (unless (uniq? (map (lambda (e) (first e)) a)) (error "duplicate fields"))
(rec (map (lambda (e) (recPair (first e) (parse (second e)))) a))))]
[(list 'get r x) (get (parse r) x)]
[(list '+ a ...) (error 'parse "bad syntax: ~a" sexp)]
[(list '- a ...) (error 'parse "bad syntax: ~a" sexp)]
[(list 'with a ...) (error 'parse "bad syntax: ~a" sexp)]
[(list 'get a ...) (error 'parse "bad syntax: ~a" sexp)]
[(list f x ...) (app f (map parse x))]
[else (error 'parse "bad syntax: ~a" sexp)]))
;parse-defn: sexp -> FunDef
;to convert s-expressions into FunDefs
(define (parse-defn sexp)
(match sexp
[(list 'deffun (list f x ...) body)
(unless (uniq? x)
(error 'parse-defn "bad syntax"))
(fundef f x (parse body))]))
;parse-str: str -> FnWAE
;parses a string containing a FnWAE expression to a FnWAE AST
(define (parse-str str)
(parse (string->sexpr str)))
;parse-defn-str: str -> FunDef
;parses a string containing a FunDef expression to a FunDef AST
(define (parse-defn-str str)
(parse-defn (string->sexpr str)))
;helper-with: symbol list-of-symbol list-of-number -> number
;to get rid of first argument from second argumet and corresponding number from
;third argument resulting expression
(define (helper-with x xs vals)
(cond ((symbol=? x (first xs)) (rest vals))
(else (append (list (first vals)) (helper-with x xs (rest vals))))))
;helper-id: symbol list-of-symbol list-of-number -> number
;to get corresponding number value in third argument to symbol in second argument
;which is same with first argument
(define (helper-id s xs vals)
(cond ((symbol=? s (first xs)) (first vals))
(else (helper-id s (rest xs) (rest vals)))))
;FnWAE-Value: FnWAE-Value -> FnWAE
;to convert FnWAE-Value to FnWAE
(define (FnWAE-Value->FnWAE fnwae-value)
(cond ((numV? fnwae-value) (num (numV-n fnwae-value)))
((recV? fnwae-value) (recV-r fnwae-value))))
;subst: FnWAE list-of-symbol list-of-FnWAE-Value -> FnWAE
;; substitutes the second argument with the third argument in the
;; first argument, as per the rules of substitution; the resulting
;; expression contains no free instances of the second argument
(define (subst fnwae xs vals)
(type-case FnWAE fnwae
(num (n) fnwae)
(add (l r) (add (subst l xs vals) (subst r xs vals)))
(sub (l r) (sub (subst l xs vals) (subst r xs vals)))
(with (y i b) (with y
(subst i xs vals)
(if (member y xs) (subst b (remove y xs) (helper-with y xs vals))
(subst b xs vals))))
(id (s) (if (not (member s xs)) fnwae
(FnWAE-Value->FnWAE (helper-id s xs vals))))
(rec (a) (rec (map (lambda (e) (recPair (recPair-name e) (subst (recPair-expr e) xs vals))) a)))
(get (r x) (get (subst r xs vals) x))
(app (f a) (app f (map (lambda (e) (subst e xs vals)) a)))))
;lookup-fundef : symbol list-of-FunDef -> FunDef
;to get FunDef in second argument which is same with first argument
(define (lookup-fundef name fundefs)
(cond
((empty? fundefs) (error 'lookup-fundef "unknown function"))
(else (if (symbol=? name (fundef-fun-name (first fundefs))) (first fundefs)
(lookup-fundef name (rest fundefs))))))
;num-op: (number number -> number) -> ((FnWAE FnWAE) -> FnWAE)
;take number opertator and make it into FnWAE operator
(define (num-op op)
(lambda (x y)
(numV (op (numV-n x) (numV-n y)))))
;num+:FnWAE FnWAE -> FnWAE
;add operator for FnWAE
(define num+ (num-op +))
;num+:FnWAE FnWAE -> FnWAE
;sub operator for FnWAE
(define num- (num-op -))
;interp : FnWAE list-of-FunDef -> FnWAE-Value
;evaluates FnWAE expressions by reducing them to FnWAE-Value
(define (interp fnwae fundefs)
(type-case FnWAE fnwae
(num (n) (numV n))
(add (l r) (num+ (interp l fundefs) (interp r fundefs)))
(sub (l r) (num- (interp l fundefs) (interp r fundefs)))
(with (x i b) (interp (subst b (list x) (list (interp i fundefs))) fundefs))
(rec (a) (recV (rec (map (lambda (e) (recPair (recPair-name e) (FnWAE-Value->FnWAE (interp (recPair-expr e) fundefs)))) a))))
(get (r x) (local
((define recv (interp r fundefs)))
(cond ((empty? (rec-arg (recV-r recv))) (error "no such field"))
((symbol=? x (recPair-name (first (rec-arg (recV-r recv))))) (interp (recPair-expr (first (rec-arg (recV-r recv)))) fundefs))
(else (interp (get (rec (rest (rec-arg (recV-r recv)))) x) fundefs)))))
(id (s) (error 'interp "free variables"))
(app (f a) (local
((define a-fundef (lookup-fundef f fundefs)))
(cond ((= (length a) (length (fundef-arg-name a-fundef))) (interp (subst (fundef-body a-fundef)
(fundef-arg-name a-fundef)
(map (lambda (e) (interp e fundefs)) a)) fundefs))
(else (error "wrong arity")))))))
;interp-expr : FnWAE-Value -> number or symbol
;evaluates FnWAE-Value expressions by reducing them to number or symbol
(define (interp-expr fnwae-value)
(type-case FnWAE-Value fnwae-value
(numV (n) n)
(recV (r) 'record)))
;run : string list -> number or symbol
;evaluate a FnWAE program contained in a string and function define list
(define (run str fundefs)
(interp-expr (interp (parse-str str) fundefs)))
;my tests
(test (run "{f 1 2}" (list (parse-defn '{deffun {f x y} {+ x y}}))) 3)
(test (run "{+ {f} {f}}" (list (parse-defn '{deffun {f} 5}))) 10)
(test/exn (run "{f 1}" (list (parse-defn '{deffun {f x y} {+ x y}})))
"wrong arity")
(test (run "{good 1 2}" (list (parse-defn '{deffun {good x y} {+ x y}}))) 3)
(test (run "{* 1 2}" (list (parse-defn '{deffun {* x y} {+ x y}}))) 3)
(test/exn (run "f" (list (parse-defn '{deffun {* x y} {+ x y}}))) "interp: free variables")
(test (run "{^ 1 2}" (list (parse-defn '{deffun {^ x y} {+ x y}}))) 3)
(test (run "{= 1 2}" (list (parse-defn '{deffun {= x y} {+ x y}}))) 3)
(test (run "{@ 1 2}" (list (parse-defn '{deffun {@ x y} {+ x y}}))) 3)
(test (run "{$ 1 2}" (list (parse-defn '{deffun {$ x y} {+ x y}}))) 3)
(test (run "{% 1 2}" (list (parse-defn '{deffun {% x y} {+ x y}}))) 3)
(test (run "{~ 1 2}" (list (parse-defn '{deffun {~ x y} {+ x y}}))) 3)
(test (run "{~12 1 2}" (list (parse-defn '{deffun {~12 x y} {+ x y}}))) 3)
(test (run "{~12b 1 2}" (list (parse-defn '{deffun {~12b x y} {+ x y}}))) 3)
(test (run "{- 1 2}" (list (parse-defn '{deffun {- x y} {+ x y}}))) -1)
(test (run "{+ 1 2}" (list (parse-defn '{deffun {+ x y} {- x y}}))) 3)
(test/exn (run "{with 1 2}" (list (parse-defn '{deffun {with x y} {+ x y}}))) "parse: bad syntax: (with 1 2)")
(test/exn (run "{rec 1 2}" (list (parse-defn '{deffun {rec x y} {+ x y}}))) "parse: bad syntax: (rec 1 2)")
(test/exn (run "{rec {x 1} {y 1 2}}" empty) "parse: bad syntax: (rec (x 1) (y 1 2))")
(test/exn (run "{with x}" (list (parse-defn '{deffun {with x} 1}))) "parse: bad syntax: (with x)")
(test/exn (run "{+ 1 2 3}" (list (parse-defn '{deffun {+ x y z} {+ {+ x y} z}}))) "parse: bad syntax: (+ 1 2 3)")
(test/exn (run "{- 1 2 3}" (list (parse-defn '{deffun {- x y z} {- {- x y} z}}))) "parse: bad syntax: (- 1 2 3)")
(test/exn (run "{ab 1 2}" (list (parse-defn '{deffun {abc x y} {- x y}}))) "lookup-fundef: unknown function")
(test (run "{rec {a 1} {b 2}}" empty) 'record)
(test (run "{rec {a 1} {b {+ 1 1}}}" empty) 'record)
(test/exn (run "{rec {a 1} {b x}}" empty) "interp: free variables")
(test (run "{rec {a {with {x 1} {+ 1 x}}} {b {+ 1 1}}}" empty) 'record)
(test (run "{rec {a {with {x 1} {+ 1 x}}} {b {+ 1 {with {x 1} {+ 1 x}}}}}" empty) 'record)
(test (run "{rec {a {rec {b 1}}}}" empty) 'record)
(test (run "{rec {a {get {rec {b 1}} b}}}" empty) 'record)
(test/exn (run "{rec {b 1} {b 2}}" empty) "duplicate fields")
(test/exn (run "{get {rec {b 1} {b 2}} b}" empty) "duplicate fields")
(test/exn (run "{get {rec {a 1} {b 2}} c}" empty) "no such field")
(test (run "{get {get {rec {a {rec {b 1}}}} a} b}" empty) 1)
(test (run "{get {rec {a 1} {b {get {rec {c 2}} c}}} b}" empty) 2)
(test (run "{get {rec {a 1} {b {get {rec {c {with {x {get {rec {d 2}} d}} {+ 1 x}}}} c}}} b}" empty) 3)
(test (run "{get {rec {a 1} {b {get {rec {a {with {a {get {rec {a 2}} a}} {+ 1 a}}}} a}}} b}" empty) 3)
(test (run "{+ {get {rec {a 1} {b 2}} a} {with {x {get {rec {a {+ 1 1}}} a}} {- x x}}}" empty) 1)
(test (run "{f 1}" (list (parse-defn '{deffun {f x} x}))) 1)
(test/exn (run "{f x}" (list (parse-defn '{deffun {f x} x}))) "interp: free variables")
(test (run "{f 2}" (list (parse-defn '{deffun {f x} 1}))) 1)
(test (run "{f}" (list (parse-defn '{deffun {f} 1}))) 1)
(test (run "{g {f}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} 2}))) 2)
(test/exn (run "{g {f}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} {rec 1}}))) "parse: bad syntax: (rec 1)")
(test/exn (run "{g {f}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {h x} 2}))) "lookup-fundef: unknown function")
(test (run "{h {f} {g 1}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} 3}))) 3)
(test (run "{h {f} {g 1}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} {f}}))) 1)
(test (run "{h {f} {g 1}}" (list (parse-defn '{deffun {f} {g 1}})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} {f}}))) 2)
(test (run "{with {h {h {f} {g 1}}} {h h h}}" (list (parse-defn '{deffun {f} {g 1}})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} {f}}))) 2)
(test/exn (run "{+ {h {f} {g 1}} {h 1}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} 3}))) "wrong arity")
(test/exn (run "{+ {h {f} {g 1}} {h 1}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} 3}))) "wrong arity")
(test (run "{+ {h {f} {g 1}} {h 1 2}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} 2})(parse-defn '{deffun {h x y} 3}))) 6)
(test (run "{+ {g {h {f} {g 1}}} {h 1 2}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} {with {x {get{rec {a 1} {b 2}} a}} {get {rec {x x}} x}}})(parse-defn '{deffun {h x y} 3}))) 4)
(test (run "{+ {g {h {with {h {get {rec {h 1}} h}} {h h h}} {g 1}}} {h 1 2}}" (list (parse-defn '{deffun {f} 1})(parse-defn '{deffun {g x} {with {x {get{rec {a 1} {b 2}} a}} {get {rec {x x}} x}}})(parse-defn '{deffun {h x y} 3}))) 4)
(test (run "{get {r 1} a}" (list (parse-defn '{deffun {r y} {rec {a y}}}))) 1)
(test (run "{get {get {rec {a {rec {b {f 1}}}}} a} b}" (list (parse-defn '{deffun {f a} {rec {a a}}}))) 'record)
(test (run "{get {get {get {rec {a {rec {b {f 1}}}}} a} b} a}" (list (parse-defn '{deffun {f a} {rec {a a}}}))) 1)
(test (run "{get {rec {a {f 1 1 2}} {b {get {rec {c 2}} c}}} a}" (list (parse-defn '{deffun {f a b c} {- {+ a b} c}}))) 0)
(test (run "{get {rec {a 1} {b {get {rec {c {with {x {get {rec {d 2}} d}} {+ 1 x}}}} c}}} b}" empty) 3)
(test (run "{get {rec {a 1} {b {get {rec {a {with {a {get {rec {a 2}} a}} {+ 1 a}}}} a}}} b}" empty) 3)
(test (run "{+ {get {rec {a 1} {b 2}} a} {with {x {get {rec {a {+ 1 1}}} a}} {- x x}}}" empty) 1)
(test (run "{g {g {r 1 {r 2 3}}}}" (list (parse-defn '{deffun {r x y} {rec {a x} {b y}}}) (parse-defn '{deffun {g x} {get x b}}))) 3)
(test (run "{get {f 1 2 3 4 5} a}" (list (parse-defn '{deffun {f l m n o p} {rec {a m} {b l} {c l} {d l} {e l}}}))) 2)
(test (run "{get {f 1 2 3 4 5} a}" (list (parse-defn '{deffun {f l m n o p} {rec {a l} {b m} {c n} {d o} {e p}}}))) 1)
(test (run "{get {f 1 2 3 4 5} a}" (list (parse-defn '{deffun {f a b c d e} {rec {a a} {b b} {c c} {d d} {e e}}}))) 1)
(test (run "{get {rec {a 1} {b {g {r {with {a {g {r 2}}} {+ 1 a}}}}}} b}" (list (parse-defn '{deffun {g x} {get x a}}) (parse-defn '{deffun {r x} {rec {a x}}}))) 3)
(test (run "{+ {get {rec {a 1} {b 2}} a} {with {x {get {r 1} a}} {- x x}}}" (list (parse-defn '{deffun {r x} {rec {a x}}}))) 1)
(test (run "{+ {get {r-2 1 2} a} {with {x {get {r-1 1} a}} {- x x}}}" (list (parse-defn '{deffun {r-1 x} {rec {a x}}}) (parse-defn '{deffun {r-2 x y} {rec {a x} {b y}}}))) 1)
;given tests
(test (run "{rec {a 10} {b {+ 1 2}}}" empty)
'record)
(test (run "{get {rec {a 10} {b {+ 1 2}}} b}" empty)
3)
(test/exn (run "{get {rec {b 10} {b {+ 1 2}}} b}" empty)
"duplicate fields")
(test/exn (run "{get {rec {a 10}} b}" empty)
"no such field")
(test (run "{g {rec {a 0} {c 12} {b 7}}}"
(list (parse-defn '{deffun {g r} {get r c}})))
12)
(test (run "{get {rec {r {rec {z 0}}}} r}" empty)
'record)
(test (run "{get {get {rec {r {rec {z 0}}}} r} z}" empty)
0)
(test/exn (run "{rec {z {get {rec {z 0}} y}}}" empty)
"no such field")
(test (run "{with {x {f 2 5}} {g x}}" (list (parse-defn '{deffun {f a b} {+ a b}}) (parse-defn '{deffun {g x} {- x 5}}))) 2)
(test (run "{f 1 2}" (list (parse-defn '{deffun {f x y} {+ x y}}))) 3)
(test (run "{+ {f} {f}}" (list (parse-defn '{deffun {f} 5}))) 10)
(test (run "{h 1 4 5 6}" (list (parse-defn '{deffun {h x y z w} {+ x w}}) (parse-defn '{deffun {g x y z w} {+ y z}}))) 7)
(test (run "{with {x 10} {- {+ x {f}} {g 4}}}" (list (parse-defn '{deffun {f} 4}) (parse-defn '{deffun {g x} {+ x x}}))) 6)
(test (run "{rec {a 10} {b {+ 1 2}}}" empty) 'record)
(test (run "{get {rec {a 10} {b {+ 1 2}}} b}" empty) 3)
(test (run "{g {rec {a 0} {c 12} {b 7}}}" (list (parse-defn '{deffun {g r} {get r c}}))) 12)
(test (run "{get {rec {r {rec {z 0}}}} r}" empty) 'record)
(test (run "{get {get {rec {r {rec {z 0}}}} r} z}" empty) 0)
(test (run "{with {x 3} {with {y 5} {get {rec {a x} {b y}} a}}}" empty) 3)
(test (run "{with {x {f {rec {a 10} {b 5}} 2}} {g x}}" (list (parse-defn '{deffun {f a b} {+ {get a a} b}}) (parse-defn '{deffun {g x} {+ 5 x}}))) 17)
(test (run "{get {f 1 2 3 4 5} c}" (list (parse-defn '{deffun {f a b c d e} {rec {a a} {b b} {c c} {d d} {e e}}}))) 3)
(test (run "{get {f 1 2 3} b}" (list (parse-defn '{deffun {f a b c} {rec {a a} {b b} {c c}}}))) 2)
(test (run "{get {f 1 2 3} y}" (list (parse-defn '{deffun {f a b c} {rec {x a} {y b} {z c} {d 2} {e 3}}}))) 2)
(test (run "{get {f 1 2 3} d}" (list (parse-defn '{deffun {f a b c} {rec {x a} {y b} {z c} {d 2} {e 3}}}))) 2)
(test (run "{f {get {get {rec {a {rec {a 10} {b {- 5 2}}}} {b {get {rec {x 50}} x}}} a} b}}" (list (parse-defn '{deffun {f x} {+ 5 x}}))) 8)
(test (run "{get {rec {a 10} {b {+ 1 2}}} b}" empty) 3)
(test (run "{g {rec {a 0} {c 12} {b 7}}}" (list (parse-defn '{deffun {g r} {get r c}}))) 12)
(test (run "{get {rec {r {rec {z 0}}}} r}" empty) 'record)
(test (run "{get {get {rec {r {rec {z 0}}}} r} z}" empty) 0)
(test (run "{rec {a 10}}" empty) `record)
(test (run "{get {rec {a 10}} a}" empty) 10)
(test (run "{get {rec {a {+ 1 2}}} a}" empty) 3)
(test (run "{rec }" empty) `record)
(test (run "{get {rec {a {rec {b 10}}}} a}" empty) `record)
(test (run "{get {get {rec {a {rec {a 10}}}} a} a}" empty) 10)
(test (run "{get {get {rec {a {rec {a 10} {b 20}}}} a} a}" empty) 10)
(test (run "{get {get {rec {a {rec {a 10} {b 20}}}} a} b}" empty) 20)
(test (run "{+ {get {rec {a 10}} a} {get {rec {a 20}} a}}" empty) 30)
(test (run "{+ {get {rec {a 10}} a} {get {rec {a 20}} a}}" empty) 30)
(test (run "{rec {a 10}}" empty) `record)
(test (run "{rec {a {- 2 1}}}" empty) `record)
(test (run "{get {rec {a 10}} a}" empty) 10)
(test (run "{get {rec {a {- 2 1}}} a}" empty) 1)
(test (run "{get {rec {a {rec {b 10}}}} a}" empty) `record)
(test (run "{get {get {rec {a {rec {a 10}}}} a} a}" empty) 10)
(test (run "{get {get {rec {a {rec {a 10} {b 20}}}} a} a}" empty) 10)
(test (run "{get {get {rec {a {rec {a 10} {b 20}}}} a} b}" empty) 20)
(test (run "{rec {a 10} {b {+ 1 2}}}" empty) 'record)
(test (run "{get {rec {a 10} {b {+ 1 2}}} b}" empty) 3)
(test (run "{get {rec {r {rec {z 0}}}} r}" empty) 'record)
(test (run "{get {get {rec {r {rec {z 0}}}} r} z}" empty) 0)
(test (run "{rec {a 10} {b {+ 1 2}}}" empty) 'record)
(test (run "{get {rec {a 10} {b {+ 1 2}}} b}" empty) 3)
(test (run "{g {rec {a 0} {c 12} {b 7}}}" (list (parse-defn '{deffun {g r} {get r c}}))) 12)
(test (run "{get {rec {r {rec {z 0}}}} r}" empty) 'record)
(test (run "{get {get {rec {r {rec {z 0}}}} r} z}" empty) 0)
(test (run "{with {y {rec {x 1} {y 2} {z 3}}} {get y y}}" empty) 2)
(test (run "{with {y {rec {x 1} {y 2} {z 3}}} {get y z}}" empty) 3)
(test (run "{rec {a 10} {b {+ 1 2}}}" empty) 'record)
(test (run "{get {rec {a 10} {b {+ 1 2}}} b}" empty) 3)
(test (run "{g {rec {a 0} {c 12} {b 7}}}" (list (parse-defn '{deffun {g r} {get r c}}))) 12)
(test (run "{get {rec {r {rec {z 0}}}} r}" empty) 'record)
(test (run "{get {get {rec {r {rec {z 0}}}} r} z}" empty) 0) | false |
b9a4cbd635f69177c3f963131488b9ec0c46483d | 0884f0d8c2cd37d8e3a6687e462862e4063b9aa4 | /src/builtin/tables.scrbl | 3e290bd6838660a4ff28a721538619fcf5fd8479 | []
| no_license | brownplt/pyret-docs | 988becc73f149cbf2d14493c05d6f2f42e622130 | 6d85789a995abf8f6375cc7516406987315972d1 | refs/heads/horizon | 2023-08-17T03:32:51.329554 | 2023-08-10T20:44:14 | 2023-08-10T20:44:14 | 61,943,313 | 14 | 20 | null | 2023-09-12T20:40:41 | 2016-06-25T12:57:24 | Racket | UTF-8 | Racket | false | false | 38,590 | scrbl | tables.scrbl | #lang scribble/base
@(require "../../scribble-api.rkt" "../abbrevs.rkt")
@(define (g-id name) (seclink (xref "<global>" name)))
@(append-gen-docs
'(module "tables"
(path "src/js/base/runtime-anf.js")
(fun-spec (name "difference"))
(fun-spec (name "difference-from"))
(fun-spec (name "running-sum"))
(fun-spec (name "running-mean"))
(fun-spec (name "running-max"))
(fun-spec (name "running-min"))
(fun-spec (name "running-fold"))
(fun-spec (name "running-reduce"))
(fun-spec (name "raw-row"))
(fun-spec (name "table-from-rows"))
(fun-spec (name "table-from-columns"))
(fun-spec (name "table-from-column"))
(data-spec
(name "Row")
(variants ("row"))
(shared (
(method-spec (name "get-value"))
(method-spec (name "get-column-names"))
(method-spec (name "get"))
)))
(data-spec
(name "Table")
(variants ("table"))
(shared (
(method-spec (name "build-column"))
(method-spec (name "add-column"))
(method-spec (name "add-row"))
(method-spec (name "row"))
(method-spec (name "length"))
(method-spec (name "add-row"))
(method-spec (name "row-n"))
(method-spec (name "column"))
(method-spec (name "get-column"))
(method-spec (name "column-n"))
(method-spec (name "column-names"))
(method-spec (name "all-rows"))
(method-spec (name "all-columns"))
(method-spec (name "filter"))
(method-spec (name "filter-by"))
(method-spec (name "order-by"))
(method-spec (name "order-by-columns"))
(method-spec (name "increasing-by"))
(method-spec (name "decreasing-by"))
(method-spec (name "select-columns"))
(method-spec (name "transform-column"))
(method-spec (name "rename-column"))
(method-spec (name "stack"))
(method-spec (name "empty"))
(method-spec (name "drop"))
;; What about new-row?
)))
(data-spec
(name "Reducer")
(type-vars ("Acc" "InVal" "OutVal"))
(variants ("reducer"))
(shared (
(method-spec (name "reduce"))
(method-spec (name "one")))))))
@(define (table-method name #:args args #:return ret #:contract contract)
(method-doc "Table" "table" name #:alt-docstrings "" #:args args #:return ret #:contract contract))
@(define Table (a-id "Table" (xref "tables" "Table")))
@(define (row-method name #:args args #:return ret #:contract contract)
(method-doc "Row" "row" name #:alt-docstrings "" #:args args #:return ret #:contract contract))
@(define Row (a-id "Row" (xref "tables" "Row")))
@(define (Red-of acc in result) (a-app (a-id "Reducer" (xref "tables" "Reducer")) acc in result))
@(define (red-method name #:args args #:return ret #:contract contract)
(method-doc "Reducer" "reducer" name #:alt-docstrings "" #:args args #:return ret #:contract contract))
@(define Red-params (list "Acc" "InVal" "OutVal"))
@docmodule["tables" #:friendly-title "Tables"]{
There are many examples of tables in computing, with
spreadsheets being the most obvious.
A @pyret-id{Table} is made up of @bold{rows} and @bold{columns}. All rows have the
same number of columns, in the same order. Each column has a name. Each column
may also be assigned a type via an annotation; if so, all entries in a column
will then be checked against the annotation. Unsurprisingly, they are useful
for representing tabular data from sources like spreadsheets or CSV files.
@bold{Note:} The @pyret-id{Table} data type and the syntax for manipulating
tables is built in to Pyret without needing any imports; however, using the
@secref{Reducers} or the functions in @secref{s:tables:methods} require the
@pyret{import} line above.
@section[#:tag "s:tables"]{Creating Tables}
A simple @pyret-id{Table} can be directly created with a @pyret{table:}
expression, which lists any number of
columns, with optional annotations, and then any number of rows. For example,
this expression creates a table with three columns, @pyret{name}, @pyret{age},
and @pyret{favorite-color}, and three rows:
@examples{
my-table = table: name :: String, age :: Number, favorite-color :: String
row: "Bob", 12, "blue"
row: "Alice", 17, "green"
row: "Eve", 13, "red"
end
}
@margin-note{Indeed, @pyret{my-table} is used as a running example in much of
the following.}
Evaluating @pyret{my-table} in the interactions window after running the
program above will display a formatted version of the table:
@(image "src/builtin/table-print.png")
@section[#:tag "s:tables:loading"]{Loading Tables}
Pyret supports loading spreadsheets from Google Sheets and
interpreting them as Pyret tables.
Currently no public interface for creating additional sources
beyond Google Sheets is supported.
You can import most relevant file types, including .xlsx,
into Google Sheets, and then into Pyret, so you should be able to
get almost any tabular data into Pyret with a little effort.
@margin-note{In Google Sheets, you create a file, referred to as a
"spreadsheet" that contains one or more grids called
"sheets." Excel refers to the file as a "workbook" and each
grid as a "worksheet." We will follow Google Sheets'
nomenclature.}
Pyret assumes each sheet contains only one table of neatly formatted
data, without skipping columns or extra comments other than an
optional single header row at the top.
As a simple and consistent example, let's say we wanted to import the
@tt{my-table} data from a spreadsheet.
@(image "src/builtin/gsheet-1.png")
To import this data into a Pyret program, you need to get the
spreadsheet's
unique Google ID. The easiest way to do this is to click
on the blue @tt{Share} button in the upper right.
@(image "src/builtin/gsheet-2.png")
If you don't
want to share your spreadsheet with anyone else, click
@tt{Advanced} in the lower right of the @tt{Share with others}
dialog, then copy the @tt{Link to share}, highlighted in orange below,
and paste it into your Pyret definitions area (or another editor).
@(image "src/builtin/gsheet-3.png")
The URL will look something like
@tt{https://docs.google.com/spreadsheets/d/1BAexzf08Q5o8bXb_k8PwuE3tMKezxRfbKBKT-4L6UzI/edit?usp=sharing}
The Google ID is the part between @tt{/d/} and @tt{/edit...}, in this case:
@tt{1BAexzf08Q5o8bXb_k8PwuE3tMKezxRfbKBKT-4L6UzI}
@margin-note{If you do want to share the spreadsheet with others, click
on the blue @tt{Share} button as above, and then click
@tt{Get sharable link}, choose the appropriate level of
sharing, and copy the URL to get the Google ID as above.}
Now you can load the spreadsheet into your Pyret program:
@examples{
import gdrive-sheets as GS
imported-my-table =
GS.load-spreadsheet("1BAexzf08Q5o8bXb_k8PwuE3tMKezxRfbKBKT-4L6UzI")
}
You can use @pyret{include} instead of @pyret{import as...} to cut down on
some typing by omitting the @tt{GS.} before the @pyret{tables} module
functions.
@examples{
include gdrive-sheets
imported-my-table =
load-spreadsheet("1BAexzf08Q5o8bXb_k8PwuE3tMKezxRfbKBKT-4L6UzI")
}
@margin-note{We'll use
@pyret{import} and the prefix @tt{GS.} in the following examples. If you
use @pyret{include}, omit @tt{GS.} where used below.}
When data is loaded into a table, we recommend using @italic{sanitizers}
to properly load each entry of the table as the correct Pyret type. The
supported sanitizers are imported from the @pyret{data-source} module.
The sanitizers currently provided by Pyret are:
@itemlist[@item{@bold{string-sanitizer} tries to convert anything to a @g-id{String}}
@item{@bold{num-sanitizer} tries to convert numbers, strings and booleans to @g-id{Number}s}
@item{@bold{bool-sanitizer} tries to convert numbers, strings and booleans to @g-id{Boolean}s}
@item{@bold{strict-num-sanitizer} tries to convert numbers and strings (not booleans) to @g-id{Number}s}
@item{@bold{strings-only} converts only strings to @g-id{String}s}
@item{@bold{numbers-only} converts only numbers to @g-id{Number}s}
@item{@bold{booleans-only} converts only booleans to @g-id{Boolean}s}
@item{@bold{empty-only} converts only empty cells to @pyret-id["none" "option"]s}]
@margin-note{While the @tt{data-source} library provides sanitizers which should cover
most use cases, there may be times when one would like to create a custom
data sanitizer. To do so, one must simply create a function which conforms
to the @pyret-id["Sanitizer" "data-source"] type in the @tt{data-source} module.}
Use the @pyret{load-table:} expression to create a table from an
imported sheet.
Each spreadsheet file contains multiple, named sheets, displayed
as tabs across the bottom of the Sheets user interface. When you start
working with the data in an imported spreadsheet, you need to indentify
which sheet you are using as the data source.
The @pyret{source:} expression should be followed by the imported spreadsheet,
calling the @pyret-method["Spreadsheet" #f "sheet-by-name" "gdrive-sheets"] method with two arguments, the sheet name and
a boolean flag indicating whether or not there is a header row in the sheet
that should be ignored. In our example above, @tt{imported-my-table} contains
one sheet, called @tt{3-rows},
and there is a header row that should be ignored by the importer, so the
@pyret{source:} expression would be written as illustrated below.
@examples{
import gdrive-sheets as GS
import data-source as DS
imported-my-table =
GS.load-spreadsheet("1BAexzf08Q5o8bXb_k8PwuE3tMKezxRfbKBKT-4L6UzI")
my-table = load-table: name :: String, age :: Number, favorite-color :: String
source: imported-my-table.sheet-by-name("3-rows", true)
sanitize name using DS.string-sanitizer
sanitize age using DS.strict-num-sanitizer
sanitize favorite-color using DS.string-sanitizer
end
}
In general, it is @italic{safest} to sanitize @italic{every} input column, since it
is the only way to guarantee that the data source will not guess the column's
type incorrectly.
Note that Google Sheets, and other spreadsheets, themselves
assign or infer types to data in a way that often is not apparent to the user
and is a common source of errors when exporting from or between spreadsheet
applications.
@section[#:tag "s:tables:select"]{Selecting Columns}
The @pyret{select} expression can be used to create a new table from a subset
of the columns of an existing one. For example, we can get just the names
and ages from @pyret{my-table} above:
@examples{
names-and-ages = select name, age from my-table end
check:
names-and-ages is table: name, age
row: "Bob", 12
row: "Alice", 17
row: "Eve", 13
end
end
}
@section{Filtering Tables}
The @pyret{sieve} mechanism allows for filtering out rows of tables based
on some criteria. The @pyret{using} keyword specifies which columns may be
used in the body of the @pyret{sieve} expression.
For instance, we can find the individuals in @pyret{my-table} who are old
enough to drive in the United States.
@pyret-block[#:style "good-ex"]{
can-drive = sieve my-table using age:
age >= 16
end
check:
can-drive is table: name, age, favorite-color
row: "Alice", 17, "green"
end
end
}
Note that the @pyret{sieve} block must explicitly list the columns used to
filter out values with @pyret{using}. The following would signal an undefined
name error for @pyret{age}, because names being used in the expression body
must be listed:
@pyret-block[#:style "bad-ex"]{
can-drive = sieve my-table using name:
# age is not visible inside of this expression
age >= 16
end
}
@section{Ordering Tables}
To arrange the rows of a table in some particular order, use an @pyret{order}
expression. This can be done with any column whose
type supports the use of @pyret{<} and @pyret{>}, including @g-id{String}s.
@examples{
name-ordered = order my-table:
name ascending
end
check:
name-ordered is table: name, age, favorite-color
row: "Alice", 17, "green"
row: "Bob", 12, "blue"
row: "Eve", 13, "red"
end
end
}
Tables can be sorted by multiple columns. In general you may select as many
columns as desired, and can mix and match @pyret{ascending} and
@pyret{descending} sorts. No column can be mentioned more than once.
@pyret-block{
order some-table:
column1 ascending,
column3 descending,
column2 ascending
end
}
This example will first sort the data in increasing order on @tt{column1}. If there
are any duplicate values in @tt{column1}, each such group of rows will be sorted in
decreasing order by @tt{column3}. If there are any duplicates in both columns,
each remaining group will be sorted in increasing order by @tt{column2}.
@section{Transforming Tables}
The @pyret{transform} expression allows the changing of columns within a
table, similar to the @pyret-id["map" "lists"] function over lists (and, just like
@pyret-id["map" "lists"], @pyret{transform} expressions do not mutate the table, but
instead return a new one).
Suppose we find out that @pyret{my-table} is wrong and everyone is actually
a year older than it says they are. We can fix our data as follows:
@pyret-block{
age-fixed = transform my-table using age:
age: age + 1
end
check:
age-fixed is table: name, age, favorite-color
row: "Bob", 13, "blue"
row: "Alice", 18, "green"
row: "Eve", 14, "red"
end
end
}
@section{Extracting Columns from Tables}
A large number of Pyret modules work on @seclink{lists} instead of tables, so it
may be desired to pull the contents of one column of a table as a list to
use it elsewhere. The @pyret{extract} mechanism allows this ability, and
serves as the primary link between processing tabular data and non-tabular
Pyret functions.
Suppose, for example, we wanted just the names of each person in
@pyret{my-table}. We could pull those names out as follows:
@pyret-block{
name-list = extract name from my-table end
check:
name-list is [list: "Bob", "Alice", "Eve"]
end
}
@section{Extending Tables}
"Extending" a table means to create a new table with an additional,
calculated column. There are two types of extensions which can be
made to tables: mapping extensions and reducing extensions.
@subsection{Mapping extensions}
A mapping column is one whose contents are calculated from other
columns only in the row it is being added to. This is analogous
to the map function for @seclink{lists}.
In a mapping expression, the body of the expression defines the name of
the new column or columns followed by an expression which calculates
the new value to be placed in each row of the new column.
One example of this is a column which tells
whether the @pyret{age} field of a given row in @pyret{my-table} indicates
that the person in that row is old enough drive in the United States or not,
that is, whether that person is at least 16:
@examples{
can-drive-col = extend my-table using age:
can-drive: age >= 16
end
check:
can-drive-col is table: name, age, can-drive
row: "Bob", 12, false
row: "Alice", 17, true
row: "Eve", 13, false
end
end
}
Another example creates a new table including baseball players'
calculated batting average and slugging percentage in extended
columns:
@examples{
batting = table: batter :: String,
at-bats :: Number, singles :: Number, doubles :: Number,
triples :: Number, home-runs :: Number
row: "Julia", 20, 4, 2, 0, 0
row: "Vivian", 25, 6, 1, 1, 1
row: "Eddie", 28, 5, 2, 0, 2
end
batting-avg-and-slugging = extend batting
using at-bats, singles, doubles, triples, home-runs:
batting-average: (singles + doubles + triples + home-runs) / at-bats,
slugging-percentage: (singles + (doubles * 2) +
(triples * 3) + (home-runs * 4)) / at-bats
end
}
@(image "src/builtin/baseball.png")
@margin-note{As in @seclink["s:tables:transform"]{@pyret{transform}},
you must specify which columns will be used to calculate the
value in the
@pyret{extend} expression using the @pyret{using} keyword.}
@subsection{Reducers}
A "reducing" column is one whose information is computed from the
row it is being added to @italic{and one or more of the rows above}
that row. This is
analogous to the @pyret-id["fold" "lists"] function for @seclink{lists}.
The simplest examples of reducing use reducers built into Pyret.
For each reducer below, you will need to specify
a name for the new column and which existing column new value
will be based on. You will also need to
@pyret{import} or @pyret{include} @pyret{tables}.
@value["running-sum" (Red-of N N N)]
Creates a new column where in each row,
the running sum will be the added
value of the cell in the selected column plus all the cells
@italic{above} the cell in the same column.
@examples{
import tables as T
dem-primary-delegates = table: state :: String, clinton :: Number,
sanders :: Number
row: "Iowa", 29, 21
row: "New Hampshire", 15, 16
row: "Nevada", 27, 16
row: "South Carolina", 44, 14
end
running-total-delegates = extend dem-primary-delegates
using clinton, sanders:
total-clinton: T.running-sum of clinton,
total-sanders: T.running-sum of sanders
end
print(running-total-delegates)
}
@(image "src/builtin/primaries.png")
@value["difference" (Red-of N N N)]{
The @pyret{difference} extender creates a new column
containing the difference between the value in
the current row (of the selected column) minus the value in @italic{only}
the row directly above. In the first row, the value is unchanged.
Since there's no value before the first row, Pyret behaves as if it were zero.
@margin-note{Both @pyret{difference} and @pyret-id{difference-from} do
@italic{not} calculate a running difference, only the difference between
the selected row and the single row above.}
@examples{
import tables as T
test-scores = table: year :: Number,
math-score :: Number, reading-score :: Number
row: 2014, 87, 89
row: 2015, 98, 93
row: 2016, 79, 83
row: 2017, 85, 90
end
changes-by-year = extend test-scores using math-score, reading-score:
math-change-from-previous: T.difference of math-score,
reading-change-from-previous: T.difference of reading-score
end
}
@(image "src/builtin/difference-table.png")
}
@function["difference-from"
#:contract (a-arrow N (Red-of N N N))
#:args '(("start-value" #f))
#:return (Red-of N N N)]{
Like @pyret-id{difference}, except the starting value is specified, instead
of defaulting to 0.
@examples{
# calculates velocity of a dropping ball
ball-info = table: pos-y
row: 25
row: 24
row: 21
row: 16
row: 0
end
with-velocity = extend ball-info using pos-y:
vel-y: T.difference-from(25) of pos-y
end
check:
with-velocity is table: pos-y, vel-y
row: 25, 0
row: 24, -1
row: 21, -3
row: 16, -5
row: 0, -16
end
end
}
}
@value["running-mean" (Red-of N N N)]
Creates a new column where the
value in each row is equal to the
mean of @italic{all} values in the designated column in the current row and
above.
@examples{
import tables as T
my-grades = table: score :: Number
row: 87
row: 91
row: 98
row: 82
end
with-running-mean = extend my-grades
using score:
mean: T.running-mean of score
end
check:
with-running-mean is table: score, mean
row: 87, 87
row: 91, 89
row: 98, 92
row: 82, 89.5
end
end
}
@value["running-max" (Red-of N N N)]
@value["running-min" (Red-of N N N)]
Creates a new column that contains the maximum
or minimum value in the selected column in the current row or
above.
@examples{
some-numbers = table: n :: Number
row: 4
row: 9
row: 3
row: 1
row: 10
end
with-min-max = extend some-numbers using n:
max: T.running-max of n,
min: T.running-min of n
end
check:
with-min-max is table: n, max, min
row: 4, 4, 4
row: 9, 9, 4
row: 3, 9, 3
row: 1, 9, 1
row: 10, 10, 1
end
end
}
@function["running-fold"
#:contract (a-arrow "Result" (a-arrow "Result" "Col" "Result") (Red-of "Result" "Col" "Result"))
#:args '(("start-value" #f) ("combiner" #f))
#:return (Red-of "Result" "Col" "Result")]{}
@function["running-reduce"
#:contract (a-arrow (a-arrow "Col" "Col" "Col") (Red-of "Col" "Col" "Col"))
#:args '(("combiner" #f))
#:return (Red-of "Col" "Col" "Col")]
@pyret{running-fold} and @pyret{running-reduce} allow you
to specify a function used to calculate
the value in the new column, based on a running calculation of all the
values in the selected column in the current row and above.
The difference between @pyret{running-fold} and @pyret{running-reduce} is
that @pyret{running-fold} requires an explicit @tt{start-value}.
@examples{
import tables as T
count-if-driver = T.running-fold(0,
lam(sum, col): if col >= 16: 1 + sum else: sum end end)
t = table: name, age
row: "Bob", 17
row: "Mary", 22
row: "Jane", 6
row: "Jim", 15
row: "Barbara", 30
end
with-driver-count = extend t using age:
total-drivers: count-if-driver of age
end
check:
with-driver-count is table: name, age, total-drivers
row: "Bob", 17, 1
row: "Mary", 22, 2
row: "Jane", 6, 2
row: "Jim", 15, 2
row: "Barbara", 30, 3
end
end
checks = table: check-number :: Number, withdrawal :: Number
row: 001, 50
row: 002, 100
row: 003, 500
end
with-checking-balance = extend checks using withdrawal:
current-balance: T.running-fold(1000,
lam(total, col): total - col end) of withdrawal
end
check:
with-checking-balance is table: check-number, withdrawal, current-balance
row: 001, 50, 950
row: 002, 100, 850
row: 003, 500, 350
end
end
}
While the reducers found in the @tt{tables} module should cover most all
use cases, there may be times when one would like to create a reducer of their
own. To do so, one must construct an object of the following type:
@type-spec["Reducer" (list "Acc" "InVal" "OutVal")]{
@red-method["one"
#:contract (a-arrow (apply Red-of Red-params) "InVal" (a-tuple "Acc" "OutVal"))
#:args '(("self" #f) ("value-from-column" #f))
#:return (a-tuple "Acc" "OutVal")]
@red-method["reduce"
#:contract (a-arrow (apply Red-of Red-params) "Acc" "InVal" (a-tuple "Acc" "OutVal"))
#:args '(("self" #f) ("accumulator" #f) ("value-from-column" #f))
#:return (a-tuple "Acc" "OutVal")]
Reducers are essentially descriptions of folds (in the list @pyret-id["fold" "lists"]
sense) over table columns. The way reducers are called by the language
runtime is as follows: the value(s) from the first row are passed to the
reducer's @pyret-method["Reducer" "reducer" "one"] method, which should return a tuple containing both
any accumulated information needed for the fold and the value which should
be placed in the new column in that row. The remaining rows are then
sequentially populated using the reducer's @pyret-method["Reducer" "reducer" "reduce"] method, which is
identical to the @pyret-method["Reducer" "reducer" "one"] method except that it receives an additional
argument which is the previously mentioned accumulated information from the
previous row.
To illustrate, a @pyret{running-mean} reducer which is equivalent to the
one provided by the @tt{tables} module could be implemented as follows:
@examples{
import tables as T
running-mean :: T.Reducer<{Number; Number}, Number, Number> = {
one: lam(n): {{n; 1}; n} end,
reduce: lam({sum; count}, n):
{ {sum + n; count + 1}; (sum + n) / (count + 1) }
end
}
}
}
@section[#:tag "s:tables:comparing"]{Comparing Tables}
The order of both rows and columns are part of a table value. To be considered
equal, tables need to have all the same rows and columns, with the rows and
columns appearing in the same order.
@section[#:tag "s:tables:methods"]{Advanced Table Manipulation}
The operations listed above come with a significant restriction: all column
names must also be valid identifier names. In addition, column names are always
chosen directly by the programmer in each query, and there's no way to abstract
over them.
To see why this is a significant restriction, consider this (non-working)
example:
@examples{
fun sieve-by-large-number(t :: Table, colname :: String) -> Table:
doc: ```Return a new table containing the rows of t whose column
named by the string provided for colname have value greater than
1000```
sieve t using colname:
colname > 1000
end
where:
my-t = table: item, price
row: "Chromebook", 250
row: "Macbook", 1300
end
sieve-by-large-number(my-t, "price") is table: item, price
row: "Macbook", 1300
end
end
}
We may well want to write this if we have a number of tables, all of which we
want to sieve by the same criteria. However, it isn't possible to abstract over
a column name using @tt{sieve}: the program above conflates the identifier
@tt{colname} with the column name @tt{colname}. As a result, that program gives
an error that the @tt{colname} in the query shadows the @tt{colname} that's a
parameter of the function.
Pyret provides facilities for writing programs like the above, they are simply
a different set of operations than the query syntax. These table manipulation
operations are useful for building abstractions over tables and for creating
tables programmatically.
@type-spec["Row" (list)]{
The type of all row values.
}
@collection-doc["raw-row" #:contract `(a-arrow ("elt" ,(a-tuple S "Col")) ,Row)]
Takes a sequence of tuples and constructs a @pyret-id["Row"] value. Note that
the type for each column may be different. The constructed row can be added to
appropriate tables by using the table methods like @pyret-method["Table" "table"
"add-row"].
It is often preferable to construct rows for an existing table by using the
@pyret-method["Table" "table" "row"] method, which avoids typing out the names of each
column for each created row, and provides built-in checking for the count of
columns.
@row-method["get-column-names"
#:contract (a-arrow Row (L-of S))
#:args '((self #f))
#:return (L-of S)]
Produces a list of strings containing the names of the columns in the row.
@examples{
check:
r = [raw-row: {"city"; "NYC"}, {"pop"; 8500000}]
r.get-column-names() is [list: "NYC", "pop"]
end
}
@row-method["get-value"
#:contract (a-arrow Row S "Col")
#:args '((self #f) ("col-name" #f))
#:return "Col"]
Consumes the name of a column, and produces the corresponding value. Results in
an error if the value isn't found. Square-bracket (@tt{[]}) accessor syntax
uses @tt{get-value}, which is often more pleasant to write than writing out
@tt{get-value} fully.
@examples{
check:
r = [raw-row: {"city"; "NYC"}, {"pop"; 8500000}]
r.get-value("pop") is 8500000
r["pop"] is 850000
end
}
@row-method["get"
#:contract (a-arrow Row S (O-of "Col"))
#:args '((self #f) ("col-name" #f))
#:return (O-of "Col")]
Consumes the name of a column, and produces a @pyret-id["some" "option"]
containing the corresponding value if it's present, or @pyret-id["none"
"option"] if it isn't.
@type-spec["Table" (list)]{
The type of all tables.
}
@collection-doc["table-from-rows" #:contract `(a-arrow ("elt" ,Row) ,Table)]
A collection constructor that creates tables from @pyret-id["Row"] values.
@examples{
check:
t = [table-from-rows:
[raw-row: {"A"; 5}, {"B"; 7}, {"C"; 8}],
[raw-row: {"A"; 1}, {"B"; 2}, {"C"; 3}]
]
t.length() is 2
t.column("A") is [list: 5, 1]
t.row-n(0) is [raw-row: {"A"; 5}, {"B"; 7}, {"C"; 8}]
end
}
@collection-doc["table-from-columns" #:contract `(a-arrow ("elt" ,(a-tuple "String" (L-of "A"))) ,Table)]
A collection constructor that creates tables from columns, where each column is
specified as a tuple of its name (as a @pyret-id["String" "<global>"]) and a
@pyret-id["List" "lists"] of its values.
@examples{
check:
t = [table-from-columns:
{"a"; [list: 100, 200, 300]},
{"b"; [list: true, false, true]}
]
t.length() is 3
t.column("a") is [list: 100, 200, 300]
t.row-n(2) is [raw-row: {"a"; 300}, {"b"; true}]
end
}
@function["table-from-column"
#:contract (a-arrow S (L-of "A") Table)
#:args '(("column-name" #f) ("values" #f))
#:return Table]{
A function that creates a table of a single column from a column name, given as
a @pyret-id["String" "<global>"] and a @pyret-id["List" "lists"] of values.
@examples{
check:
col = range(0, 100)
tfc = table-from-column("a", col)
tfc.length() is 100
tfc.column-names() is [list: "a"]
cs = tfc.all-columns()
cs.get(0) is col
end
}
}
@table-method["length"
#:contract (a-arrow Table N)
#:args '(("self" #f))
#:return N]
Evaluates to the number of rows in the table.
@table-method["row"
#:contract (a-arrow Table "Col1" "Col2" "..." "ColN" Row)
#:args '(("self" #f) ("col-1" #f) ("col-2" #f) ("..." #f) ("col-n" #f))
#:return Row]
Consumes one value for each column in the table, and produces a
@pyret-id["Row"] value where each provided value is associated with the
appropriate column.
@examples{
check:
t = table: city, pop
row: "NYC", 8.5 * 1000000
row: "SD", 1.4 * 1000000
end
r = t.row("Houston", 2.3 * 1000000)
r is [raw-row: {"city"; "Houston"}, {"pop"; 2.3 * 1000000}]
end
}
@table-method["build-column"
#:contract (a-arrow Table S (a-arrow Row "Col") Table)
#:args '(("self" #f) ("colname" #f) ("compute-new-val" #f))
#:return Table]
Consumes an existing table, and produces a new
table containing an additional column with the given @tt{colname}, using
@tt{compute-new-val} to produce the values for that column, once for each row.
Here, @tt{Col} is the type of the new column, determined by the type of value
the @tt{compute-new-val} function returns.
@examples{
check:
foods = table: name, grams, calories
row: "Fries", 200, 500
row: "Milkshake", 400, 600
end
foods-with-cpg = table: name, grams, calories, cal-per-gram
row: "Fries", 200, 500, 500/200
row: "Milkshake", 400, 600, 600/400
end
fun add-cpg(r :: Row) -> Number:
r["calories"] / r["grams"]
end
foods.build-column("cal-per-gram", add-cpg) is foods-with-cpg
end
}
@examples{
fun add-index(t):
var ix = -1
t.build-column("index", lam(_) block:
ix := ix + 1
ix
end)
where:
before = table: name
row: "Joe"
row: "Shriram"
row: "Kathi"
end
after = table: name, index
row: "Joe", 0
row: "Shriram", 1
row: "Kathi", 2
end
add-index(before) is after
end
}
@table-method["add-column"
#:contract (a-arrow Table S (L-of "Col") Table)
#:args '(("self" #f) ("colname" #f) ("new-vals" #f))
#:return Table]
Consumes a column name and a list of values, and produces a new table with a
columng of the given name added, containing the values from @tt{new-vals}.
It is an error if the length of @tt{new-vals} is different than the length of
the table.
@table-method["add-row"
#:contract (a-arrow Table Row Table)
#:args '(("self" #f) ("r" #f))
#:return Table]
Consumes a table and a row to add, and produces a new table with the given row
at the end.
@table-method["row-n"
#:contract (a-arrow Table N Row)
#:args '(("self" #f) ("index" #f))
#:return Row]
Consumes an index, and returns the row at that index. The first row has index
0.
@table-method["get-column"
#:contract (a-arrow Table S (L-of "Col"))
#:args '(("self" #f) ("colname" #f))
#:return (L-of "Col")]
Consumes the name of a column, and returns the values in that column as a
list.
@table-method["column"
#:contract (a-arrow Table S (L-of "Col"))
#:args '(("self" #f) ("colname" #f))
#:return (L-of "Col")]
This method is no longer used (use @pyret-method["Table" "table" "get-column"]
instead).
@table-method["column-n"
#:contract (a-arrow Table N (L-of "Col"))
#:args '(("self" #f) ("index" #f))
#:return (L-of "Col")]
Consumes an index, and returns the values in the column at that index as a
list. The first column has index 0.
@table-method["column-names"
#:contract (a-arrow Table (L-of S))
#:args '(("self" #f))
#:return (L-of S)]
Consumes no arguments, and produces the names of the columns of the table as a
list.
@table-method["all-rows"
#:contract (a-arrow Table (L-of Row))
#:args '(("self" #f))
#:return (L-of Row)]
Consumes no arguments, and produces a list containing all the rows in the
table, in the same order they appear in the table.
@table-method["all-columns"
#:contract (a-arrow Table (L-of (L-of "Col")))
#:args '(("self" #f))
#:return (L-of (L-of "Col"))]
Consumes no arguments, and produces a list of lists of the column values. The
columns and values appear in the same order they appeared in the table.
@table-method["filter"
#:contract (a-arrow Table (a-arrow Row B) Table)
#:args '(("self" #f) ("predicate" #f))
#:return Table]
Consumes a predicate over rows, and produces a new table containing only the
rows for which the predicate returned @pyret{true}.
@table-method["filter-by"
#:contract (a-arrow Table S (a-arrow "Col" B) Table)
#:args '(("self" #f) ("colname" #f) ("predicate" #f))
#:return Table]
Consumes a column name and a predicate over the values of that column, and
produces a new table containing only the rows for which the predicate returned
@pyret{true} for that column. The type of argument to the predicate has the
type of values in the specified column.
@table-method["order-by"
#:contract (a-arrow Table S B Table)
#:args '(("self" #f) ("colname" #f) ("asc" #f))
#:return Table]
Consumes a column name and whether to order ascending or descending, and
produces a new table with the rows ordered by the given column.
If @pyret{true} is given for @tt{asce}, the rows are ordered lowest to
highest by the given column (e.g. using @pyret{<}), and if @pyret{false} is
given, they are ordered highest to lowest.
@table-method["order-by-columns"
#:contract (a-arrow Table (L-of (a-tuple S B)) Table)
#:args '(("self" #f) ("cols" #f))
#:return Table]
Consumes a list of tuples describing column orderings, and produces a new table
according to the given ordering.
Each element of the list must be a two-element tuple, containing a column name
and a boolean indicating whether to order ascending or not. As with
@pyret-method["Table" "table" "order-by"], @pyret{true} indicates ascending and
@pyret{false} indicates descending.
@table-method["increasing-by"
#:contract (a-arrow Table S Table)
#:args '(("self" #f) ("colname" #f))
#:return Table]
Like @pyret-method["Table" "table" "order-by"], but @tt{ascending} is always
@pyret{true}.
@table-method["decreasing-by"
#:contract (a-arrow Table S Table)
#:args '(("self" #f) ("colname" #f))
#:return Table]
Like @pyret-method["Table" "table" "order-by"], but @tt{ascending} is always
@pyret{false}.
@table-method["select-columns"
#:contract (a-arrow Table (L-of S) Table)
#:args '(("self" #f) ("colnames" #f))
#:return Table]
Consumes a list of column names, and produces a new table containing only those
columns. The order of the values in the columns is the same as in the input
table, and the order of the columns themselves is the order they are given in
the list.
@table-method["transform-column"
#:contract (a-arrow Table S (a-arrow "ColIn" "ColOut") Table)
#:args '(("self" #f) ("colname" "") ("f" ""))
#:return Table]
Consumes a column name and a transformation function, and produces a new table
where the given function has been applied to all values in the specified
column of the original table.
@table-method["rename-column"
#:contract (a-arrow Table S S Table)
#:args '(("self" #f) ("old-colname" "") ("new-colname" ""))
#:return Table]
Produces a new table where the specified column name in the original table has
been renamed to the new name. The new name must not already be present in the
table's columns.
This operation is essentially the following:
@pyret-block{
fun rename-column(t :: Table, old-colname :: String, new-colname :: String):
new-t = t.build-column(new-colname, lam(r): r["old-colname"] end)
new-t.drop("old-colname")
end
}
except that in this code, the renamed column will appear as the rightmost column of
the result, whereas using @pyret-method["Table" "table" "rename-column"], the renamed
column will stay in its original place.
@table-method["stack"
#:contract (a-arrow Table Table Table)
#:args '(("self" #f) ("bot-table" ""))
#:return Table]
Returns a new table containing all the rows of this table, followed by all the
rows of the @pyret{bot-table}. The column names must all match, but the order
is not required to match.
@examples{
check:
t1 = table: city, pop
row: "Houston", 2400000
row: "NYC", 8400000
end
t2 = table: pop, city # deliberately reversed column order for this example
row: 1400000, "San Diego"
end
t1.stack(t2) is table: city, pop
row: "Houston", 2400000
row: "NYC", 8400000
row: "San Diego", 1400000
end
t2.stack(t1) is table: pop, city
row: 1400000, "San Diego"
row: 2400000, "Houston"
row: 8400000, "NYC"
end
end
}
@table-method["empty"
#:contract (a-arrow Table Table)
#:args '(("self" #f))
#:return Table]
Returns a new table with the same columns as this table, but with all rows
removed.
@examples{
check:
t1 = table: city, pop
row: "Houston", 2400000
row: "NYC", 8400000
end
t1.empty() is table: city, pop end
end
}
@table-method["drop"
#:contract (a-arrow Table S Table)
#:args '(("self" #f) ("colname" ""))
#:return Table]
Returns a new table that contains all the data from this table except the
specified column.
@examples{
check:
t1 = table: city, pop
row: "Houston", 2400000
row: "NYC", 8400000
end
t1.drop("city") is table: pop
row: 2400000
row: 8400000
end
t1.drop("pop") is table: city
row: "Houston"
row: "NYC"
end
end
}
@;{
@table-method["join"
#:contract (a-arrow Table S Table S Table)
#:args '(("self" #f) ("col1" #f) ("t2" #f) ("col2" #f))
#:return Table]
Creates a new table containing all the rows from the tables where the column
@tt{col1} in @tt{t1} is equal to the column @tt{col2} in @tt{t2}. If the column
@examples{
check:
t1 = table: city, pop
row: "Houston", 2400000
row: "NYC", 8400000
end
t2 = table: city-name, latitude
row: "Houston", 29.7604
row: "NYC", 40.7128
end
result = table: city, pop, city-name, latitude
row: "Houston", 240000, "Houston", 29.7604
row: "NYC", 240000, "NYC", 40.7128
end
t1.join("city", t2, "city-name") is result
end
}
}
}
| false |
9f237fc2d10fd1598afb4bfab3cfb1fa48c3fbfd | 9ef0b809bd17c71bcb30bc9f0037713a116c9495 | /private/util.rkt | 0792cf7aef77c961633d70eb7ae16d41829f6b22 | [
"MIT"
]
| permissive | utahplt/gtp-measure | 1403b73e9295397a33d1ad7f658a089a2c41d325 | 985c62ffec08f5036092b97f808d74041e5138d3 | refs/heads/master | 2023-05-31T01:28:02.440466 | 2023-04-24T19:16:18 | 2023-04-24T19:16:46 | 119,434,878 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 1,773 | rkt | util.rkt | #lang racket/base
(provide
copy-file*
copy-racket-file*
enumerate
gtp-measure-logger
log-gtp-measure-fatal
log-gtp-measure-error
log-gtp-measure-warning
log-gtp-measure-info
log-gtp-measure-debug
force/gtp-measure)
(require
file/glob
gtp-util
(only-in racket/file
delete-directory/files)
(only-in racket/path
file-name-from-path)
(only-in racket/logging
with-intercepted-logging)
(for-syntax
racket/base
(only-in racket/syntax format-id)
syntax/parse))
;; =============================================================================
(define-logger gtp-measure)
(define-syntax (make-log-interceptor stx)
(syntax-parse stx
[(_ ?base-name:id)
#:with ?logger-id (format-id stx "~a-logger" (syntax-e #'?base-name))
#'(lambda (thunk #:level [level 'info])
(define inbox (make-hasheq '((debug . ()) (info . ()) (warning . ()) (error . ()) (fatal . ()))))
(with-intercepted-logging
(λ (l)
(define lvl (vector-ref l 0))
(define msg (vector-ref l 1))
(when (eq? '?base-name (vector-ref l 3))
(hash-set! inbox lvl (cons msg (hash-ref inbox lvl))))
(void))
thunk
#:logger ?logger-id
level)
(for/hasheq ([(k v) (in-hash inbox)])
(values k (reverse v))))]))
(define force/gtp-measure
(make-log-interceptor gtp-measure))
;; =============================================================================
(module+ test
(provide filesystem-test-case)
(require
rackunit
(for-syntax racket/base))
(define-syntax (filesystem-test-case stx)
(if (getenv "CI")
#'(void)
(with-syntax ([stuff (cdr (syntax-e stx))])
#'(test-case . stuff))))
)
| true |
a8505e2952d8d2f918b17ec2f49e64aba8253bbf | 04c0a45a7f234068a8386faf9b1319fa494c3e9d | /applicative-order-y-combinator.rkt | 74c2a8fed8aba2d3406785679f72164f5a47bc17 | []
| no_license | joskoot/lc-with-redex | 763a1203ce9cbe0ad86ca8ce4b785a030b3ef660 | 9a7d2dcb229fb64c0612cad222829fa13d767d5f | refs/heads/master | 2021-01-11T20:19:20.986177 | 2018-06-30T18:02:48 | 2018-06-30T18:02:48 | 44,252,575 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 733 | rkt | applicative-order-y-combinator.rkt | #lang racket
(require redex)
(printf "~a~n" "applicative-order-y-combinator")
(define (! n) (if (zero? n) 1 (* n (! (sub1 n)))))
(define (test1 n)
(test-equal
(((λ (m) ((λ (f) (m (f f))) (λ (f) (m (λ (x) ((f f) x))))))
(λ (!) (λ (n) (if (zero? n) 1 (* n (! (sub1 n)))))))
n)
(! n)))
(define (test2 n)
(test-equal
(((λ (m) ((λ (f) (f f)) (λ (f) (m (λ (x) ((f f) x))))))
(λ (!) (λ (n) (if (zero? n) 1 (* n (! (sub1 n)))))))
n)
(! n)))
(define (test3 n)
(test-equal
(((λ (m) ((λ (f) (m (λ (x) ((f f) x)))) (λ (f) (m (λ (x) ((f f) x))))))
(λ (!) (λ (n) (if (zero? n) 1 (* n (! (sub1 n)))))))
n)
(! n)))
(for ((n (in-range 0 11))) (test1 n) (test2 n) (test3 n))
(test-results)
| false |
2d7c4396267b2e357107cff1fbf4438184392df5 | b3f7130055945e07cb494cb130faa4d0a537b03b | /gamble/private/mh/proposal.rkt | 68639be19a05282dc607074e75ad385b2303d83a | [
"BSD-2-Clause"
]
| permissive | rmculpepper/gamble | 1ba0a0eb494edc33df18f62c40c1d4c1d408c022 | a5231e2eb3dc0721eedc63a77ee6d9333846323e | refs/heads/master | 2022-02-03T11:28:21.943214 | 2016-08-25T18:06:19 | 2016-08-25T18:06:19 | 17,025,132 | 39 | 10 | BSD-2-Clause | 2019-12-18T21:04:16 | 2014-02-20T15:32:20 | Racket | UTF-8 | Racket | false | false | 7,660 | rkt | proposal.rkt | ;; Copyright (c) 2014 Ryan Culpepper
;; Released under the terms of the 2-clause BSD license.
;; See the file COPYRIGHT for details.
#lang racket/base
(require (rename-in racket/match [match-define defmatch])
racket/class
racket/format
"base.rkt"
"db.rkt"
"../interfaces.rkt"
"interfaces.rkt"
"../dist.rkt")
(provide (all-defined-out))
;; ============================================================
;; proposal:<X> : ... -> Proposal
(define (proposal:resample) (new resample-proposal%))
(define (proposal:drift) (new adaptive-drift-proposal%))
;; default-proposal : (parameterof Proposer)
(define default-proposal (make-parameter proposal:drift))
;; ============================================================
(define proposal-base%
(class* object% (proposal<%>)
(super-new)
(field [counter 0])
(define/public (accinfo)
(Info ["Count" counter]))
(define/public (propose1 key zones dist value)
(set! counter (add1 counter))
(propose1* key zones dist value))
(abstract propose1*)
(define/public (propose2 key zones last-dist current-dist value)
(set! counter (add1 counter))
(propose2* key zones last-dist current-dist value))
(abstract propose2*)
(define/public (feedback key success?) (void))
))
(define resample-proposal%
(class proposal-base%
(inherit-field counter)
(super-new)
(define/override (accinfo)
(Info "-- resample proposal"
[include (super accinfo)]))
(define/override (propose1* key zones dist value)
(propose:resample dist value))
(define/override (propose2* key zones old-dist new-dist old-value)
(propose2:resample old-dist new-dist old-value))
))
(define static-drift-proposal%
(class proposal-base%
(init-field scale-factor)
(inherit-field counter)
(super-new)
(define/override (accinfo)
(Info "-- static drift proposal"
[include (super accinfo)]))
(define/override (propose1* key zones dist value)
(define r (*drift1 dist value scale-factor))
(vprintf "DRIFTED from ~e to ~e\n" value (car r))
r)
(define/override (propose2* key zones old-dist new-dist old-value)
(define fd (*drift-dist new-dist old-value scale-factor))
(define new-value (dist-sample fd))
(define rd (*drift-dist old-dist new-value scale-factor))
(define F (dist-pdf fd new-value #t))
(define R (dist-pdf rd old-value #t))
(list* new-value F R))
))
;; ============================================================
;; An Adapt is (adapt Real Nat Nat Nat Nat)
;; - scale-factor is the current scale factor
;; - batch-{trials,successes} is the number of trials/successes since the last adjustment
;; - old-{trials,successes} is the number of trials/successes before the last adjustment
(struct adapt (scale batch-trials batch-successes old-trials old-successes) #:mutable)
(define (adapt-all-trials a) (+ (adapt-batch-trials a) (adapt-old-trials a)))
(define (adapt-all-successes a) (+ (adapt-batch-successes a) (adapt-old-successes a)))
(define ADAPT-BATCH 40)
(define ADAPT-GOAL-HI 0.50)
(define ADAPT-GOAL-LO 0.25)
(define ADAPT-INIT 1.0)
(define ADAPT-UP 1.25)
(define ADAPT-DOWN 0.80)
(define ADAPT-MIN (exp -20))
(define ADAPT-MAX (exp 20))
;; FIXME: alternatives to Address as adaptation key?
;; FIXME: check single-site goal range
;; FIXME: multi-site has different goal range (?), may be fundamentally different
(define adaptive-drift-proposal%
(class proposal-base%
(field [table (make-hash)] ;; Hash[ Key => Adapt ]
[incr-count 0]
[decr-count 0]
[stay-count 0])
(define warned-out-of-range? #f) ;; suppresses multiple warnings
(super-new)
(define/override (accinfo)
(Info "-- adaptive drift proposal"
[include (super accinfo)]
["Scale increased" incr-count]
["Scale decreased" decr-count]
["Scale maintained" stay-count]))
(define/override (propose1* key zones dist value)
(define a (hash-ref! table key (lambda () (adapt ADAPT-INIT 0 0 0 0))))
(define scale-factor (adapt-scale a))
(define r (*drift1 dist value scale-factor))
(vprintf "DRIFTED from ~e to ~e\n" value (car r))
r)
(define/override (propose2* key zones old-dist new-dist old-value)
(define a (hash-ref! table key (lambda () (adapt ADAPT-INIT 0 0 0 0))))
(define scale-factor (adapt-scale a))
(define fd (*drift-dist new-dist old-value scale-factor))
(define new-value (dist-sample fd))
(define rd (*drift-dist old-dist new-value scale-factor))
(define F (dist-pdf fd new-value #t))
(define R (dist-pdf rd old-value #t))
(vprintf "DRIFTED from ~e to ~e\n" old-value new-value)
(vprintf " R = ~s, F = ~s\n" (exp R) (exp F))
(list* new-value R F))
(define/override (feedback key success?)
(define a (hash-ref table key))
(set-adapt-batch-trials! a (add1 (adapt-batch-trials a)))
(when success? (set-adapt-batch-successes! a (add1 (adapt-batch-successes a))))
(when (> (adapt-batch-trials a) ADAPT-BATCH)
(cond [(> (adapt-batch-successes a) (* ADAPT-GOAL-HI (adapt-batch-trials a))) ;; high
;; (eprintf "increasing scale for ~s from ~s\n" key (adapt-scale a))
(set! incr-count (add1 incr-count))
(set-adapt-scale! a (* ADAPT-UP (adapt-scale a)))]
[(< (adapt-batch-successes a) (* ADAPT-GOAL-LO (adapt-batch-trials a))) ;; low
;; (eprintf "decreasing scale for ~s from ~s\n" key (adapt-scale a))
(set! decr-count (add1 decr-count))
(set-adapt-scale! a (* ADAPT-DOWN (adapt-scale a)))]
[else
(set! stay-count (add1 stay-count))
(void)])
(when (> (adapt-scale a) ADAPT-MAX)
(unless warned-out-of-range?
(eprintf "adaptive-drift-proposal: scale increased out of range\n")
(set! warned-out-of-range? #t))
(set-adapt-scale! a ADAPT-MAX))
(when (< (adapt-scale a) ADAPT-MIN)
(unless warned-out-of-range?
(eprintf "adaptive-drift-proposal: scale decreased out of range\n")
(set! warned-out-of-range? #t))
(set-adapt-scale! a ADAPT-MIN))
(set-adapt-old-trials! a (+ (adapt-old-trials a) (adapt-batch-trials a)))
(set-adapt-old-successes! a (+ (adapt-old-successes a) (adapt-batch-successes a)))
(set-adapt-batch-trials! a 0)
(set-adapt-batch-successes! a 0)))
))
;; ============================================================
(define (propose:resample dist value)
;; Just resample from same dist.
;; Then Kt(x|x') = Kt(x) = (dist-pdf dist value)
;; and Kt(x'|x) = Kt(x') = (dist-pdf dist value*)
(define value* (dist-sample dist))
(define R (dist-pdf dist value #t))
(define F (dist-pdf dist value* #t))
(when (verbose?)
(vprintf "RESAMPLED from ~e to ~e\n" value value*)
(vprintf " R = ~s, F = ~s\n" (exp R) (exp F)))
(cons value* (- R F)))
(define (propose2:resample old-dist new-dist old-value)
;; Just resample from current-dist.
;; Then Q(x|x') = Q(x) = (dist-pdf old-dist old-value)
;; and Q(x'|x) = Q(x') = (dist-pdf new-dist new-value)
(define new-value (dist-sample new-dist))
(define R (dist-pdf old-dist old-value #t))
(define F (dist-pdf new-dist new-value #t))
(when (verbose?)
(vprintf "RESAMPLED from ~e to ~e\n" old-value new-value)
(vprintf " R = ~s, F = ~s\n" (exp R) (exp F)))
(list* new-value R F))
| false |
e6cacc9d398df35696d4e084e5faafe535d9b1c0 | ea0854849ff547901c62c20e4f1034966969d939 | /workset-loop.rkt | 6154c9ae3eac311ae8723ad495b03f4de19ae1ab | []
| no_license | danking/racket-utils | 40272be49645050eb21af26b80ed6cc95f9a8731 | 90d5c86ba992a87138cb8f14a86ecf852966aca7 | refs/heads/master | 2020-04-06T06:37:21.110912 | 2014-07-23T16:13:33 | 2014-07-23T16:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 870 | rkt | workset-loop.rkt | #lang racket
(require "set-utilities.rkt")
(provide (all-defined-out))
;; - can I make current, workset, and value into match patterns?
(define-syntax workset-loop!
(syntax-rules ()
((_ initial-set (current workset)
body ...)
(let loop ((workset initial-set))
(unless (set-empty? workset)
(let*-values (((current workset) (set-get-one/rest workset))
((w) (let () body ...)))
(loop w)))))))
(define-syntax workset-loop
(syntax-rules ()
((_ initial-set initial-value (current workset value)
body ...)
(let loop ((workset initial-set)
(value initial-value))
(if (set-empty? workset)
value
(let*-values (((current workset) (set-get-one/rest workset))
((w v) (let () body ...)))
(loop w v)))))))
| true |
31439bab98629421199a7b0936638c65d021ec77 | 14be9e4cde12392ebc202e69ae87bbbedd2fea64 | /CSC324/lab/myfoldlab.rkt | 174b192456861db8396652a5d6c606afd5ff81c0 | [
"LicenseRef-scancode-unknown-license-reference",
"GLWTPL"
]
| permissive | zijuzhang/Courses | 948e9d0288a5f168b0d2dddfdf825b4ef4ef4e1e | 71ab333bf34d105a33860fc2857ddd8dfbc8de07 | refs/heads/master | 2022-01-23T13:31:58.695290 | 2019-08-07T03:13:09 | 2019-08-07T03:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,475 | rkt | myfoldlab.rkt | #lang racket
(require (except-in rackunit fail))
; INTRODUCING FOLD
; in racket, every base function that /can/ be variadic likely already is.
; but let's say we only had the binary forms of some classic variadic functions:
(define (my-add a b) (+ a b))
(define (my-prod a b) (* a b))
(define (my-string-append a b) (string-append a b))
; how can we use higher-order programming to recover the variadic versions
; in a systematic way? below you will implement my-fold, an operation which
; takes a binary function and a list and 'folds' that function over the list
; let's begin more concretely:
; (uncomment the check-equal?s as you implement each function)
; first, define var-add to return the sum of a list of numbers
; use my-add from above. do not use + !!!
(define (var-add ls)
(if (empty? ls)
(void) ; ★ replace (void) with something
(void))) ; ★ replace (void) with something
; second, define var-prod to return the product of a list of numbers
; use my-add from above. do not use + !!!
(define (var-prod ls)
(if (empty? ls)
(void) ; ★ replace (void) with something
(void))) ; ★ replace (void) with something
#;(check-equal? (var-add '(1 2 3 4)) 10)
#;(check-equal? (var-prod '(1 2 3 4)) 10)
; abtracting what you've learned above, implement my-fold
; which takes a binary operation (bin-op) and a 'base' value
; and returns a function which can 'fold' that operation over a list
(define ((my-fold bin-op base) ls)
(if (empty? ls)
(void) ; ★ replace (void) with something
(void))) ; ★ replace (void) with something
#;(check-equal? ((my-fold my-add 0) '(1 2 3 4)) 10)
#;(check-equal? ((my-fold my-prod 1) '(1 2 3 4)) '24)
#;(check-equal? ((my-fold my-string-append "") '("a" "b" "c" "d")) "abcd")
; now let's get slightly fancier.
; cons is the constuctor for the list type. it takes two
; arguments, a value and a list, and prepends that value onto the list
; note that (cons a b) is the same as (list* a b)
; implement 'my-list', which does the same thing as 'list'
; using only my-fold and cons
; note that . below allows us to define a variadic function
; whose arguments are captured as a list called 'ls'
(define (my-list . ls)
(void)) ; ★ replace (void) with something
#;(check-equal? (my-list 1 2 3 4) (list 1 2 3 4))
; now implement 'my-map', which does the same thing as 'map',
; using only my-fold and cons (and lambda)
; if you have trouble writing in directly, try to seperately define the
; function which you're going to fold over:
; apply-and-prepend should take a function f, and return a binary function
; which takes a value and a list and returns the result of applying that
; function to the value, and the prepending the returned value to a list
; (see the check-expect)
; you should only have to use cons and function application
(define ((apply-and-prepend f) element ls)
(void)) ; ★ replace (void) with something
#;(check-equal? ((apply-and-prepend sqr) 2 '(1 1 1)) '(4 1 1 1))
#;(check-equal? ((apply-and-prepend not) #t '(1 1 1)) '(#f 1 1 1))
; now use only cons and my-fold and lambda
; (or only my-fold and apply-and-prepend)
; to write my-map:
(define (my-map f ls)
(void)) ; ★ replace (void) with something
#;(check-equal? (my-map sqr '(1 2 3 4)) '(1 4 9 16))
; note that there are many variations on fold.
; we've implemented right fold, called foldr in racket
; (in many languages, foldr is simply called 'fold')
; sometimes we may want to fold from the left as well (foldl).
; for associative operations like my-add and my-prod these are
; going to behave identically, but for non-associative operations
; like subtraction, foldr and foldl are different:
(foldr - 0 '(1 2 3 4))
(foldl - 0 '(1 2 3 4))
; (note that the racket syntax is a bit different than i used above)
; now use foldl and cons to implement my-reverse, which does the same thing as reverse
(define (my-reverse ls)
(void)) ; ★ replace (void) with something
#;(check-equal? (my-reverse '(1 2 3 4)) '(4 3 2 1))
; also for some situations it doesn't make sense to fold over an
; empty list, or maybe not a list with a single element either
; in such a case we might have a version of fold which doesn't take a base
; and simply produces an error if the list is too short
; finally, just as racket allows us to map over multiple lists
; we can make a variadic fold which takes n lists, and an function
; which takes n+1 values
; that's it!
| false |
88d6a309714e5229bee6c94097294f2f9ec60268 | 471a04fa9301455c51a890b8936cc60324a51f27 | /srfi-lib/srfi/%3a11.rkt | 0017499f91d62d0dace65d8eb17c72713f318d0d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
]
| permissive | racket/srfi | e79e012fda6d6bba1a9445bcef461930bc27fde8 | 25eb1c0e1ab8a1fa227750aa7f0689a2c531f8c8 | refs/heads/master | 2023-08-16T11:10:38.100847 | 2023-02-16T01:18:44 | 2023-02-16T12:34:27 | 27,413,027 | 10 | 10 | NOASSERTION | 2023-09-14T14:40:51 | 2014-12-02T03:22:45 | HTML | UTF-8 | Racket | false | false | 34 | rkt | %3a11.rkt | #lang s-exp srfi/provider srfi/11
| false |
1ad366a3bb97e944be960ec3e398d8e8e6ecc4cd | 631764b5f40576a6857e7d31d207a5ece7ccba43 | /Scheme/Lists-And-Multiple-Arguments/remove-last.rkt | e8729beda6476c8782177b621c2b87bbb0b47291 | []
| no_license | Ralitsa-Vuntsova/fp | ea37a40aaf3c42a70a1abc5fdb6736b875393543 | 7cca3819079de98108c70aed4d79f42c1fc294cc | refs/heads/main | 2023-06-07T03:24:18.405190 | 2021-06-28T15:59:34 | 2021-06-28T15:59:34 | 381,085,860 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 227 | rkt | remove-last.rkt | ; Да се напише функция, която премахва последния елемент от списък.
(define (remove-last lst)
(if (null? (cdr lst)) '()
(cons (car lst) (remove-last (cdr lst)))))
| false |
5b5e94f63d792e6541a4c706d971ffe6a56a9af0 | d9276fbd73cdec7a5a4920e46af2914f8ec3feb1 | /data/scheme/srcdoc.rkt | ee977a16f9c2adfe42dccc166a085e584828b7ca | []
| no_license | CameronBoudreau/programming-language-classifier | 5c7ab7d709b270f75269aed1fa187e389151c4f7 | 8f64f02258cbab9e83ced445cef8c1ef7e5c0982 | refs/heads/master | 2022-10-20T23:36:47.918534 | 2016-05-02T01:08:13 | 2016-05-02T01:08:13 | 57,309,188 | 1 | 1 | null | 2022-10-15T03:50:41 | 2016-04-28T14:42:50 | C | UTF-8 | Racket | false | false | 33,328 | rkt | srcdoc.rkt | #lang racket/base
(require racket/contract/base
(for-syntax racket/base
racket/require-transform
racket/provide-transform
syntax/stx
syntax/private/modcollapse-noctc
syntax/parse))
(provide for-doc require/doc
provide/doc ; not needed anymore
thing-doc
parameter-doc
proc-doc
proc-doc/names
struct-doc
struct*-doc
form-doc
generate-delayed-documents
begin-for-doc)
(begin-for-syntax
(define requires null)
(define doc-body null)
(define doc-exprs null)
(define generated? #f)
(define delayed? #f)
(define (add-requires!/decl specs)
(unless delayed?
(syntax-local-lift-module-end-declaration
#`(begin-for-syntax (add-relative-requires! (#%variable-reference)
(quote-syntax #,specs)))))
(with-syntax ([(spec ...) (syntax-local-introduce specs)])
;; Using `combine-in` protects `spec` against
;; matching `(op arg ...)` in `doc-submodule`:
(add-requires! #'((combine-in spec) ...))))
(define (add-relative-requires! varref specs)
(define mpi (variable-reference->module-path-index varref))
(define-values (name base) (module-path-index-split mpi))
(if name
(add-requires!
(with-syntax ([(spec ...) specs]
[rel-to (collapse-module-path-index
mpi
(build-path (or (current-load-relative-directory)
(current-directory))
"here.rkt"))])
#'((relative-in rel-to spec) ...)))
(add-requires! specs)))
(define (add-requires! specs)
(set! requires (cons specs requires)))
(define (generate-doc-submodule!)
(unless generated?
(set! generated? #t)
(syntax-local-lift-module-end-declaration #'(doc-submodule)))))
(define-syntax for-doc
(make-require-transformer
(lambda (stx)
(syntax-case stx ()
[(_ spec ...)
(add-requires!/decl #'(spec ...))])
(values null null))))
(define-syntax (doc-submodule stx)
(define (shift-and-introduce s)
(syntax-local-introduce
(syntax-shift-phase-level s #f)))
(with-syntax ([((req ...) ...)
(map (lambda (rs)
(map (lambda (r)
(syntax-case r ()
[(op arg ...)
(with-syntax ([(arg ...)
(map shift-and-introduce
(syntax->list #'(arg ...)))])
#'(op arg ...))]
[else
(shift-and-introduce r)]))
(syntax->list rs)))
(reverse requires))]
[(expr ...)
(map shift-and-introduce (reverse doc-exprs))]
[doc-body
(map shift-and-introduce (reverse doc-body))])
;; This module will be required `for-template':
(if delayed?
;; delayed mode: return syntax objects to drop into context:
#'(begin-for-syntax
(module* srcdoc #f
(require (for-syntax racket/base syntax/quote))
(begin-for-syntax
(provide get-docs)
(define (get-docs)
(list (quote-syntax (req ... ...))
(quote-syntax (expr ...))
(quote-syntax/keep-srcloc #:source 'doc doc-body))))))
;; normal mode: return an identifier that holds the document:
(with-syntax ([((id d) ...) #'doc-body])
#'(begin-for-syntax
(module* srcdoc #f
(require req ... ...)
expr ...
(define docs (list (cons 'id d) ...))
(require (for-syntax racket/base))
(begin-for-syntax
(provide get-docs)
(define (get-docs)
#'docs))))))))
(define-syntax (require/doc stx)
(syntax-case stx ()
[(_ spec ...)
(add-requires!/decl #'(spec ...))
#'(begin)]))
(define-for-syntax (do-provide/doc stx modes)
(let ([forms (list stx)])
(with-syntax ([((for-provide/contract (req ...) d id) ...)
(map (lambda (form)
(syntax-case form ()
[(id . _)
(identifier? #'id)
(let ([t (syntax-local-value #'id (lambda () #f))])
(unless (provide/doc-transformer? t)
(raise-syntax-error
#f
"not bound as a provide/doc transformer"
stx
#'id))
(let* ([i (make-syntax-introducer)]
[i2 (lambda (x) (syntax-local-introduce (i x)))])
(let-values ([(p/c d req/d id)
((provide/doc-transformer-proc t)
(i (syntax-local-introduce form)))])
(list (i2 p/c) (i req/d) (i d) (i id)))))]
[_
(raise-syntax-error
#f
"not a provide/doc sub-form"
stx
form)]))
forms)])
(with-syntax ([(p/c ...)
(map (lambda (form f)
(if (identifier? f)
f
(quasisyntax/loc form
(contract-out #,f))))
forms
(syntax->list #'(for-provide/contract ...)))])
(generate-doc-submodule!)
(set! doc-body (append (reverse (syntax->list #'((id d) ...)))
doc-body))
(set! requires (cons #'(req ... ...) requires))
(pre-expand-export #'(combine-out p/c ...) modes)))))
(define-syntax (begin-for-doc stx)
(syntax-case stx ()
[(_ d ...)
(set! doc-exprs (append (reverse (syntax->list
(syntax-local-introduce
#'(d ...))))
doc-exprs))
#'(begin)]))
(define-syntax-rule (provide/doc form ...)
(provide form ...))
(provide define-provide/doc-transformer
(for-syntax
provide/doc-transformer?
provide/doc-transformer-proc))
(begin-for-syntax
(define-struct provide/doc-transformer (proc)
#:property
prop:provide-pre-transformer
(lambda (self)
(lambda (stx mode)
(do-provide/doc stx mode)))))
(define-syntax-rule (define-provide/doc-transformer id rhs)
(define-syntax id
(make-provide/doc-transformer rhs)))
(module transformers racket/base
(require (for-template racket/base racket/contract)
racket/contract)
(provide proc-doc-transformer proc-doc/names-transformer)
(define (remove->i-deps stx-lst arg?)
(let loop ([stx-lst stx-lst])
(cond
[(null? stx-lst) '()]
[else
(define fst (car stx-lst))
(syntax-case fst ()
[kwd
(and arg? (keyword? (syntax-e #'kwd)))
(let ()
(when (null? (cdr stx-lst))
(raise-syntax-error 'proc-doc "expected something to follow keyword" stx-lst))
(define snd (cadr stx-lst))
(syntax-case snd ()
[(id (id2 ...) ctc)
(cons #'(kwd id ctc) (loop (cddr stx-lst)))]
[(id ctc)
(cons #'(kwd id ctc) (loop (cddr stx-lst)))]
[else
(raise-syntax-error 'proc-doc "unknown argument spec in ->i" snd)]))]
[(id (id2 ...) ctc)
(cons #'(id ctc) (loop (cdr stx-lst)))]
[(id ctc)
(cons #'(id ctc) (loop (cdr stx-lst)))]
[else
(raise-syntax-error 'proc-doc (if arg? "unknown argument spec in ->i" "unknown result spec in ->i") fst)])])))
(define (proc-doc-transformer stx)
(syntax-case stx ()
[(_ id contract . desc+stuff)
(let ()
(define (one-desc desc+stuff)
(syntax-case desc+stuff ()
[(desc) #'desc]
[() (raise-syntax-error 'proc-doc "expected a description expression" stx)]
[(a b . c) (raise-syntax-error 'proc-doc "expected just a single description expression" stx #'a)]))
(define (parse-opts opts desc+stuff)
(syntax-case opts ()
[() #`(() #,(one-desc desc+stuff))]
[(opt ...)
(with-syntax ([(opt ...) (remove->i-deps (syntax->list #'(opt ...)) #t)])
(syntax-case desc+stuff ()
[((defaults ...) . desc+stuff)
(let ()
(define def-list (syntax->list #'(defaults ...)))
(define opt-list (syntax->list #'(opt ...)))
(unless (= (length def-list) (length opt-list))
(raise-syntax-error 'proc-doc
(format "expected ~a default values, but got ~a"
(length opt-list) (length def-list))
stx
opts))
#`(#,(for/list ([opt (in-list opt-list)]
[def (in-list def-list)])
(syntax-case opt ()
[(id ctc)
#`(id ctc #,def)]
[(kwd id ctc)
#`(kwd id ctc #,def)]))
#,(one-desc #'desc+stuff)))]))]))
(define-values (header result body-extras desc)
(syntax-case #'contract (->d ->i -> values)
[(->d (req ...) () (values [name res] ...))
(values #'(id req ...) #'(values res ...) #'() (one-desc #'desc+stuff))]
[(->d (req ...) () #:pre-cond condition (values [name res] ...))
(values #'(id req ...) #'(values res ...) #'((bold "Pre-condition: ") (racket condition) "\n" "\n") (one-desc #'desc+stuff))]
[(->d (req ...) () [name res])
(values #'(id req ...) #'res #'() (one-desc #'desc+stuff))]
[(->d (req ...) () #:pre-cond condition [name res])
(values #'(id req ...) #'res #'((bold "Pre-condition: ") (racket condition) "\n" "\n" ) (one-desc #'desc+stuff))]
[(->d (req ...) () #:rest rest rest-ctc [name res])
(values #'(id req ... [rest rest-ctc] (... ...)) #'res #'() (one-desc #'desc+stuff))]
[(->d (req ...) (one more ...) whatever)
(raise-syntax-error
#f
(format "unsupported ->d contract form for ~a, optional arguments non-empty, must use proc-doc/names"
(syntax->datum #'id))
stx
#'contract)]
[(->d whatever ...)
(raise-syntax-error
#f
(format "unsupported ->d contract form for ~a" (syntax->datum #'id))
stx
#'contract)]
[(->i (req ...) (opt ...) (values ress ...))
(with-syntax ([(req ...) (remove->i-deps (syntax->list #'(req ...)) #t)]
[((opt ...) desc) (parse-opts #'(opt ...) #'desc+stuff)]
[([name res] ...) (remove->i-deps (syntax->list #'(req ...)) #f)])
(values #'(id req ... opt ...) #'(values res ...) #'() #'desc))]
[(->i (req ...) (opt ...) #:pre (pre-id ...) condition (values ress ...))
(with-syntax ([(req ...) (remove->i-deps (syntax->list #'(req ...)) #t)]
[((opt ...) desc) (parse-opts #'(opt ...) #'desc+stuff)]
[([name res] ...) (remove->i-deps (syntax->list #'(req ...)) #f)])
(values #'(id req ... opt ...) #'(values res ...) #'((bold "Pre-condition: ") (racket condition) "\n" "\n") #'desc))]
[(->i (req ...) (opt ...) res)
(with-syntax ([(req ...) (remove->i-deps (syntax->list #'(req ...)) #t)]
[((opt ...) desc) (parse-opts #'(opt ...) #'desc+stuff)]
[([name res]) (remove->i-deps (list #'res) #f)])
(values #'(id req ... opt ...) #'res #'() #'desc))]
[(->i (req ...) (opt ...) #:pre (pre-id ...) condition [name res])
(with-syntax ([(req ...) (remove->i-deps (syntax->list #'(req ...)) #t)]
[((opt ...) desc) (parse-opts #'(opt ...) #'desc+stuff)]
[([name res]) (remove->i-deps (list #'res) #f)])
(values #'(id req ... opt ...) #'res #'((bold "Pre-condition: ") (racket condition) "\n" "\n" ) #'desc))]
[(->i (req ...) (opt ...) #:rest rest res)
(with-syntax ([(req ...) (remove->i-deps (syntax->list #'(req ...)) #t)]
[((opt ...) desc) (parse-opts #'(opt ...) #'desc+stuff)]
[([name-t rest-ctc]) (remove->i-deps (list #'rest) #t)]
[([name res]) (remove->i-deps (list #'res) #f)])
(values #'(id req ... opt ... [name-t rest-ctc] (... ...)) #'res #'() #'desc))]
[(->i whatever ...)
(raise-syntax-error
#f
(format "unsupported ->i contract form for ~a" (syntax->datum #'id))
stx
#'contract)]
[(-> result)
(values #'(id) #'result #'() (one-desc #'desc+stuff))]
[(-> whatever ...)
(raise-syntax-error
#f
(format "unsupported -> contract form for ~a, must use proc-doc/names if there are arguments"
(syntax->datum #'id))
stx
#'contract)]
[(id whatever ...)
(raise-syntax-error
#f
(format "unsupported ~a contract form (unable to synthesize argument names)" (syntax->datum #'id))
stx
#'contract)]))
(values
#'[id contract]
#`(defproc #,header #,result #,@body-extras #,@desc)
#'(scribble/manual
racket/base) ; for `...'
#'id))]))
(define (proc-doc/names-transformer stx)
(syntax-case stx ()
[(_ id contract names desc)
(with-syntax ([header
(syntax-case #'(contract names) (->d -> ->* values case->)
[((-> ctcs ... result) (arg-names ...))
(begin
(unless (= (length (syntax->list #'(ctcs ...)))
(length (syntax->list #'(arg-names ...))))
(raise-syntax-error #f "mismatched argument list and domain contract count" stx))
#'([(id (arg-names ctcs) ...) result]))]
[((->* (mandatory ...) (optional ...) result)
names)
(syntax-case #'names ()
[((mandatory-names ...)
((optional-names optional-default) ...))
(let ([build-mandatories/optionals
(λ (names contracts extras)
(let ([names-length (length names)]
[contracts-length (length contracts)])
(let loop ([contracts contracts]
[names names]
[extras extras])
(cond
[(and (null? names) (null? contracts)) '()]
[(or (null? names) (null? contracts))
(raise-syntax-error #f
(format "mismatched ~a argument list count and domain contract count (~a)"
(if extras "optional" "mandatory")
(if (null? names)
"ran out of names"
"ran out of contracts"))
stx)]
[else
(let ([fst-name (car names)]
[fst-ctc (car contracts)])
(if (keyword? (syntax-e fst-ctc))
(begin
(unless (pair? (cdr contracts))
(raise-syntax-error #f
"keyword not followed by a contract"
stx))
(cons (if extras
(list fst-ctc fst-name (cadr contracts) (car extras))
(list fst-ctc fst-name (cadr contracts)))
(loop (cddr contracts)
(cdr names)
(if extras
(cdr extras)
extras))))
(cons (if extras
(list fst-name fst-ctc (car extras))
(list fst-name fst-ctc))
(loop (cdr contracts) (cdr names) (if extras
(cdr extras)
extras)))))]))))])
#`([(id #,@(build-mandatories/optionals (syntax->list #'(mandatory-names ...))
(syntax->list #'(mandatory ...))
#f)
#,@(build-mandatories/optionals (syntax->list #'(optional-names ...))
(syntax->list #'(optional ...))
(syntax->list #'(optional-default ...))))
result]))]
[(mandatory-names optional-names)
(begin
(syntax-case #'mandatory-names ()
[(mandatory-names ...)
(andmap identifier? (syntax->list #'(mandatory-names ...)))]
[x
(raise-syntax-error #f "mandatory names should be a sequence of identifiers"
stx
#'mandatory-names)])
(syntax-case #'optional-names ()
[((x y) ...)
(andmap identifier? (syntax->list #'(x ... y ...)))]
[((x y) ...)
(for-each
(λ (var)
(unless (identifier? var)
(raise-syntax-error #f "expected an identifier in the optional names" stx var)))
(syntax->list #'(x ... y ...)))]
[(a ...)
(for-each
(λ (a)
(syntax-case stx ()
[(x y) (void)]
[other
(raise-syntax-error #f "expected an sequence of two idenfiers" stx #'other)]))
(syntax->list #'(a ...)))]))]
[x
(raise-syntax-error
#f
"expected two sequences, one of mandatory names and one of optionals"
stx
#'x)])]
[((case-> (-> doms ... rng) ...)
((args ...) ...))
(begin
(unless (= (length (syntax->list #'((doms ...) ...)))
(length (syntax->list #'((args ...) ...))))
(raise-syntax-error #f
"number of cases and number of arg lists do not have the same size"
stx))
(for-each
(λ (doms args)
(unless (= (length (syntax->list doms))
(length (syntax->list args)))
(raise-syntax-error #f "mismatched case argument list and domain contract" stx
#f
(list doms args))))
(syntax->list #'((doms ...) ...))
(syntax->list #'((args ...) ...)))
#'([(id (args doms) ...) rng] ...))]
[else
(raise-syntax-error
#f
"unsupported procedure contract form (no argument names)"
stx
#'contract)])])
(values
#'[id contract]
#'(defproc* header . desc)
#'((only-in scribble/manual defproc*))
#'id))])))
(require (for-syntax (submod "." transformers)))
(define-provide/doc-transformer proc-doc proc-doc-transformer)
(define-provide/doc-transformer proc-doc/names proc-doc/names-transformer)
(define-provide/doc-transformer parameter-doc
(lambda (stx)
(syntax-case stx (parameter/c)
[(_ id (parameter/c contract) arg-id desc)
(begin
(unless (identifier? #'arg-id)
(raise-syntax-error 'parameter-doc
"expected an identifier"
stx
#'arg-id))
(unless (identifier? #'id)
(raise-syntax-error 'parameter-doc
"expected an identifier"
stx
#'id))
(values
#'[id (parameter/c contract)]
#'(defparam id arg-id contract . desc)
#'((only-in scribble/manual defparam))
#'id))])))
(define-for-syntax (struct-doc-transformer stx result-form)
(syntax-case stx ()
[(_ struct-name ([field-name contract-expr-datum] ...) . stuff)
(let ()
(define the-name #f)
(syntax-case #'struct-name ()
[x (identifier? #'x) (set! the-name #'x)]
[(x y) (and (identifier? #'x) (identifier? #'y))
(set! the-name #'x)]
[_
(raise-syntax-error #f
"expected an identifier or sequence of two identifiers"
stx
#'struct-name)])
(for ([f (in-list (syntax->list #'(field-name ...)))])
(unless (identifier? f)
(raise-syntax-error #f
"expected an identifier"
stx
f)))
(define omit-constructor? #f)
(define-values (ds-args desc)
(let loop ([ds-args '()]
[stuff #'stuff])
(syntax-case stuff ()
[(#:mutable . more-stuff)
(loop (cons (stx-car stuff) ds-args)
#'more-stuff)]
[(#:inspector #f . more-stuff)
(loop (list* (stx-car (stx-cdr stuff))
(stx-car stuff)
ds-args)
#'more-stuff)]
[(#:prefab . more-stuff)
(loop (cons (stx-car stuff) ds-args)
#'more-stuff)]
[(#:transparent . more-stuff)
(loop (cons (stx-car stuff) ds-args)
#'more-stuff)]
[(#:constructor-name id . more-stuff)
(loop (list* (stx-car (stx-cdr stuff))
(stx-car stuff)
ds-args)
#'more-stuff)]
[(#:extra-constructor-name id . more-stuff)
(loop (list* (stx-car (stx-cdr stuff))
(stx-car stuff)
ds-args)
#'more-stuff)]
[(#:omit-constructor . more-stuff)
(begin
(set! omit-constructor? #t)
(loop (cons (stx-car stuff) ds-args)
#'more-stuff))]
[(x . more-stuff)
(keyword? (syntax-e #'x))
(raise-syntax-error #f
"unknown keyword"
stx
(stx-car stuff))]
[(desc)
(values (reverse ds-args) #'desc)]
[_
(raise-syntax-error #f "bad syntax" stx)])))
(values
#`(struct struct-name ((field-name contract-expr-datum) ...)
#,@(if omit-constructor?
'(#:omit-constructor)
'()))
#`(#,result-form struct-name ([field-name contract-expr-datum] ...)
#,@(reverse ds-args)
#,@desc)
#`((only-in scribble/manual #,result-form))
the-name))]))
(define-provide/doc-transformer struct-doc
(λ (stx)
(struct-doc-transformer stx #'defstruct)))
(define-provide/doc-transformer struct*-doc
(λ (stx)
(struct-doc-transformer stx #'defstruct*)))
(define-provide/doc-transformer thing-doc
(lambda (stx)
(syntax-case stx ()
[(_ id contract desc)
(begin
(unless (identifier? #'id)
(raise-syntax-error 'parameter/doc
"expected an identifier"
stx
#'id))
(values
#'[id contract]
#'(defthing id contract . desc)
#'((only-in scribble/manual defthing))
#'id))])))
(begin-for-syntax
(define-splicing-syntax-class kind-kw
#:description "#:kind keyword"
(pattern (~seq #:kind kind)
#:with (kind-seq ...) #'(#:kind kind))
(pattern (~seq)
#:with (kind-seq ...) #'()))
(define-splicing-syntax-class link-target?-kw
#:description "#:link-target? keyword"
(pattern (~seq #:link-target? expr)
#:with (link-target-seq ...) #'(#:link-target? expr))
(pattern (~seq)
#:with (link-target-seq ...) #'()))
(define-splicing-syntax-class id-kw
#:description "#:id keyword"
(pattern (~seq #:id [defined-id:id defined-id-expr])
#:with (id-seq ...) #'(#:id [defined-id:id defined-id-expr]))
(pattern (~seq #:id defined-id:id)
#:with (id-seq ...) #'(#:id defined-id))
(pattern (~seq #:id other)
#:with defined-id #'#f
#:with (id-seq ...) #'(#:id other))
(pattern (~seq)
#:with defined-id #'#f
#:with (id-seq ...) #'()))
(define-splicing-syntax-class literals-kw
#:description "#:literals keyword"
(pattern (~seq #:literals l)
#:with (literals-seq ...) #'(#:literals l))
(pattern (~seq)
#:with (literals-seq ...) #'()))
(define-splicing-syntax-class subs-kw
#:description "#:grammar keyword"
(pattern (~seq #:grammar g)
#:with (grammar-seq ...) #'(#:grammar g))
(pattern (~seq)
#:with (grammar-seq ...) #'()))
(define-splicing-syntax-class contracts-kw
#:description "#:contracts keyword"
(pattern (~seq #:contracts c)
#:with (contracts-seq ...) #'(#:contracts c))
(pattern (~seq)
#:with (contracts-seq ...) #'())))
(define-provide/doc-transformer form-doc
(lambda (stx)
(syntax-parse stx
[(_ k:kind-kw lt:link-target?-kw d:id-kw l:literals-kw spec
subs:subs-kw c:contracts-kw desc)
(with-syntax ([id (if (syntax-e #'d.defined-id)
#'d.defined-id
(syntax-case #'spec ()
[(id . rest)
(identifier? #'id)
#'id]
[_ #'unknown]))])
(values
#'id
#'(defform
k.kind-seq ...
lt.link-target-seq ...
d.id-seq ...
l.literals-seq ...
spec
subs.grammar-seq ...
c.contracts-seq ...
. desc)
#'((only-in scribble/manual defform))
#'id))])))
(define-syntax (generate-delayed-documents stx)
(syntax-case stx ()
[(_)
(begin
(set! delayed? #t)
#'(begin))]))
(module+ test
(require (submod ".." transformers)
rackunit
racket/contract)
(define (try-docs transformer input)
(define-values (_0 docs _1 _2) (transformer input))
(syntax->datum docs))
(check-equal? (try-docs proc-doc-transformer #'(_ f (-> void?) ()))
'(defproc (f) void?))
(check-equal? (try-docs proc-doc-transformer #'(_ f (->i ([x integer?]) () [result void?]) ()))
'(defproc (f [x integer?]) void?))
(check-equal? (try-docs proc-doc-transformer #'(_ f (->i ([x integer?] #:y [y boolean?]) () [res void?]) ()))
'(defproc (f [x integer?] [#:y y boolean?]) void?))
(check-equal? (try-docs proc-doc-transformer #'(_ f (->i ([x integer?]) ([y boolean?] [z char?]) [result void?]) (#t #\x) ()))
'(defproc (f [x integer?] [y boolean? #t] [z char? #\x]) void?))
(check-equal? (try-docs proc-doc-transformer #'(_ f (->i ([x integer?] #:y [y boolean?]) ([z char?] #:w [w string?]) [res void?]) (#\a "b") ()))
'(defproc (f [x integer?] [#:y y boolean?] [z char? #\a] [#:w w string? "b"]) void?))
(check-equal? (try-docs proc-doc-transformer
#'(_ g
(->i ([str string?])
()
#:rest [rest (listof any/c)]
[res (str) integer?])
()))
'(defproc (g (str string?) (rest (listof any/c)) ...) integer?))
(check-equal? (try-docs proc-doc/names-transformer #'(_ f (-> integer? char? boolean?) (a b) ()))
'(defproc* (((f [a integer?] [b char?]) boolean?))))
(check-equal? (try-docs proc-doc/names-transformer #'(_ f (->* (integer? char?) () boolean?) ((a b) ()) ()))
'(defproc* (((f [a integer?] [b char?]) boolean?))))
(check-equal? (try-docs proc-doc/names-transformer #'(_ f (->* (integer? char?) (string? number?) boolean?) ((a b) ((c "a") (d 11))) ()))
'(defproc* (((f [a integer?] [b char?] [c string? "a"] [d number? 11]) boolean?))))
(check-equal? (try-docs proc-doc/names-transformer #'(_ f (case-> (-> integer? char?) (-> string? number? boolean? void?)) ((a) (b c d)) ()))
'(defproc* (((f [a integer?]) char?)
((f [b string?] [c number?] [d boolean?]) void?)))))
| true |
1ee9c9a4a9f27c046f70b86a622fd7c0af7447f5 | d38b44cc1e913d3906f92a3f5bf3c6afad7b4aa5 | /dyn-scope-is-bad/lang/reader.rkt | 3361c07388b0cc141afee125c34d41c5c35668d4 | []
| no_license | shriram/smol | 41cb00d908a8f75a8edf796e1ada8830e5665c68 | da99591c7c4bb58ece6a1c935d95fbd2d64685b1 | refs/heads/master | 2022-12-22T03:56:51.031967 | 2022-12-02T00:20:53 | 2022-12-02T00:20:53 | 204,587,082 | 12 | 3 | null | 2022-11-08T22:24:33 | 2019-08-27T00:42:00 | Racket | UTF-8 | Racket | false | false | 65 | rkt | reader.rkt | #lang s-exp syntax/module-reader
smol/dyn-scope-is-bad/semantics
| false |
dde83b3bb3ece9595672c5b6a327b56b4aff811a | eb48ced56feaf37d1f1439589894353a5d0a50f8 | /cKanren/tests/quines.rkt | 69126b999a44d2fb97aba0acc9dfb120792edfd9 | [
"MIT"
]
| permissive | ReinoutStevens/cKanren | f40eaad090865f4b326d35e4f90738ff985aefbb | b388b60c5487bce1d0ea84a0149347197e80643a | refs/heads/master | 2020-12-27T09:13:45.121481 | 2013-09-08T22:31:39 | 2013-09-08T22:31:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 28,302 | rkt | quines.rkt | #lang racket
(require
"../ck.rkt"
"../absento.rkt"
"../tree-unify.rkt"
"../neq.rkt"
"../tester.rkt"
(for-syntax "../ck.rkt"))
(provide test-quines test-quines-long)
(begin-for-syntax
(define strat 'dfs)
(search-strategy strat))
(define-lazy-goal (eval-expo exp env val)
;; (define (eval-expo exp env val)
(conde
((fresh (v)
(== `(quote ,v) exp)
(not-in-envo 'quote env)
(absento 'closure v)
(== v val)))
((fresh (a*)
(== `(list . ,a*) exp)
(not-in-envo 'list env)
(absento 'closure a*)
(proper-listo a* env val)))
((symbolo exp) (lookupo exp env val))
((fresh (rator rand x body env^ a)
(== `(,rator ,rand) exp)
(eval-expo rator env `(closure ,x ,body ,env^))
(eval-expo rand env a)
(eval-expo body `((,x . ,a) . ,env^) val)))
((fresh (x body)
(== `(lambda (,x) ,body) exp)
(symbolo x)
(not-in-envo 'lambda env)
(== `(closure ,x ,body ,env) val)))))
(define not-in-envo
(lambda (x env)
(conde
((fresh (y v rest)
(== `((,y . ,v) . ,rest) env)
(=/= y x)
(not-in-envo x rest)))
((== '() env)))))
(define-lazy-goal proper-listo
;; (define proper-listo
(lambda (exp env val)
(conde
((== '() exp)
(== '() val))
((fresh (a d t-a t-d)
(== `(,t-a . ,t-d) val)
(== `(,a . ,d) exp)
(eval-expo a env t-a)
(proper-listo d env t-d))))))
(define lookupo
(lambda (x env t)
(fresh (rest y v)
(== `((,y . ,v) . ,rest) env)
(conde
((== y x) (== v t))
((=/= y x) (lookupo x rest t))))))
(define (test-quines)
(parameterize ([reify-with-colon #f]
[reify-prefix-dot #f])
(test "1 quine"
(time (run 1 (q) (eval-expo q '() q)))
'((((lambda (_.0) (list _.0 (list 'quote _.0)))
'(lambda (_.0) (list _.0 (list 'quote _.0))))
(=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote)))
(sym _.0))))
(test "2 quines"
(time (run 2 (q) (eval-expo q '() q)))
'((((lambda (_.0) (list _.0 (list (quote quote) _.0)))
(quote (lambda (_.0) (list _.0 (list (quote quote) _.0)))))
(=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote)))
(sym _.0))
(((lambda (_.0)
(list (list (quote lambda) (quote (_.0)) _.0)
(list (quote quote) _.0)))
(quote (list (list (quote lambda) (quote (_.0)) _.0)
(list (quote quote) _.0))))
(=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote)))
(sym _.0))))
(test-check "3 quines"
(run 3 (q) (eval-expo q '() q))
'((((lambda (_.0) (list _.0 (list (quote quote) _.0)))
(quote (lambda (_.0) (list _.0 (list (quote quote) _.0)))))
(=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0))
(((lambda (_.0) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0)))
(quote (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))))
(=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0))
(((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2))))
(quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2))))))
(=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list))
((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote)))
(absento (closure _.2)) (sym _.0 _.1))))
)
)
(define (test-quines-long)
(test-quines)
(parameterize ([reify-with-colon #f]
[reify-prefix-dot #f])
(test-check "5 quines"
(run 5 (q) (eval-expo q '() q))
'((((lambda (_.0) (list _.0 (list (quote quote) _.0))) (quote (lambda (_.0) (list _.0 (list (quote quote) _.0))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))) (quote (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (quote (list (quote quote) _.0)))) (list (quote quote) _.0))) (quote (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (quote (list (quote quote) _.0)))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1))))
(test-check "10 quines"
(run 10 (q) (eval-expo q '() q))
'((((lambda (_.0) (list _.0 (list (quote quote) _.0))) (quote (lambda (_.0) (list _.0 (list (quote quote) _.0))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))) (quote (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (quote (list (quote quote) _.0)))) (list (quote quote) _.0))) (quote (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (quote (list (quote quote) _.0)))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list _.1 _.0)) (quote quote)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list _.1 _.0)) (quote quote)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list))) (sym _.0 _.1)) (((lambda (_.0) ((lambda (_.1) (list _.0 (list (quote quote) _.0))) (quote _.2))) (quote (lambda (_.0) ((lambda (_.1) (list _.0 (list (quote quote) _.0))) (quote _.2))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) _.1) (quote quote)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) _.1) (quote quote)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) (((lambda (_.0) (list ((lambda (_.1) _.0) (quote _.2)) (list (quote quote) _.0))) (quote (lambda (_.0) (list ((lambda (_.1) _.0) (quote _.2)) (list (quote quote) _.0))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) (quote _.3))) (quote _.4)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) (quote _.3))) (quote _.4)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2))))
(test-check "40 quines"
(run 40 (q) (eval-expo q '() q))
'((((lambda (_.0) (list _.0 (list (quote quote) _.0))) (quote (lambda (_.0) (list _.0 (list (quote quote) _.0))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))) (quote (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0)))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) (quote _.2)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (quote (list (quote quote) _.0)))) (list (quote quote) _.0))) (quote (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (quote (list (quote quote) _.0)))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list _.1 _.0)) (quote quote)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list _.1 _.0)) (quote quote)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list))) (sym _.0 _.1)) (((lambda (_.0) ((lambda (_.1) (list _.0 (list (quote quote) _.0))) (quote _.2))) (quote (lambda (_.0) ((lambda (_.1) (list _.0 (list (quote quote) _.0))) (quote _.2))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) _.1) (quote quote)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) _.1) (quote quote)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) (((lambda (_.0) (list ((lambda (_.1) _.0) (quote _.2)) (list (quote quote) _.0))) (quote (lambda (_.0) (list ((lambda (_.1) _.0) (quote _.2)) (list (quote quote) _.0))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) (quote _.3))) (quote _.4)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) (quote _.3))) (quote _.4)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list _.2 _.0)) (quote quote))) (quote _.3)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list _.2 _.0)) (quote quote))) (quote _.3)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) ((lambda (_.1) (list _.0 (list _.1 _.0))) (quote quote))) (quote (lambda (_.0) ((lambda (_.1) (list _.0 (list _.1 _.0))) (quote quote))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list))) (sym _.0 _.1)) (((lambda (_.0) ((lambda (_.1) (list (list (quote lambda) (quote (_.0)) (list _.1 (list (quote quote) _.1))) (quote (quote _.2)))) (quote (lambda (_.1) (list (list (quote lambda) (quote (_.0)) (list _.1 (list (quote quote) _.1))) (quote (quote _.2))))))) (quote _.2)) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (list (quote quote) (list (quote quote) _.0)))) (quote (quote (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (list (quote quote) (list (quote quote) _.0)))))))) (quote (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (list (quote quote) (list (quote quote) _.0)))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) ((lambda (_.1) (list _.1 (list (quote quote) _.1))) _.0)) (quote (lambda (_.0) ((lambda (_.1) (list _.1 (list (quote quote) _.1))) _.0)))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) (((lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list _.0 (list (quote quote) _.0))) (quote _.3))) (quote _.4))) (quote (lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list _.0 (list (quote quote) _.0))) (quote _.3))) (quote _.4))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list _.1 _.0)) (quote _.3))) (quote quote)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list _.1 _.0)) (quote _.3))) (quote quote)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 _.2)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list ((lambda (_.2) (quote quote)) (quote _.3)) _.0)) (quote _.4)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list ((lambda (_.2) (quote quote)) (quote _.3)) _.0)) (quote _.4)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 quote))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) ((lambda (_.1) (list (list (quote lambda) (quote (_.0)) (list _.1 (list _.0 _.1))) (quote (quote quote)))) (quote (lambda (_.1) (list (list (quote lambda) (quote (_.0)) (list _.1 (list _.0 _.1))) (quote (quote quote))))))) (quote quote)) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.1)) _.0))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.1)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) ((lambda (_.3) (list _.3 _.0)) (quote quote))) (quote _.4))) (quote _.5)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) ((lambda (_.3) (list _.3 _.0)) (quote quote))) (quote _.4))) (quote _.5)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 _.3)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 lambda)) ((_.2 list)) ((_.2 quote)) ((_.3 closure)) ((_.3 list))) (absento (closure _.4) (closure _.5)) (sym _.0 _.1 _.2 _.3)) (((lambda (_.0) ((lambda (_.1) (list _.1 (list (quote quote) _.0))) _.0)) (quote (lambda (_.0) ((lambda (_.1) (list _.1 (list (quote quote) _.0))) _.0)))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) ((lambda (_.2) (quote quote)) (quote _.3))) (quote _.4)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) ((lambda (_.2) (quote quote)) (quote _.3))) (quote _.4)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 quote)) ((_.2 closure)) ((_.2 quote))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 (list (quote quote) ((lambda (_.1) _.0) (quote _.2))))) (quote (lambda (_.0) (list _.0 (list (quote quote) ((lambda (_.1) _.0) (quote _.2))))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) _.0))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) _.0)) _.0))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 list)) ((_.1 quote))) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list ((lambda (_.2) _.2) (quote quote)) _.0)) (quote _.3)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list ((lambda (_.2) _.2) (quote quote)) _.0)) (quote _.3)))))) (=/= ((_.0 _.1)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (list (quote list) (quote (quote quote)) (quote _.0)))) (list (quote quote) _.0))) (quote (list (quote lambda) (quote (_.0)) (list (quote list) _.0 (list (quote list) (quote (quote quote)) (quote _.0)))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((lambda (_.0) (list _.0 (list (quote quote) ((lambda (_.1) ((lambda (_.2) _.0) (quote _.3))) (quote _.4))))) (quote (lambda (_.0) (list _.0 (list (quote quote) ((lambda (_.1) ((lambda (_.2) _.0) (quote _.3))) (quote _.4))))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 quote)) ((_.2 closure))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) ((lambda (_.2) _.0) (quote _.3)))) (quote _.4)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) (list (quote quote) ((lambda (_.2) _.0) (quote _.3)))) (quote _.4)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 (list ((lambda (_.1) ((lambda (_.2) _.2) (quote quote))) (quote _.3)) _.0))) (quote (lambda (_.0) (list _.0 (list ((lambda (_.1) ((lambda (_.2) _.2) (quote quote))) (quote _.3)) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 quote)) ((_.2 closure))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list ((lambda (_.1) _.1) _.0) (list (quote quote) _.0))) (quote (lambda (_.0) (list ((lambda (_.1) _.1) _.0) (list (quote quote) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) _.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0))) (quote (list (list (quote lambda) (quote (_.0)) _.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) _.0)))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) _.1)) (quote _.3)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) _.1)) (quote _.3)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) ((lambda (_.3) (list (quote quote) _.0)) (quote _.4))) (quote _.5))) (quote _.6)))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) ((lambda (_.3) (list (quote quote) _.0)) (quote _.4))) (quote _.5))) (quote _.6)))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 _.3)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 lambda)) ((_.2 list)) ((_.2 quote)) ((_.3 closure)) ((_.3 list)) ((_.3 quote))) (absento (closure _.4) (closure _.5) (closure _.6)) (sym _.0 _.1 _.2 _.3)) (((lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list _.0 (list _.2 _.0))) (quote quote))) (quote _.3))) (quote (lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list _.0 (list _.2 _.0))) (quote quote))) (quote _.3))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.1)) (quote _.3))) _.0))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.1)) (quote _.3))) _.0))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 _.2)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list (list (quote lambda) (quote (_.0)) (list _.1 (list (quote quote) _.1))) (quote (quote _.3)))) (quote _.4))) (quote (lambda (_.1) ((lambda (_.2) (list (list (quote lambda) (quote (_.0)) (list _.1 (list (quote quote) _.1))) (quote (quote _.3)))) (quote _.4)))))) (quote _.3)) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 _.2)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3) (closure _.4)) (sym _.0 _.1 _.2)) (((lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list _.1 (list (quote quote) _.1))) (quote _.3))) _.0)) (quote (lambda (_.0) ((lambda (_.1) ((lambda (_.2) (list _.1 (list (quote quote) _.1))) (quote _.3))) _.0)))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 _.2)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3)) (sym _.0 _.1 _.2)) (((lambda (_.0) (list (list (quote lambda) (quote (_.0)) _.0) (list ((lambda (_.1) _.1) (quote quote)) _.0))) (quote (list (list (quote lambda) (quote (_.0)) _.0) (list ((lambda (_.1) _.1) (quote quote)) _.0)))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure))) (sym _.0 _.1)) (((lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) (quote _.3))) _.0))) (quote (lambda (_.0) (list _.0 ((lambda (_.1) ((lambda (_.2) (list (quote quote) _.0)) (quote _.3))) _.0))))) (=/= ((_.0 _.1)) ((_.0 _.2)) ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 lambda)) ((_.1 list)) ((_.1 quote)) ((_.2 closure)) ((_.2 list)) ((_.2 quote))) (absento (closure _.3)) (sym _.0 _.1 _.2))))
(test-check "2 twines"
(run 2 (x) (fresh (p q)
(=/= p q)
(eval-expo p '() q)
(eval-expo q '() p)
(== `(,p ,q) x)))
'((((quote ((lambda (_.0) (list (quote quote) (list _.0 (list (quote quote) _.0)))) (quote (lambda (_.0) (list (quote quote) (list _.0 (list (quote quote) _.0))))))) ((lambda (_.0) (list (quote quote) (list _.0 (list (quote quote) _.0)))) (quote (lambda (_.0) (list (quote quote) (list _.0 (list (quote quote) _.0))))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((quote (list (quote quote) ((lambda (_.0) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0)))) (quote (lambda (_.0) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0)))))))) (list (quote quote) ((lambda (_.0) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0)))) (quote (lambda (_.0) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0)))))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0))))
(test-check "4 thrines"
(run 4 (x)
(fresh (p q r)
(=/= p q)
(=/= q r)
(=/= r p)
(eval-expo p '() q)
(eval-expo q '() r)
(eval-expo r '() p)
(== `(,p ,q ,r) x)))
'((((quote (quote ((lambda (_.0) (list (quote quote) (list (quote quote) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list (quote quote) (list (quote quote) (list _.0 (list (quote quote) _.0))))))))) (quote ((lambda (_.0) (list (quote quote) (list (quote quote) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list (quote quote) (list (quote quote) (list _.0 (list (quote quote) _.0)))))))) ((lambda (_.0) (list (quote quote) (list (quote quote) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list (quote quote) (list (quote quote) (list _.0 (list (quote quote) _.0)))))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((quote (quote (list (quote quote) ((lambda (_.0) (list (quote quote) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list (quote quote) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0)))))))))) (quote (list (quote quote) ((lambda (_.0) (list (quote quote) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list (quote quote) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0))))))))) (list (quote quote) ((lambda (_.0) (list (quote quote) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list (quote quote) (list (quote list) (quote (quote quote)) (list _.0 (list (quote quote) _.0))))))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0)) (((quote (quote ((lambda (_.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) (list (quote quote) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) (list (quote quote) (list _.0 (list (quote quote) _.0))))))))) (quote ((lambda (_.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) (list (quote quote) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) (list (quote quote) (list _.0 (list (quote quote) _.0)))))))) ((lambda (_.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) (list (quote quote) (list _.0 (list (quote quote) _.0))))) (quote (lambda (_.0) (list ((lambda (_.1) (quote quote)) (quote _.2)) (list (quote quote) (list _.0 (list (quote quote) _.0)))))))) (=/= ((_.0 closure)) ((_.0 lambda)) ((_.0 list)) ((_.0 quote)) ((_.1 closure)) ((_.1 quote))) (absento (closure _.2)) (sym _.0 _.1)) (((quote (quote ((lambda (_.0) (list (quote quote) (list (quote quote) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))))) (quote (list (quote quote) (list (quote quote) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0)))))))) (quote ((lambda (_.0) (list (quote quote) (list (quote quote) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))))) (quote (list (quote quote) (list (quote quote) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))))))) ((lambda (_.0) (list (quote quote) (list (quote quote) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))))) (quote (list (quote quote) (list (quote quote) (list (list (quote lambda) (quote (_.0)) _.0) (list (quote quote) _.0))))))) (=/= ((_.0 closure)) ((_.0 list)) ((_.0 quote))) (sym _.0))))))
(module+ main
(test-quines-long))
| false |
a732e62afb421682fa8ece180c98e0db16065ed5 | 7b6fda23820f41b902cf72d427be58718d419891 | /monoskolem.rkt | a57c39d278df8be58f57ac9be63fed81b7c20f15 | [
"MIT"
]
| permissive | Sumith1896/skosette | f1b3be4786af7f16074b8156b1d3136ec2c34e05 | e605edb9536db62d8f48e619fb1f0b04f67d48bc | refs/heads/master | 2021-01-23T05:55:40.846655 | 2017-07-07T02:50:05 | 2017-07-07T02:50:05 | 92,998,367 | 1 | 0 | null | 2017-07-07T02:51:15 | 2017-05-31T23:48:03 | Racket | UTF-8 | Racket | false | false | 11,861 | rkt | monoskolem.rkt | ; Implementation of Skolem synthesis from the paper
;
; The Rosette library can be found at http://emina.github.io/rosette/
;
; author: Sumith Kulal ([email protected])
; date: 2017 May 31
; license: MIT
#lang racket
(require (only-in rosette unsat? current-solver
solver-push solver-pop solver-assert solver-check)
;; Note that evaluate comes from util.rkt and not Rosette.
"util.rkt")
;;;;;;;;;;;;;
;; Parsing ;;
;;;;;;;;;;;;;
; number of clauses r, total variable num-var and number of x variables n
(define r 0)
(define num-var 0)
(define n 0)
; list of x-list, y-list, clauses and variable to clauses
(define x-list '())
(define y-list '())
(define clauses '())
(define (parse-dimacs-formula file)
(for ([str (file->lines file)] #:unless (equal? str ""))
(let* ([first-char (string-ref str 0)]
[list-str (regexp-split #px" " str)])
(cond
[(char=? first-char #\c)]
[(char=? first-char #\p)
(set! num-var (string->number (list-ref list-str 2)))
(set! r (string->number (list-ref list-str 3)))]
[(char=? first-char #\a)
(define str-y-list (reverse (cdr (reverse (cdr list-str)))))
(set! y-list (map string->number str-y-list))]
[(char=? first-char #\e)
(define str-x-list (reverse (cdr (reverse (cdr list-str)))))
(set! x-list (map string->number str-x-list))
(set! n (length x-list))]
[else
(define str-clause (reverse (cdr (reverse list-str))))
(define clause (map string->number str-clause))
(set! clauses (cons clause clauses))]))))
(define (rosettify num-vars xs clauses)
(define orig-var->rosette-var
(for/hash ([i (range 1 (add1 num-vars))])
(cond [(member i xs)
(values i (make-symbolic-boolean x))]
[else
(values i (make-symbolic-boolean y))])))
(define rosette-var->orig-var
(for/hash ([(k v) orig-var->rosette-var])
(values v k)))
(define get-rosette-var (curry hash-ref orig-var->rosette-var))
(define get-orig-var (curry hash-ref rosette-var->orig-var))
(define (rosettify-literal lit)
(if (< lit 0)
(! (get-rosette-var (- lit)))
(get-rosette-var lit)))
(define (rosettify-formula clause)
(apply || (map rosettify-literal clause)))
(values (map get-rosette-var xs)
(map rosettify-formula clauses)
get-rosette-var get-orig-var))
;;;;;;;;;;;;;;;;
;; Monoskolem ;;
;;;;;;;;;;;;;;;;
;; Algorithm 1
(define (monoskolem)
(define-values (_ reversed-ψs)
(for/fold ([factors rosette-clauses] [reversed-ψs '()])
([var xs])
(printf "Current var: ~a~%" var)
(let* ([factors-with-var
(filter (curry in-formula? var) factors)]
[F (apply && factors-with-var)]
;[cb0 (! (bind F var #f))]
[cb1 (! (bind F var #t))]
[ψ (! cb1)]) ;; (combine cb0 cb1)
(values (cons (bind F var ψ)
(remove* factors-with-var factors))
(cons ψ reversed-ψs)))))
(define result
(reverse-substitute (list->vector xs)
(list->vector (reverse reversed-ψs))))
result)
;; Algorithm 2
(define (reverse-substitute x-vec ψs)
(display "Reverse substitute: ")
(time
(for ([i (range (sub1 (vector-length ψs)) 0 -1)])
;(printf "Reverse substituting variable ~a~%" (vector-ref x-vec i))
(for ([k (range (sub1 i) -1 -1)])
(let ([ψ-k (vector-ref ψs k)]
[ψ-i (vector-ref ψs i)]
[x-i (vector-ref x-vec i)])
(vector-set! ψs k (bind ψ-k x-i ψ-i))))))
ψs)
;;;;;;;;;;;;;;;;;;;;;;
;; Annotated values ;;
;;;;;;;;;;;;;;;;;;;;;;
;; Annotated values keep around the sets of symbolic variables in the
;; formulas so that in-formula? queries are O(1).
(struct annotated-val (formula set))
(define (in-formula?^ var formula)
(set-member? (annotated-val-set formula) var))
(define (&&^ . args)
(annotated-val (apply && (map annotated-val-formula args))
(apply set-union (map annotated-val-set args))))
(define (bind^ formula var val)
(unless (boolean? val)
(error "bind^ does not currently handle non-booleans"))
(annotated-val (bind (annotated-val-formula formula) var val)
(set-remove (annotated-val-set formula) var)))
;;;;;;;;;;;;;;;
;; R vectors ;;
;;;;;;;;;;;;;;;
;; symbolic-sets: Vector of immutable sets
;; changes: Vector of lists of symbolic/concrete booleans
;; values: Vector of symbolic/concrete booleans
;; Invariants:
;; The overall value at any index i is given by
;; true-value[i] = (apply || values[i] changes[i])
;; symbolic-sets[i] == (symbolics-set true-value[i])
(struct rvec (symbolic-sets changes values))
(define (make-rvec n)
(rvec (make-vector n (set))
(make-vector n '())
(make-vector n #f)))
(define (rvec-add! rvec index elem)
(rvec-add-with-set! rvec index elem (symbolics-set elem)))
(define (rvec-add!^ rvec index elem)
(match elem
[(annotated-val formula set)
(rvec-add-with-set! rvec index formula set)]))
(define (rvec-add-with-set! rvec index elem s)
(define changes (rvec-changes rvec))
(define rvec-sets (rvec-symbolic-sets rvec))
(vector-set! changes index
(cons elem (vector-ref changes index)))
(vector-set! rvec-sets index
(set-union s (vector-ref rvec-sets index))))
(define (rvec-formula rvec index)
(apply ||
(vector-ref (rvec-values rvec) index)
(vector-ref (rvec-changes rvec) index)))
(define (consolidate-changes! rvec)
(define changes (rvec-changes rvec))
(define values (rvec-values rvec))
(for ([i (vector-length values)])
(vector-set! values i (rvec-formula rvec i))
(vector-set! changes i '())))
;;;;;;;;;;;;;;;
;; Algorithm ;;
;;;;;;;;;;;;;;;
(define (r1->ψ r1)
(define n (vector-length (rvec-values r1)))
(for/vector #:length n ([i n])
(! (rvec-formula r1 i))))
;; Algorithm 3
(define (init-abs-ref x-vec factors r0 r1)
(for ([f factors])
(define vars-in-f (symbolics-set f))
(for ([i (in-naturals 0)]
[var x-vec]
#:when (set-member? vars-in-f var))
(let* ([with-false (bind f var #f)]
[with-true (bind f var #t)])
(rvec-add! r0 i (! with-false))
(rvec-add! r1 i (! with-true))
(set! f (bind f var with-true)))))
(r1->ψ r1))
;; Multiple implementations possible
(define (generalize^ π rvec index)
(annotated-val (rvec-formula rvec index)
(vector-ref (rvec-symbolic-sets rvec) index)))
;; Algorithm 4
;; r0, r1: Vector mapping each x variable to a list of formulas
;; pi: A sat? model (i.e. one produced by solve)
(define (update-abs-ref x-vec r0 r1 π)
(define π-fn (make-evaluator π))
(let* ([n (vector-length x-vec)]
;; Lemma 3a/3b says x_{n-1} cannot be the one we want, so
;; start looking from x_{n-2}
[k (time (display "Calculate: ")
(for/first ([m (range (- n 2) -1 -1)]
#:when (and (π-fn (rvec-formula r0 m))
(π-fn (rvec-formula r1 m))))
m))]
[µ0 (generalize^ π r0 k)]
[µ1 (generalize^ π r1 k)])
(let loop ([l (add1 k)] [µ (&&^ µ0 µ1)])
(define var (vector-ref x-vec l))
(cond [(not (in-formula?^ var µ))
(loop (add1 l) µ)]
[(π-fn var)
(let ([new-µ1 (bind^ µ var #t)])
(rvec-add!^ r1 l new-µ1)
(if (time (display "Evaluate: ") (π-fn (rvec-formula r0 l)))
(let ([new-µ0 (generalize^ π r0 l)])
(loop (add1 l) (&&^ new-µ0 new-µ1)))
'done))]
[else
(let ([new-µ0 (bind^ µ var #f)])
(rvec-add!^ r0 l new-µ0)
(let ([new-µ1 (generalize^ π r1 l)])
(loop (add1 l) (&&^ new-µ0 new-µ1))))]))))
;; Algorithm 5
(define (cegar-skolem x-vec factors)
(define (make-extra) (make-symbolic-boolean extra))
;; extras: List of symbolic boolean variables
(define (solve-with-extras extras-list)
(solver-push (current-solver))
(solver-assert (current-solver) extras-list)
(begin0 (time (display "SAT solver: ") (solver-check (current-solver)))
(solver-pop (current-solver) 1)))
(let* ([n (vector-length x-vec)]
[r0 (make-rvec n)]
[r1 (make-rvec n)]
[init-ψ (init-abs-ref x-vec factors r0 r1)]
[x->fresh-var (for/hash ([x x-vec])
(values x (make-symbolic-boolean fresh-x)))]
[F (apply && factors)]
[F-fresh (bind-all F x->fresh-var)]
[extras (build-vector n (lambda (i) (make-extra)))]
[equivalences (for/fold ([result #t])
([x x-vec] [p init-ψ] [extra extras])
(&& (<=> x (&& p extra)) result))]
[ε (&& F-fresh equivalences (! F))])
(solver-assert (current-solver) (list (desugar-binds ε)))
(define π (solve-with-extras (vector->list extras)))
(for ([i (in-naturals 1)]
#:break (unsat? π))
(consolidate-changes! r0)
(consolidate-changes! r1)
;; update-abs-ref will create new changes which we then send to
;; the SAT solver incrementally
(time (begin0 (update-abs-ref x-vec r0 r1 π) (display "Update: ")))
(define new-asserts
(time
(display "New asserts: ")
(for/list ([i (in-naturals 0)]
[change (rvec-changes r1)]
#:unless (null? change))
(define old-extra (vector-ref extras i))
(define new-extra (make-extra))
(vector-set! extras i new-extra)
;; TODO: We're forced to desugar-binds here because Rosette
;; can't encode binds. However, this leads to a blowup in
;; the size of the formula (which binds were meant to avoid
;; in the first place). There is probably speedup to be
;; gained by rewriting enc to understand binds and produce
;; a result that avoids formula blowup.
(<=> old-extra (apply && new-extra
(map (compose ! desugar-binds) change))))))
(time (display "Solver assert: ")
(solver-assert (current-solver) new-asserts))
(time (set! π (solve-with-extras (vector->list extras)))
(printf "~a. solve-with-extras: " i)))
(reverse-substitute x-vec (r1->ψ r1))))
;;;;;;;;;;;;;;
;; Examples ;;
;;;;;;;;;;;;;;
(parse-dimacs-formula "test.qdimacs")
; (writeln r)
; (writeln num-var)
; (writeln n)
; (displayln "x-list")
; (writeln x-list)
; (displayln "y-list")
; (writeln y-list)
; (displayln "clauses")
; (writeln clauses)
(define-values (xs rosette-clauses get-rosette-var get-orig-var)
(rosettify num-var x-list clauses))
(define (my-repr formula)
(formula-repr formula get-orig-var))
(define (order xs clauses)
;; Order the xs in order of the number of times they appear in clauses
(define x->count (make-hash (for/list ([x xs]) (cons x 0))))
(for* ([clause clauses] [x (symbolics-set clause)])
(hash-set! x->count x (add1 (hash-ref x->count x))))
(map car (sort (for/list ([(x c) x->count]) (cons x c))
(lambda (x y) (< (cdr x) (cdr y))))))
(define ordered-xs (order xs clauses))
(define result
;(monoskolem)
(cegar-skolem (list->vector ordered-xs) rosette-clauses))
(displayln "Solved! Printing the results:")
(for-each (curry printf "~a: ~a~%")
(map get-orig-var ordered-xs)
(map (compose nnf desugar-binds) (vector->list result)))
| false |
8b1714cb794633bcc0bfd382122dd3be947843ed | e553691752e4d43e92c0818e2043234e7a61c01b | /rosette/lib/roseunit.rkt | a4b1b44b9438f6a7aa06e018cbc277624ee8ddb9 | [
"BSD-2-Clause"
]
| permissive | emina/rosette | 2b8c1bcf0bf744ba01ac41049a00b21d1d5d929f | 5dd348906d8bafacef6354c2e5e75a67be0bec66 | refs/heads/master | 2023-08-30T20:16:51.221490 | 2023-08-11T01:38:48 | 2023-08-11T01:38:48 | 22,478,354 | 656 | 89 | NOASSERTION | 2023-09-14T02:27:51 | 2014-07-31T17:29:18 | Racket | UTF-8 | Racket | false | false | 5,025 | rkt | roseunit.rkt | #lang racket
; Utilities for testing Rosette programs.
(require rackunit rackunit/text-ui)
(require rosette/base/core/result
(only-in rosette
clear-state!
current-bitwidth
with-vc with-terms terms
solution? sat? unsat?))
(require (for-syntax syntax/parse))
(provide run-all-tests test-groups test-suite+
run-generic-tests run-solver-specific-tests check-all-tests-executed
test-sat test-unsat check-sol check-sat check-unsat)
; Groups tests into N modules with names id ..., each
; of which requires the specified modules and submodules.
; For example, (test-groups [test fast] "a.rkt" (submod "b.rkt"))
; creates two module+ forms, test and fast, both of which require
; "a.rkt" and (submod "b.rkt" id).
(define-syntax (test-groups stx)
(syntax-case stx ()
[(_ [id ...] mod ...)
(quasisyntax/loc stx
(begin
#,@(for/list ([i (syntax->list #'(id ...))])
(quasisyntax/loc i
(module+ #,i
(run-all-tests
#,@(for/list ([m (syntax->list #'(mod ...))])
(syntax-case m (submod)
[(submod name) (quasisyntax/loc m (submod name #,i))]
[_ m]))))))))]))
; Given a set of relative paths containing modules with tests,
; requires them all into the present environment, one by one,
; clearing the Rosette state between each import.
(define-syntax (run-all-tests stx)
(syntax-case stx ()
([_ path ...]
(with-syntax ([(id ...) (generate-temporaries #'(path ...))])
(syntax/loc stx
(begin
(module id racket
(require path)
(require (only-in rosette/safe clear-state!))
(clear-state!)) ...
(require 'id) ...))))))
(define-syntax-rule (with-normal-or-fail expr)
(match (with-vc expr)
[(normal v _) v]
[(failed ex _) (raise ex)]))
; Makes sure that a test suite clears all Rosette state after it terminates.
(define-syntax (test-suite+ stx)
(syntax-parse stx
[(_ name:expr
(~optional (~seq #:features features:expr))
(~optional (~seq #:before before:expr))
(~optional (~seq #:after after:expr))
test:expr ...)
(with-syntax ([features (or (attribute features) #''())]
[before (or (attribute before) #'void)]
[after (or (attribute after) #'void)])
#'(let ([ts (test-suite
name
#:before (thunk (printf "~a\n" name) (before))
#:after after
(with-normal-or-fail
(with-terms
(parameterize ([current-bitwidth (current-bitwidth)])
test ...))))])
(let ([rts (rosette-test-suite features ts (terms) (current-bitwidth))])
(set-box! discovered-tests (append (unbox discovered-tests) (list rts)))
ts)))]))
; Tests discovered by instantiating test-suite+.
; Each element of the list is a rosette-test-suite?.
; A test should only be run if the current-solver satisfies the test's feature list.
(define discovered-tests (box '()))
(define executed-tests (mutable-seteq))
(struct rosette-test-suite (features ts terms bitwidth) #:transparent)
; Run all discovered tests that the given list of features satisfies.
; Only tests that actually require features are run.
(define (run-solver-specific-tests [features '()])
(for ([rts (in-list (unbox discovered-tests))])
(match-define (rosette-test-suite feats ts trms bw) rts)
(when (and (not (null? feats)) (for/and ([f feats]) (member f features)))
(with-terms trms
(parameterize ([current-bitwidth bw])
(set-add! executed-tests rts)
(time (run-tests ts)))))))
; The same as run-all-discovered-tests, but only for tests
; that require no features.
(define (run-generic-tests)
(for ([rts (in-list (unbox discovered-tests))])
(match-define (rosette-test-suite feats ts trms bw) rts)
(when (null? feats)
(with-terms trms
(parameterize ([current-bitwidth bw])
(set-add! executed-tests rts)
(time (run-tests ts)))))))
; Check that every discovered test was executed at least once
(define (check-all-tests-executed)
(define all-tests (list->seteq (unbox discovered-tests)))
(define unexecuted (set-subtract all-tests executed-tests))
(check-equal? unexecuted (seteq) "some tests were not executed"))
(define-syntax-rule (check-sol pred test)
(let ([sol test])
(check-true (pred sol) (format "not ~a for ~a: ~a" (quote pred) (quote test) sol))
sol))
(define-syntax-rule (check-sat test) (check-sol sat? test))
(define-syntax-rule (check-unsat test) (check-sol unsat? test))
(define-syntax-rule (test-sat name expr)
(test-case name (check-sat expr)))
(define-syntax-rule (test-unsat name expr)
(test-case name (check-unsat expr)))
| true |
27daed1bc5aac8c9aa49eae09159022a66979b81 | 6b8bee118bda956d0e0616cff9ab99c4654f6073 | /stasis/hash-tbl-ctype/hash-code.rkt | fd8cb23673f67b22b56127644491586044b74ff1 | []
| no_license | skchoe/2012.Functional-GPU-Programming | b3456a92531a8654ae10cda622a035e65feb762d | 56efdf79842fc465770214ffb399e76a6bbb9d2a | refs/heads/master | 2016-09-05T23:42:36.784524 | 2014-05-26T17:53:34 | 2014-05-26T17:53:34 | 20,194,204 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,354 | rkt | hash-code.rkt | #lang racket
(provide (all-defined-out))
(define (hash-1-str x)
(hash-1-char (car (string->list x))))
(define (hash-1-char x)
(hash-1-by (char->integer x)))
;; a(97) ~ z(122) A(65) ~ Z(90)
;; 0 ~ 25 26 ~ 51 : Total 52 in a row.
(define (hash-1-by by)
(let* ([nby (if (<= 97 by) ;; lower case character?
(- by 97) ;; by - 'a'
(- by 39))]) ;; by - 39(65-26)
nby))
;; input - string with 2 digit valid alphabet
;; output -hash code: integer?
(define (hash-2-str xx)
(hash-2-char (string->list xx)))
(define (hash-2-char l-c)
(hash-2-by (map char->integer l-c)))
(define (hash-2-by l-by)
(let* ([l-idx (map hash-1-by l-by)]
[head (car l-idx)] ;; hash code for digit 2
[neck (cadr l-idx)]) ;; hash code for digit 1
#;(display l-idx)
(+ (+ neck (* head 52)) ; order 2
52))) ; order 1
(define (hash-3-str xxx)
(hash-3-char (string->list xxx)))
(define (hash-3-char l-c)
(let* ([l-by (map char->integer l-c)]
[l-idx (map hash-1-by l-by)]
[o3 (car l-idx)]
[o2 (cadr l-idx)]
[o1 (caddr l-idx)])
(+ (* 52 52 o3) (* 52 o2) o1
(* 52 52) ; order 2
52))) ; order 1
;; given char-list, convert to sublist from 'a~z', 'A~Z' by deleting #\null or #\space
;; whereever in the list, call corresponding hash-x func by the length of the resulting list.
(define (string->hash-code str)
(let* ([new-string
(list->string
(filter (λ (x)
(if (or (equal? x #\null)
(equal? x #\space))
#f #t))
(string->list str)))]
[result
(case (string-length new-string)
[(1) (hash-1-str new-string)]
[(2) (hash-2-str new-string)]
[(3) (hash-3-str new-string)]
[else (printf " string->hashcode : Hashcode for ~a?\n" new-string)
(error "TODO: such long string cannot have hash code now\n")])])
;(printf "string->hashcode for ~a, newstr:~a --> result:~a\n" str new-string result)
result))
(define (hash-code->string-1 code)
(if (<= code 51)
(list->string (list (integer->char (if (<= code 25) (+ code 97) (+ code 39)))))
(error "hash-code->string-1 outof range error\n")))
(define (hash-code->string-2 code)
(cond
[(< code (string->hash-code "aa")) (error "hash-code->string-2 outof range error: too small\n")]
[(<= code (string->hash-code "ZZ"))
(let*-values ([(length1) (+ (string->hash-code "Z") 1)]
[(normed-code) (- code length1)]
[(q r) (quotient/remainder normed-code length1)])
#;(printf "code:~a, quotient:~a, remainder:~a, length:~a\n" normed-code q r length1)
(let ([s0 (hash-code->string-1 q)]
[s1 (hash-code->string-1 r)])
(string-append s0 s1)))]
[else (error "hash-code->string-2 outof range error: too big\n")]))
(define (hash-code->string-3 code)
(cond
[(< code (string->hash-code "aaa")) (error "hash-code->string-3 outof range error: too small\n")]
[(<= code (string->hash-code "ZZZ"))
(let*-values ([(length1) (+ (string->hash-code "Z") 1)]
[(length2) (* length1 length1)]
[(normed-code) (- code length1 length2)]
[(q2 r2) (quotient/remainder normed-code length2)]
[(q1 r1) (quotient/remainder r2 length1)])
#;(printf "n-code:~a, len1:~a len2:~a quotients:~a ~a, remainder:~a ~a\n"
normed-code length1 length2 q2 q1 r2 r1)
(let ([s0 (hash-code->string-1 q2)]
[s1 (hash-code->string-1 q1)]
[s2 (hash-code->string-1 r1)])
(string-append s0 s1 s2)))]
[else (error "hash-code->string-3 outof range error: too big\n")]))
;(string->hash-code "a")
;(hash-code->string-1 0)
;(string->hash-code "aa")
;(hash-code->string-2 52)
;(string->hash-code "aZ")
;(hash-code->string-2 103)
;(string->hash-code "ZZ")
;(hash-code->string-2 2755)
;(- (string->hash-code "aaa") (string->hash-code "baa"))
;(hash-code->string-3 2756)
;(- (string->hash-code "ZZZ") (string->hash-code "YZZ"))
;(hash-code->string-3 143363)
;code: integer? non-negative
(define (hash-code->string code)
(let* ([max1 (string->hash-code "Z")]
[max2 (string->hash-code "ZZ")]
[max3 (string->hash-code "ZZZ")]
[result
(cond
[(<= code max1) (hash-code->string-1 code)]
[(<= code max2) (hash-code->string-2 code)]
[(<= code max3) (hash-code->string-3 code)]
[else (error "Hash code too big\n")])])
;(printf "hash-code->string: INPUT-code:~a, uppbd:~a, ~a, ~a\n" code max1 max2 max3)
result))
#;(hash-code->string (string->hash-code "a"))
;(string->hash-code "z ")
;(string->hash-code " A")
#;(hash-code->string (string->hash-code "Z"))
#;(hash-code->string (string->hash-code "aa"))
#;(hash-code->string (string->hash-code "ZZ"))
#;(hash-code->string (string->hash-code "aaa"))
#;(hash-code->string (string->hash-code "ZZZ"))
;"aZ"
;(string->hash-code "aZ")
;"ZZ"
;(string->hash-code "ZZ")
;"aaa"
;(string->hash-code "aaa")
;"ZZZ"
#;(string->hash-code "ZZZ")
;(- (+ (* 52 52 52) (* 52 52) 52) 1) | false |
f502935504f10e86631a7912e28f585f8fac0b87 | 821e50b7be0fc55b51f48ea3a153ada94ba01680 | /exp4/tr/typed-racket/typecheck/tc-app/tc-app-apply.rkt | 25dd768c839a7fa6c81570fb8797e1d23fc2cda5 | []
| no_license | LeifAndersen/experimental-methods-in-pl | 85ee95c81c2e712ed80789d416f96d3cfe964588 | cf2aef11b2590c4deffb321d10d31f212afd5f68 | refs/heads/master | 2016-09-06T05:22:43.353721 | 2015-01-12T18:19:18 | 2015-01-12T18:19:18 | 24,478,292 | 1 | 0 | null | 2014-12-06T20:53:40 | 2014-09-25T23:00:59 | Racket | UTF-8 | Racket | false | false | 965 | rkt | tc-app-apply.rkt | #lang racket/unit
(require "../../utils/utils.rkt"
"signatures.rkt"
"utils.rkt"
syntax/parse racket/match
syntax/parse/experimental/reflect
(typecheck signatures tc-funapp)
(types abbrev utils)
(rep type-rep)
;; fixme - don't need to be bound in this phase - only to make tests work
(only-in '#%kernel [apply k:apply])
;; end fixme
(for-template
racket/base
(only-in '#%kernel [apply k:apply])))
(import tc-expr^ tc-apply^)
(export tc-app-apply^)
(define-tc/app-syntax-class (tc/app-apply expected)
#:literals (k:apply apply values)
(pattern ((~or apply k:apply) values e)
(match (single-value #'e)
[(tc-result1: (ListDots: dty dbound))
(ret null null null dty dbound)]
[(tc-result1: (List: ts)) (ret ts)]
[_ (tc/apply #'values #'(e))]))
(pattern ((~or apply k:apply) f . args)
(tc/apply #'f #'args)))
| false |
f121ca1f657290797d342bdbb08debebdfac69ba | 0abd54a0a7bbd4150cb94c42faae025a519182b7 | /compositions/02.rkt | 8de0f2b698d301600f283585638cff623433676c | []
| no_license | jagen31/tonart-less-old | 83c0c3cfc6918c08c1ec6c9308b8cec42824f6cb | 3beb8b632305d2cc2057f8014e86077618083d1a | refs/heads/master | 2022-03-17T04:13:53.046582 | 2019-12-09T23:14:33 | 2019-12-09T23:14:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 802 | rkt | 02.rkt | #lang racket
(require "../eval.rkt")
(require "../music.rkt")
(require "../perform.rkt")
(require "../realize.rkt")
(define (secret o)
(-- ()
(1 (note 'd 0 o))
(1 (note 'e 0 o))
(1 (note 'f 0 o))
(1 (note 'g 0 o))
(2 (note 'e 0 o))
(1 (note 'c 0 o))
(4 (note 'd 0 o))))
(define comp
(|| ([voices '(s a t b)])
(g:tremolo .5)
(-- ([voices '(s)])
(2 (note 'a 0 4))
(4 (note 'b -1 4))
(2 (note 'a 0 4))
(4 (note 'a 0 4)))
(in ([voices '(a)]) (secret 4))
(-- ([voices '(t)])
(4 (note 'f 0 3))
(4 (note 'e 0 3))
(4 (note 'f 0 3)))
(-- ([voices '(b)])
(2 (note 'd 0 3))
(2 (note 'b -1 2))
(2 (note 'g 0 2))
(2 (note 'a 0 2))
(4 (note 'd 0 2)))))
(play (perform (realize comp) 240)) | false |
52cae3d1a9d8d2631e5cd29a6cd829cd8b4074e4 | f6bbf5befa45e753077cf8afc8f965db2d214898 | /ASTBenchmarks/class-compiler/tests/examples/r1_8.rkt | ce44e48f82ccaf1f2c9339e2084f644f55bf9499 | []
| no_license | iu-parfunc/gibbon | 4e38f1d2d0526b30476dbebd794f929943f19f12 | 45f39ad0322cd7a31fe04922ad6bf38e6ac36ad6 | refs/heads/main | 2023-08-31T11:39:58.367737 | 2023-08-30T23:44:33 | 2023-08-30T23:44:38 | 58,642,617 | 139 | 23 | null | 2023-09-12T20:40:48 | 2016-05-12T13:10:41 | C | UTF-8 | Racket | false | false | 40 | rkt | r1_8.rkt | (let ([x 20])
(+ (let ([x 22]) x) x))
| false |
1184d89bbb163b8ac5183df815053687bc27fc87 | d29c2c4061ea24d57d29b8fce493d116f3876bc0 | /tests/test-modules-3.rkt | 565ef4f8c1664b010c9767dccfcd2c6198f5c52d | []
| no_license | jbejam/magnolisp | d7b28e273550ff0df884ecd73fb3f7ce78957d21 | 191d529486e688e5dda2be677ad8fe3b654e0d4f | refs/heads/master | 2021-01-16T19:37:23.477945 | 2016-10-01T16:02:42 | 2016-10-01T16:02:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 163 | rkt | test-modules-3.rkt | #lang magnolisp/2014
(require "lib-modules-3.rkt")
(typedef int (#:annos foreign))
(function (f x)
(#:annos export (type (fn int int)))
(eight-m))
(f 100)
| false |
e81cc01b5a9f14b4250c41c4d6d661d9e9198f2a | 4b5472bdab1db0c0425ae79eced9b0e3da1aae0a | /tests/stress-test-arithmetic.rkt | 002ddd4a3bc334f008a4cb7559a4967aebc83263 | [
"Apache-2.0"
]
| permissive | Metaxal/rascas | c5a921c456e5c9e0948f6fd65c0f2ca3628ec47d | f575e5a63b02358e80bfde53c7cb3eaae396e41a | refs/heads/master | 2023-03-16T04:23:54.814941 | 2023-03-11T13:37:28 | 2023-03-11T13:37:28 | 121,151,282 | 27 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 873 | rkt | stress-test-arithmetic.rkt | #lang racket/base
(require rascas/misc
rascas/arithmetic
rascas/order-relation
racket/list
racket/match
data/heap
(prefix-in rkt: (only-in racket/base + * - /)))
#;
(define (chain-comparators a b kind+cmps)
(if (empty? kind+cmps)
(error "cmps empty" 'order<?)
(let ([kind+cmp (first kind+cmps)])
(define kind (first kind+cmp))
(define cmp (second kind+cmp))
(define kinda (kind a))
(define kindb (kind b))
(cond [(and kinda kindb)
(cmp a b)]
[kinda #t]
[kindb #f]
[else (chain-comparators a b (rest kind+cmps))]))))
(module+ main
(define n 1000000)
(define l (shuffle (append* (build-list n (λ (i) (random 1000)))
(make-list n '(x y z t u v)))))
(collect-garbage)
(time (apply + l))
)
| false |
3b390bde1ddd4115c3c236c9d8e12ec089a891cc | c161c2096ff80424ef06d144dacdb0fc23e25635 | /chapter1/exercise/ex1.10.rkt | ea87b98eaa6f66a2f3dd6a5cbead63cfce10b413 | []
| no_license | tangshipoetry/SICP | f674e4be44dfe905da4a8fc938b0f0460e061dc8 | fae33da93746c3f1fc92e4d22ccbc1153cce6ac9 | refs/heads/master | 2020-03-10T06:55:29.711600 | 2018-07-16T00:17:08 | 2018-07-16T00:17:08 | 129,242,982 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 558 | rkt | ex1.10.rkt | #lang racket
;阿克曼函数
(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1)
(A x (- y 1))))))
;A函数,x为0,值为2*y ——>2*n
(define (f n)(A 0 n))
;A函数,x为1,y>1时,until y=1,multiplicate 2, recursive, when y = 1, value = 2, -------->>>2 to the power of n
(define (g n)(A 1 n))
;A函数,x 为2,2 to the power of (A 2 (- n 1))
;n =1-->2,n=2-->4, n=3--16,n=4-->2 to the power of 16m,65536,n=5-->2 to the power of 655636
(define (h n)(A 2 n))
| false |
2f3c40f80f89191ccb99ad774ff58f8bac59dc04 | b6a5637b6d3fc8ad1b7996c62ec73b6d895c5e95 | /ch2/2.1/ex-2.5.rkt | e20da32afa4f960dcdbff79194eada183e5b2234 | [
"MIT"
]
| permissive | abelkov/sicp-musings | 8911b5215b42fc21c15699b11cdb68727852d399 | 49373974eb3df8e12ad086ddfabda14b95f139ba | refs/heads/master | 2021-06-12T03:55:16.842917 | 2017-01-31T19:02:45 | 2017-01-31T19:02:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 376 | rkt | ex-2.5.rkt | #lang racket
(define (divides? a b)
(= (remainder b a) 0))
(define (cons a b)
(* (expt 2 a)
(expt 3 b)))
(define (car num)
(if (divides? 2 num)
(+ 1 (car (/ num 2)))
0))
(define (cdr num)
(if (divides? 3 num)
(+ 1 (cdr (/ num 3)))
0))
(car (cons 2 3))
(car (cons 5 2))
(cdr (cons 2 3))
(cdr (cons 5 2))
(divides? 3 5)
(divides? 3 6) | false |
89db8050ef5c348b931200ea6874246ec9c9db72 | 64e20bbf56596c58ef79306ea5b02744307b1af1 | /2015-2/practica3/practica3-base.rkt | 1973cc259f1a75aaddcd5096a34d449506fe5c58 | [
"MIT"
]
| permissive | hectoregm/lenguajes | d3dbe7a7992fd2e76c104f06ea275bca1a32b1de | c8a990f8db39bf448784de393b74744f4f2b0fa0 | refs/heads/master | 2020-04-28T12:11:59.101098 | 2015-12-13T02:54:50 | 2015-12-13T02:54:50 | 29,424,727 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,726 | rkt | practica3-base.rkt | #lang plai
(require 2htdp/image)
(print-only-errors false)
;; any? Dado cualquier valor x, regresa #t
;
(define (any? x) #t)
;; Tipo de datos seccion I
(define-type HRZ
[resting (low number?)
(high number?)]
[warm-up (low number?)
(high number?)]
[fat-burning (low number?)
(high number?)]
[aerobic (low number?)
(high number?)]
[anaerobic (low number?)
(high number?)]
[maximum (low number?)
(high number?)])
(define-type Time
[delta (distance number?)
(lhr number?)
(hhr number?)
(zone HRZ?)
(time number?)])
;; BTree - Tipo de dato
;
(define-type BTree
[EmptyBT]
[BNode (c procedure?) ; Funcion de comparacion, recibe dos argumentos,
; regresa un booleano.
(l BTree?)
(e any?)
(r BTree?)])
;; Abreviación de la hoja vacía
;
(define ebt (EmptyBT))
;(test (EmptyBT) ebt )
;; Abreviación del constructor de tipo BNode para números y para strings
;
(define-syntax-rule (bnn l v r) (BNode < l v r))
(define-syntax-rule (bns l v r) (BNode string<? l v r))
;(test (bnn ebt 4 ebt ) (BNode < (EmptyBT) 4 (EmptyBT)))
;(test (bns ebt "hola" ebt ) (BNode string<? (EmptyBT) "hola" (EmptyBT)))
;; Ejemplos de árboles de números
;
(define arb1 (bnn ebt 1 ebt))
(define arb2 (bnn arb1 2 arb1))
(define arb3 (bnn arb2 3 arb2))
(define arb4 (bnn arb3 4 arb3))
(define arbN
(bnn
(bnn (bnn ebt 4 ebt) 2 (bnn ebt 5 ebt))
1
(bnn (bnn (bnn ebt 7 ebt) 6 (bnn ebt 9 ebt)) 3 ebt)))
(define maxiarb (bnn arbN 10 arbN))
;; Lista de árboles numéricos
;
(define arb-list (list arb1 arb2 arb3 arb4 arbN maxiarb))
;; Ejemplos de árboles de strings
;
(define arb1s (bns ebt "a" ebt))
(define arb2s (bns arb1s "b" arb1s))
(define arb3s (bns arb2s "c" arb2s))
(define arb4s (bns arb3s "d" arb3s))
(define arbNs
(bns
(bns (bns ebt "adios" ebt) "que" (bns ebt "suc" ebt))
"cloj"
(bns (bns (bns ebt "pow" ebt) "ext" (bns ebt "trial" ebt)) "lambda" ebt)))
(define maxiarbs (bnn arbNs "racket" arbNs))
;; Lista de árboles de strings
;
(define arbs-list (list arb1s arb2s arb3s arb4s arbNs maxiarbs))
;; Arbol base Wikipedia
;
(define arbol-base (bns (bns (bns ebt "A" ebt) "B" (bns (bns ebt "C" ebt) "D" (bns ebt "E" ebt)))
"F"
(bns ebt "G" (bns (bns ebt "H" ebt) "I" ebt))))
;; Funciones auxiliares
;
(define (heightAB expArb)
(type-case BTree
expArb
[EmptyBT () 0]
[BNode (c l e r) (max (+ 1 (heightAB l) ) (+ 1 (heightAB r)) )]))
(define (a-label v)
(overlay
(if (number? v)
(text (number->string v) 12 "black")
(text v 12 "black"))
(circle 15 "solid" "lightblue")))
(define white-circle (circle 15 "solid" "white"))
(define black-circle (circle 15 "solid" "black"))
(define nothing (circle 0 "solid" "white"))
(define (print-list l)
(if (empty? l)
nothing
(beside (a-label (car l)) (print-list (cdr l)))))
(define (printBT-complete arb level)
(type-case BTree arb
[EmptyBT () (if (zero? level) nothing (above white-circle (beside (printBT-complete arb (sub1 level))
(printBT-complete arb (sub1 level)))))]
[BNode (c l v r) (if (zero? level)
(a-label v)
(let* ((lblack (line (* 15 (expt 2 (- level 2))) -30 "black"))
(rblack (line (* -15 (expt 2 (- level 2))) -30 "black"))
(lwhite (line (* 15 (expt 2 (- level 2))) -30 "white"))
(rwhite (line (* -15 (expt 2 (- level 2))) -30 "white"))
(d (above (a-label v) (beside (printBT-complete l (sub1 level))
(printBT-complete r (sub1 level))))))
(cond
((and (EmptyBT? l) (EmptyBT? r)) d)
((EmptyBT? l) (underlay/align/offset "middle" "top" (beside lwhite rblack) 0 -15 d))
((EmptyBT? r) (underlay/align/offset "middle" "top" (beside lblack rwhite) 0 -15 d))
(else (underlay/align/offset "middle" "top" (beside lblack rblack) 0 -15 d)))))]))
;; Imprime la representación gráfica de un BTree
;
(define (printBT arb)
(printBT-complete arb (heightAB arb)))
;; Murales de árboles de números
;
(define arb-drawings (map printBT arb-list))
(define arb-mural (apply beside arb-drawings))
;; Murales de árboles de strings
;
(define arbs-drawings (map printBT arbs-list))
(define arbs-mural (apply beside arbs-drawings)) | true |
69fdf044c3ecc329aa624d97e03807f31c236c61 | 69e94593296c73bdfcfc2e5a50fea1f5c5f35be1 | /Tutorials/Tut2/q16.rkt | 6917f14bc58e224e3a61405095eb288dd9305a01 | []
| no_license | nirajmahajan/CS152 | 7e64cf4b8ec24ed9c37ecc72c7731816089e959b | ef75b37715422bf96648554e74aa5ef6e36b9eb3 | refs/heads/master | 2020-05-29T18:02:08.993097 | 2019-05-29T20:35:06 | 2019-05-29T20:35:06 | 189,293,837 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 54 | rkt | q16.rkt | #lang racket
(define (reverse l)
(foldl cons '() l)) | false |
ddcbed0cb1ff449403b2cc30b24556e2e456f0d1 | e553691752e4d43e92c0818e2043234e7a61c01b | /rosette/base/core/real.rkt | b99c4a7eba6eda3f2fedb4c946084a245522e38a | [
"BSD-2-Clause"
]
| permissive | emina/rosette | 2b8c1bcf0bf744ba01ac41049a00b21d1d5d929f | 5dd348906d8bafacef6354c2e5e75a67be0bec66 | refs/heads/master | 2023-08-30T20:16:51.221490 | 2023-08-11T01:38:48 | 2023-08-11T01:38:48 | 22,478,354 | 656 | 89 | NOASSERTION | 2023-09-14T02:27:51 | 2014-07-31T17:29:18 | Racket | UTF-8 | Racket | false | false | 18,921 | rkt | real.rkt | #lang racket
(require (for-syntax racket/syntax) racket/stxparam racket/stxparam-exptime)
(require "term.rkt" "union.rkt" "bool.rkt" "polymorphic.rkt"
"merge.rkt" "safe.rkt" "lift.rkt" "forall.rkt")
(provide @integer? @real? @= @< @<= @>= @> @+ @* @- @/ @quotient @remainder @modulo @abs
@integer->real @real->integer @int?
lift-op numeric-coerce T*->integer? T*->real?)
;; ----------------- Integer and Real Types ----------------- ;;
(define (int? v)
(match v
[(? integer?) #t]
[(term _ (== @integer?)) #t]
[(term _ (== @real?)) (expression @int? v)]
[(union xs (or (== @real?) (== @any/c)))
(let-values ([(i r) (guarded-numbers xs)])
(match* (i r)
[((cons g _) #f) g]
[(#f (cons g x)) (&& g (int? x))]
[((cons gi _) (cons gr xr)) (|| gi (&& gr (int? xr)))]
[(_ _) #f]))]
[_ #f]))
(define-lifted-type @real?
#:base real?
#:is-a? (instance-of? real? @real?)
#:methods
[(define (least-common-supertype self t)
(if (or (equal? self t) (equal? @integer? t)) self @any/c))
(define (solvable-default self) 0)
(define (type-eq? self u v) ($= u v))
(define (type-equal? self u v) ($= u v))
(define (type-cast self v [caller 'type-cast])
(match v
[(? real?) v]
[(term _ (== self)) v]
[(term _ (== @integer?)) (integer->real v)]
[(union xs (or (== @real?) (== @any/c)))
(let-values ([(i r) (guarded-numbers xs)])
(match* (i r)
[((cons g x) #f)
(assert g (numeric-type-error caller @real? v))
(integer->real x)]
[(#f (cons g x))
(assert g (numeric-type-error caller @real? v))
x]
[((cons gi xi) (cons gr _))
(unless (= (length xs) 2)
(assert (|| gi gr) (numeric-type-error caller @real? v)))
(ite* (cons gi (integer->real xi)) r)]
[(_ _)
(assert #f (numeric-type-error caller @real? v))]))]
[_ (assert #f (numeric-type-error caller @real? v))]))
(define (type-compress self force? ps) (generic-merge* ps))])
(define-lifted-type @integer?
#:base integer?
#:is-a? int?
#:methods
[(define (least-common-supertype self t)
(if (or (equal? self t) (equal? @real? t)) t @any/c))
(define (solvable-default self) 0)
(define (type-eq? self u v) ($= u v))
(define (type-equal? self u v) ($= u v))
(define (type-cast self v [caller 'type-cast])
(match v
[(? integer?) v]
[(term _ (== self)) v]
[(term _ (== @real?))
(assert (int? v) (numeric-type-error caller @integer? v))
(real->integer v)]
[(union xs (or (== @real?) (== @any/c)))
(let-values ([(i r) (guarded-numbers xs)])
(match* (i r)
[((cons g x) #f)
(assert g (numeric-type-error caller @integer? v))
x]
[(#f (cons g x))
(assert (&& g (int? x)) (numeric-type-error caller @integer? v))
(real->integer x)]
[((cons gi xi) (cons gr xr))
(let ([gr (&& (int? xr) gr)])
(assert (|| gi gr) (numeric-type-error caller @integer? v))
(merge* i (cons gr (real->integer xr))))]
[(_ _) (assert #f (numeric-type-error caller @integer? v))]))]
[_ (assert #f (numeric-type-error caller @integer? v))]))
(define (type-compress self force? ps) (generic-merge* ps))])
;; ----------------- Lifting Utilities ----------------- ;;
(define (guarded-numbers xs)
(for/fold ([i #f][r #f]) ([gx xs])
(match (cdr gx)
[(or (? integer?) (term _ (== @integer?))) (values gx r)]
[(or (? real?) (term _ (== @real?))) (values i gx)]
[_ (values i r)])))
(define-match-expander ≈
(lambda (stx)
(syntax-case stx ()
[(_ v) #`(or v #,(exact->inexact (syntax->datum #'v)))])))
(define (numeric-coerce v [caller 'numeric-coerce])
(match v
[(? real?) v]
[(term _ (or (== @integer?) (== @real?))) v]
[(union xs (or (== @real?) (== @any/c)))
(let-values ([(i r) (guarded-numbers xs)])
(match* (i r)
[((cons g x) #f)
(assert g (numeric-type-error caller @real? v))
x]
[(#f (cons g x))
(assert g (numeric-type-error caller @real? v))
x]
[((cons gi _) (cons gr _))
(cond [(= (length xs) 2) v]
[else (assert (|| gi gr) (numeric-type-error caller @real? v))
(merge* i r)])]
[(_ _) (assert #f (numeric-type-error caller @real? v))]))]
[_ (assert #f (numeric-type-error caller @real? v))]))
(define (numeric-type-error name t . args)
(arguments-error name (format "expected ~a arguments" t) "arguments" args))
(define (safe-apply-1 op x)
(match (numeric-coerce x (object-name op))
[(union (list (cons ga a) (cons gb b)))
(merge* (cons ga (op a)) (cons gb (op b)))]
[a (op a)]))
(define (int-primitive? v)
(or (integer? v) (and (term? v) (equal? (get-type v) @integer?))))
(define (real-primitive? v)
(or (real? v) (and (term? v) (equal? (get-type v) @real?))))
(define (safe-apply-2 op x y)
(define caller (object-name op))
(define a (numeric-coerce x caller))
(define b (numeric-coerce y caller))
(match* (a b)
[((? int-primitive?)(? int-primitive?)) (op a b)]
[((? real-primitive?)(? real-primitive?)) (op a b)]
[(_ _) (op (type-cast @real? a caller) (type-cast @real? b caller))]))
(define (safe-apply-n op xs)
(define caller (object-name op))
(define ys (for/list ([x xs]) (numeric-coerce x caller)))
(match ys
[(or (list (? int-primitive?) ...) (list (? real-primitive?) ...)) (apply op ys)]
[_ (apply op (for/list ([y ys]) (type-cast @real? y caller)))]))
(define (lift-op op)
(case (procedure-arity op)
[(1) (lambda (x) (safe-apply-1 op x))]
[(2) (lambda (x y) (safe-apply-2 op x y))]
[else (case-lambda [() (op)]
[(x) (safe-apply-1 op x)]
[(x y) (safe-apply-2 op x y)]
[xs (safe-apply-n op xs)])]))
(define-syntax-rule (define-lifted-operator @op $op type)
(define-operator @op
#:identifier (string->symbol (substring (symbol->string '@op) 1))
#:range type
#:unsafe $op
#:safe (lift-op $op)))
;; ----------------- Predicates ----------------- ;;
(define-operator @int?
#:identifier 'int?
#:range T*->boolean?
#:unsafe int?
#:safe int?)
(define $= (compare @= $= = sort/expression #t))
(define $<= (compare @<= $<= <= expression #t))
(define $< (compare @< $< < expression #f))
(define $>= (case-lambda [(x y) ($<= y x)] [xs (apply $<= (reverse xs))]))
(define $> (case-lambda [(x y) ($< y x)] [xs (apply $< (reverse xs))]))
(define-syntax-rule (compare @op $op op expr same=true?)
(case-lambda
[(x y)
(match* (x y)
[((? real?) (? real?)) (op x y)]
[(_ (== x)) same=true?]
[((expression (== ite) a (? real? b) (? real? c)) (? real? d)) (merge a (op b d) (op c d))]
[((? real? d) (expression (== ite) a (? real? b) (? real? c))) (merge a (op d b) (op d c))]
[((expression (== ite) a (? real? b) (? real? c))
(expression (== ite) d (? real? e) (? real? f)))
(let ([b~e (op b e)]
[b~f (op b f)]
[c~e (op c e)]
[c~f (op c f)])
(or (and b~e b~f c~e c~f)
(|| (&& a d b~e) (&& a (! d) b~f) (&& (! a) d c~e) (&& (! a) (! d) c~f))))]
[(a (expression (== @+) (? real? r) a)) (op 0 r)]
[((expression (== @+) (? real? r) a) a) (op r 0)]
[(_ _) (expr @op x y)])]
[(x y . zs)
(apply && ($op x y) (for/list ([a (in-sequences (in-value y) zs)][b zs]) ($op a b)))]))
(define-lifted-operator @= $= T*->boolean?)
(define-lifted-operator @<= $<= T*->boolean?)
(define-lifted-operator @>= $>= T*->boolean?)
(define-lifted-operator @< $< T*->boolean?)
(define-lifted-operator @> $> T*->boolean?)
;; ----------------- Int and Real Operators ----------------- ;;
(define $+
(case-lambda
[() 0]
[(x) x]
[(x y) (or (simplify-+ x y) (sort/expression @+ x y))]
[xs
(let*-values ([(lits terms) (partition real? xs)]
[(lit) (apply + lits)])
(if (null? terms)
lit
(match (simplify* (if (= 0 lit) terms (cons lit terms)) simplify-+)
[(list y) y]
[(list a ... (? real? b) c ...) (apply expression @+ b (sort (append a c) term<?))]
[ys (apply expression @+ (sort ys term<?))])))]))
(define $*
(case-lambda
[() 1]
[(x) x]
[(x y) (or (simplify-* x y) (sort/expression @* x y))]
[xs
(let*-values ([(lits terms) (partition real? xs)]
[(lit) (apply * lits)])
(if (or (zero? lit) (null? terms))
lit
(match (simplify* (if (= 1 lit) terms (cons lit terms)) simplify-*)
[(list y) y]
[(list a ... (? real? b) c ...) (apply expression @* b (sort (append a c) term<?))]
[ys (apply expression @* (sort ys term<?))])))]))
(define $-
(case-lambda
[(x) (match x
[(? real?) (- x)]
[(expression (== @-) a) a]
[(expression (== @*) (? real? c) a) ($* (- c) a)]
[_ (expression @- x)])]
[(x y) ($+ x ($- y))]
[(x . xs) (apply $+ x (map $- xs))]))
(define ($abs x)
(match x
[(? real?) (abs x)]
[(expression (== @abs) _) x]
[_ (expression @abs x)]))
(define-lifted-operator @+ $+ T*->T)
(define-lifted-operator @* $* T*->T)
(define-lifted-operator @- $- T*->T)
(define-lifted-operator @abs $abs T*->T)
;; ----------------- Int Operators ----------------- ;;
(define $quotient (div @quotient $quotient quotient))
(define-syntax-rule (define-remainder $op op @op)
(define ($op x y)
(match* (x y)
[((? integer?) (? integer?)) (op x y)]
[(_ (≈ 1)) 0]
[(_ (≈ -1)) 0]
[((≈ 0) _) 0]
[(_ (== x)) 0]
[(_ (expression (== @-) (== x))) 0]
[((expression (== @-) (== y)) _) 0]
[((expression (== @*) _ (... ...) (== y) _ (... ...)) _) 0]
[((expression (== ite) a (? real? b) (? real? c)) (? real?))
(merge a (op b y) (op c y))]
[((? real?) (expression (== ite) a
(and b (? real?) (not (? zero?)))
(and c (? real?) (not (? zero?)))))
(merge a (op x b) (op x c))]
[(_ _) (expression @op x y)])))
(define-remainder $remainder remainder @remainder)
(define-remainder $modulo modulo @modulo)
(define T*->integer? (const @integer?))
(define (undefined-for-zero-error name)
(arguments-error name "undefined for 0"))
(define-syntax-rule (define-lifted-int-operator @op $op op)
(define-operator @op
#:identifier 'op
#:range T*->integer?
#:unsafe $op
#:safe (lambda (x y)
(let ([a (type-cast @integer? x 'op)]
[b (type-cast @integer? y 'op)])
(assert (! ($= b 0)) (undefined-for-zero-error 'op))
($op a b)))))
(define-lifted-int-operator @quotient $quotient quotient)
(define-lifted-int-operator @remainder $remainder remainder)
(define-lifted-int-operator @modulo $modulo modulo)
;; ----------------- Real Operators ----------------- ;;
(define $/ (div @/ $/ /))
(define T*->real? (const @real?))
(define-operator @/
#:identifier '/
#:range T*->real?
#:unsafe $/
#:safe (case-lambda
[(x) (@/ 1 x)]
[(x y) (let ([a (type-cast @real? x '/)]
[b (type-cast @real? y '/)])
(assert (! ($= 0 b)) (undefined-for-zero-error '/))
($/ a b))]
[(x . ys) (let ([z (type-cast @real? x '/)]
[zs (for/list ([y ys]) (type-cast @real? y '/))])
(for ([z zs])
(assert (! ($= z 0)) (undefined-for-zero-error '/)))
($/ x (apply $* zs)))]))
;; ----------------- Coercion Operators ----------------- ;;
(define (integer->real i)
(match i
[(? integer?) i]
[(? term?) (expression @integer->real i)]))
(define (real->integer r)
(match r
[(? real?) (floor r)]
[(expression (== @integer->real) x) x]
[(expression (== ite) a
(expression (== @integer->real) x)
(expression (== @integer->real) y)) (ite a x y)]
[(expression (== ite) a (expression (== @integer->real) x) y) (ite a x (real->integer y))]
[(expression (== ite) a x (expression (== @integer->real) y)) (ite a (real->integer x) y)]
[(? term?) (expression @real->integer r)]))
(define-operator @integer->real
#:identifier 'integer->real
#:range T*->real?
#:unsafe integer->real
#:safe (lambda (n) (integer->real (type-cast @integer? n 'integer->real))))
(define-operator @real->integer
#:identifier 'real->integer
#:range T*->integer?
#:unsafe real->integer
#:safe (lambda (n) (real->integer (type-cast @real? n 'real->integer))))
;; ----------------- Simplification rules for operators ----------------- ;;
(define (simplify-+ x y)
(match* (x y)
[((? real?) (? real?)) (+ x y)]
[(_ (≈ 0)) x]
[((≈ 0) _) y]
[((? expression?) (? expression?))
(or (simplify-+:expr/term x y) (simplify-+:expr/term y x))]
[((? expression?) _) (simplify-+:expr/term x y)]
[(_ (? expression?)) (simplify-+:expr/term y x)]
[(_ _) #f]))
(define (simplify-+:expr/term x y)
(match* (x y)
[((expression (== @-) (== y)) _) 0]
[((expression (== @-) (expression (== @+) (== y) z)) _) ($- z)]
[((expression (== @-) (expression (== @+) z (== y))) _) ($- z)]
[((expression (== @+) (expression (== @-) (== y)) z) _) z]
[((expression (== @+) z (expression (== @-) (== y))) _) z]
[((expression (== @+) (? real? a) b) (? real?)) ($+ (+ a y) b)]
[((expression (== ite) a (? real? b) (? real? c)) (? real?)) (ite a (+ b y) (+ c y))]
[((expression (== @*) (? real? a) (== y)) _) ($* (+ a 1) y)]
[((expression (== @*) (? real? a) b) (expression (== @*) (? real? c) b)) ($* (+ a c) b)]
[((expression (== @+) a b) (expression (== @-) a)) b]
[((expression (== @+) a b) (expression (== @-) b)) a]
[((expression (== @+) as ...) (expression (== @+) bs ...))
(let ([alen (length as)]
[blen (length bs)])
(and (<= alen blen) (<= (- blen alen) 1)
(match (cancel+ as bs)
[(list) 0]
[(list b) b]
[#f #f])))]
[(_ _) #f]))
(define (cancel+ xs ys)
(and ys
(match xs
[(list) ys]
[(list x rest ...)
(cancel+ rest
(match* (x ys)
[((? real?) (list (? real? a) b ...)) (and (zero? (+ x a)) b)]
[((? term?) (list a ... (expression (== @-) (== x)) b ...)) (append a b)]
[((expression (== @-) y) (list a ... y b ...)) (append a b)]
[((expression (== @*) (? real? a) b)
(list c ... (expression (== @*) (and (? real?) (app - a)) b) d ...))
(append c d)]
[(_ _) #f]))])))
(define (simplify-* x y)
(match* (x y)
[((? real?) (? real?)) (* x y)]
[((≈ 0) _) 0]
[((≈ 1) _) y]
[((≈ -1) _) ($- y)]
[(_ (≈ 0)) 0]
[(_ (≈ 1)) x]
[(_ (≈ -1)) ($- x)]
[((? expression?) (? expression?))
(or (simplify-*:expr/term x y) (simplify-*:expr/term y x))]
[((? expression?) _) (simplify-*:expr/term x y)]
[(_ (? expression?)) (simplify-*:expr/term y x)]
[(_ _) #f]))
(define (simplify-*:expr/term x y)
(match* (x y)
[((expression (== @/) a (== y)) _) a]
[((expression (== @/) a (expression (== @*) (== y) z)) _) ($/ a z)]
[((expression (== @/) a (expression (== @*) z (== y))) _) ($/ a z)]
[((expression (== @/) (? real? a) b) (? real?)) ($/ (* a y) b)]
[((expression (== @*) (expression (== @/) a (== y)) z) _) ($* a z)]
[((expression (== @*) z (expression (== @/) a (== y))) _) ($* a z)]
[((expression (== @*) (? real? a) b) (? real?)) ($* (* a y) b)]
[((expression (== ite) a (? real? b) (? real? c)) (? real?)) (ite a (* b y) (* c y))]
[((expression (== @*) a b) (expression (== @/) c a)) ($* b c)]
[((expression (== @*) a b) (expression (== @/) c b)) ($* a c)]
[((expression (== @*) as ...) (expression (== @*) bs ...))
(let ([alen (length as)]
[blen (length bs)])
(and (<= alen blen) (<= (- blen alen) 1)
(match (cancel* as bs)
[(list) 1]
[(list b) b]
[#f #f])))]
[(_ _) #f]))
(define (cancel* xs ys) ;(printf "cancel* ~a ~a\n" xs ys)
(and ys
(match xs
[(list) ys]
[(list x rest ...)
(cancel* rest
; Pattern matching broken in 6.1 when the first rule is in the third position.
; TODO: place the first rule in 3rd position and test with 6.2.
(match* (x ys)
[((expression (== @/) (≈ 1) c) (list a ... c b ...))
(append a b)]
[((? term?) (list a ... (expression (== @/) 1 (== x)) b ...)) (append a b)]
[((? real?) (list (? real? a) b ...)) (and (= 1 (* x a)) b)]
[(_ _) #f]))])))
(define-syntax-rule (div @op $op op)
(lambda (x y)
(match* (x y)
[((? real?) (? real?)) (op x y)]
[((≈ 0) _) 0]
[(_ (≈ 1)) x]
[(_ (≈ -1)) ($- x)]
[(_ (== x)) 1]
[(_ (expression (== @-) (== x))) -1]
[((expression (== @-) (== y)) _) -1]
[((expression (== ite) a (? real? b) (? real? c)) (? real?))
(merge a (op b y) (op c y))]
[((? real?) (expression (== ite) a
(and b (? real?) (not (? zero?)))
(and c (? real?) (not (? zero?)))))
(merge a (op x b) (op x c))]
[((expression (== @op) a (? real? b)) (? real?)) ($op a (* b y))]
[((expression (== @*) a (... ...) (== y) b (... ...)) _) (apply $* (append a b))]
[((expression (== @*) as (... ...)) (expression (== @*) bs (... ...)))
(or (and (<= (length bs) (length as))
(let ([cs (cancel-div bs as)])
(and cs (apply $* cs))))
(expression @op x y))]
[(_ _) (expression @op x y)])))
(define (cancel-div xs ys)
(and ys
(match xs
[(list) ys]
[(list x rest ...)
(cancel-div rest
(match* (x ys)
[((? real?) (list (== x) b ...)) b]
[(_ (list a ... (== x) b ...)) (append a b)]
[(_ _) #f]))])))
| true |
fcdc7396beef0cbf35b51edf7a0efc07a636e27b | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/character-codes.rkt | ab28419f41ce8d01b99973fb6bf78cf3f4b59ffa | []
| no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867677 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 242 | rkt | character-codes.rkt | #lang racket
(define (code ch)
(printf "The unicode number for ~s is ~a\n" ch (char->integer ch)))
(code #\a)
(code #\λ)
(define (char n)
(printf "The unicode number ~a is the character ~s\n" n (integer->char n)))
(char 97)
(char 955)
| false |
6defbb98b1aa43f81c357e8eee609b8ee65d843f | 3b2cf17b2d77774a19e9a9540431f1f5a840031e | /src/info.rkt | db48b8e6c1fc9a683058f16d1046a188035e8732 | []
| no_license | brownplt/pyret-lang-resugarer | 5bfaa09e52665657abad8d9d863e8915e0029a29 | 49519679aefb7b280a27938bc7bfbaaecc0bd4fc | HEAD | 2016-09-06T03:59:24.608789 | 2014-06-27T03:45:02 | 2014-06-27T03:45:02 | 13,936,477 | 1 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 194 | rkt | info.rkt | #lang setup/infotab
(define name "pyret")
(define pre-install-collection "setup.rkt")
(define raco-commands
'(("pyret" pyret/cmdline "Run commands related to the Pyret language" 100)))
| false |
5153b36fd29159c70653faacbe71d9bdb0008487 | 9ef0b809bd17c71bcb30bc9f0037713a116c9495 | /private/test/sample-deep-shallow-untyped-target/untyped/a1.rkt | 9ad8441036544adf6395211c315c80e84046ea2a | [
"MIT"
]
| permissive | utahplt/gtp-measure | 1403b73e9295397a33d1ad7f658a089a2c41d325 | 985c62ffec08f5036092b97f808d74041e5138d3 | refs/heads/master | 2023-05-31T01:28:02.440466 | 2023-04-24T19:16:18 | 2023-04-24T19:16:46 | 119,434,878 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 29 | rkt | a1.rkt | #lang racket/base
(void 'a1)
| false |
05e9167c468a81c7439d12962fe5922309163310 | 67f496ff081faaa375c5000a58dd2c69d8aeec5f | /koyo-test/koyo/hasher.rkt | 370f20cd4b118a3fdc326b4f0b716505f9a0fa6c | [
"BSD-3-Clause"
]
| permissive | Bogdanp/koyo | e99143dd4ee918568ed5b5b199157cd4f87f685f | a4dc1455fb1e62984e5d52635176a1464b8753d8 | refs/heads/master | 2023-08-18T07:06:59.433041 | 2023-08-12T09:24:30 | 2023-08-12T09:24:30 | 189,833,202 | 127 | 24 | null | 2023-03-12T10:24:31 | 2019-06-02T10:32:01 | Racket | UTF-8 | Racket | false | false | 789 | rkt | hasher.rkt | #lang racket/base
(require component/testing
koyo/hasher
rackunit)
(provide
hasher-tests)
(define hasher-tests
(system-test-suite hasher-tests ([a (h) void]
[h (make-argon2id-hasher-factory
#:parallelism 1
#:iterations 128
#:memory 1024)])
(test-case "passwords can be hashed and then verified"
(define pass-hash (hasher-make-hash h "supersecret"))
(check-false (hasher-hash-matches? h pass-hash "invalid"))
(check-true (hasher-hash-matches? h pass-hash "supersecret")))))
(module+ test
(require rackunit/text-ui)
(unless (getenv "PLT_PKG_BUILD_SERVICE")
(run-tests hasher-tests)))
| false |
fed176b745a13ed2c5c807b7acee35c1b20e9e57 | 56bd3e3c44345a80d1e67ff3844a615eeaae0108 | /Carrom.rkt | d5cc5dcf53a210795da4e68d14d0f07a88e7156d | []
| no_license | kushagra1729/Carrom | 82146d4aef33d289907ae9bf61e952ccac096594 | ac8d756f04f7db1d9cbce784bc6dc8e8dc70f60a | refs/heads/master | 2020-03-14T11:42:48.267092 | 2018-07-25T17:04:59 | 2018-07-25T17:04:59 | 131,596,103 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 44,220 | rkt | Carrom.rkt | #lang racket
(require 2htdp/universe)
(require 2htdp/image)
(require lang/posn)
(define states 'main-menu)
(define red (circle 10 "solid" "crimson"))
(define black (circle 10 "solid" "black"))
(define white (circle 10 "solid" "navajowhite"))
(define blue (circle 10 "solid" "blue"))
(define coin-m 23) ;decide later
(define striker-m 32) ;decide later
(define coin-r 10)
(define striker-r 12.5)
(define coin-coeff 5) ;decide later
(define striker-coeff 5) ;decide later
(define pocket-r 16)
(define max-power 1000)
(define x0 20)
(define y0 20)
(define x1 520)
(define y1 520)
(define midx (/ (+ x0 x1) 2))
(define midy (/ (+ y0 y1) 2))
(define edges (* 0.1 (- x1 x0)))
(define e-wall 0.7) ;decide later
(define e-discs 0.9) ;decide later
(define pockets (list (cons (+ x0 pocket-r) (+ y0 pocket-r)) (cons (- x1 pocket-r) (+ y0 pocket-r))
(cons (+ x0 pocket-r) (- y1 pocket-r)) (cons (- x1 pocket-r) (- y1 pocket-r))))
(define mode 0)
(define turn 0)
(define time 0)
(define static 0.5) ; changed by Kushagra
(define del-t (/ 1 50))
(define g 9.81)
(define-syntax myfor
(syntax-rules (:)
[(myfor init : condition : step : statements)
(begin init (define (iter) (cond [condition (begin statements step (iter))])) (iter))]))
(struct state (str coi str-o coi-o qt nqt coi-t scr turn-end) #:transparent)
(struct disc (color mass radius coeff x y vx vy) #:transparent #:mutable)
(define striker (disc blue striker-m striker-r striker-coeff midx (+ y0 edges) 0 0))
(define coins (build-vector 19 (lambda (z) (disc (if (= z 0) red (if (= 0 (remainder z 2)) black white))
coin-m coin-r coin-coeff
(+ midx (if (= z 0) 0 (if (< z 7) (* 2 coin-r (cos (* z (/ pi 3))))
(* 2 (if (= 0 (remainder z 2)) (sqrt 3) 2) coin-r
(cos (* (- z 7) (/ pi 6)))))))
(+ midy (if (= z 0) 0 (if (< z 7) (* 2 coin-r (sin (* z (/ pi 3))))
(* 2 (if (= 0 (remainder z 2)) (sqrt 3) 2) coin-r
(sin (* (- z 7) (/ pi 6)))))))
0 0))))
(define (magn a b)
(sqrt (+ (* a a) (* b b))))
(define (wall-collision disc1)
(cond[(> (disc-x disc1) (- x1 (disc-radius disc1))) (begin (set-disc-x! disc1 (- (* (+ 1 e-wall) (- x1 (disc-radius disc1))) (* e-wall (disc-x disc1))))
(set-disc-vx! disc1 (* -1 (disc-vx disc1) e-wall)))]
[(> (disc-y disc1) (- y1 (disc-radius disc1))) (begin (set-disc-y! disc1 (- (* (+ 1 e-wall) (- y1 (disc-radius disc1))) (* e-wall (disc-y disc1))))
(set-disc-vy! disc1 (* -1 (disc-vy disc1) e-wall)))]
[(< (disc-x disc1) (+ x0 (disc-radius disc1))) (begin (set-disc-x! disc1 (- (* (+ 1 e-wall) (+ x0 (disc-radius disc1))) (* e-wall (disc-x disc1))))
(set-disc-vx! disc1 (* -1 (disc-vx disc1) e-wall)))]
[(< (disc-y disc1) (+ y0 (disc-radius disc1))) (begin (set-disc-y! disc1 (- (* (+ 1 e-wall) (+ y0 (disc-radius disc1))) (* e-wall (disc-y disc1))))
(set-disc-vy! disc1 (* -1 (disc-vy disc1) e-wall)))]
[else '()]))
(define (collision disc1 disc2)
(begin
(set-disc-x! disc1 (- (disc-x disc1) (* del-t (disc-vx disc1))))
(set-disc-x! disc2 (- (disc-x disc2) (* del-t (disc-vx disc2))))
(set-disc-y! disc1 (- (disc-y disc1) (* del-t (disc-vy disc1))))
(set-disc-y! disc2 (- (disc-y disc2) (* del-t (disc-vy disc2))))
(define d0 (magn (- (disc-x disc2) (disc-x disc1)) (- (disc-y disc2) (disc-y disc1))))
(define cos0 (/ (- (disc-x disc2) (disc-x disc1)) d0))
(define sin0 (/ (- (disc-y disc2) (disc-y disc1)) d0))
(define h10 (+ (* (disc-vx disc1) cos0) (* (disc-vy disc1) sin0)))
(define h20 (+ (* (disc-vx disc2) cos0) (* (disc-vy disc2) sin0)))
(define hp10 (- (* (disc-vy disc1) cos0) (* (disc-vx disc1) sin0)))
(define hp20 (- (* (disc-vy disc2) cos0) (* (disc-vx disc2) sin0)))
(define relvel (magn (- h10 h20) (- hp10 hp20)))
(define sin2t (with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ (* (- hp10 hp20) (- hp10 hp20)) (* relvel relvel))))
(define cost (with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ (abs (- h10 h20)) relvel)))
(define d1 (+ (disc-radius disc1) (disc-radius disc2)))
(define dc (sqrt (- (+ (* d1 d1) (* d0 d0)) (+ (* 2 d0 d0 sin2t) (* 2 d0 cost (sqrt (- (* d1 d1) (* d0 d0 sin2t))))))))
(define tc (with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ dc relvel)))
(set-disc-x! disc1 (+ (disc-x disc1) (* tc (disc-vx disc1))))
(set-disc-x! disc2 (+ (disc-x disc2) (* tc (disc-vx disc2))))
(set-disc-y! disc1 (+ (disc-y disc1) (* tc (disc-vy disc1))))
(set-disc-y! disc2 (+ (disc-y disc2) (* tc (disc-vy disc2))))
(define cos1 (/ (- (disc-x disc2) (disc-x disc1)) d1))
(define sin1 (/ (- (disc-y disc2) (disc-y disc1)) d1))
(define h11 (+ (* (disc-vx disc1) cos1) (* (disc-vy disc1) sin1)))
(define h21 (+ (* (disc-vx disc2) cos1) (* (disc-vy disc2) sin1)))
(define hp11 (- (* (disc-vy disc1) cos1) (* (disc-vx disc1) sin1)))
(define hp21 (- (* (disc-vy disc2) cos1) (* (disc-vx disc2) sin1)))
(define u1 (/ (- (+ (* (disc-mass disc1) h11) (* (disc-mass disc2) h21)) (* (disc-mass disc2) e-discs (- h11 h21))) (+ (disc-mass disc1) (disc-mass disc2))))
(define u2 (/ (+ (* (disc-mass disc1) h11) (* (disc-mass disc2) h21) (* (disc-mass disc1) e-discs (- h11 h21))) (+ (disc-mass disc1) (disc-mass disc2))))
(set-disc-vx! disc1 (- (* u1 cos1) (* sin1 hp11)))
(set-disc-vy! disc1 (+ (* u1 sin1) (* hp11 cos1)))
(set-disc-vx! disc2 (- (* u2 cos1) (* sin1 hp21)))
(set-disc-vy! disc2 (+ (* u2 sin1) (* hp21 cos1)))
(set-disc-x! disc1 (+ (disc-x disc1) (* (- del-t tc) (disc-vx disc1))))
(set-disc-x! disc2 (+ (disc-x disc2) (* (- del-t tc) (disc-vx disc2))))
(set-disc-y! disc1 (+ (disc-y disc1) (* (- del-t tc) (disc-vy disc1))))
(set-disc-y! disc2 (+ (disc-y disc2) (* (- del-t tc) (disc-vy disc2))))
))
(define (put-back coin-out coins) ;if striker is out -remember to add to queen putback if its queen turn and foul together
(define dummy 0)
(define poslist (map cons (map (lambda (z) (+ midx (if (= z 0) 0 (if (< z 7) (* 2 coin-r (cos (* z (/ pi 3))))
(* 2 (if (= 0 (remainder z 2)) (sqrt 3) 2) coin-r
(cos (* (- z 7) (/ pi 6)))))))) (range 19))
(map (lambda (z) (+ midy (if (= z 0) 0 (if (< z 7) (* 2 coin-r (sin (* z (/ pi 3))))
(* 2 (if (= 0 (remainder z 2)) (sqrt 3) 2) coin-r
(sin (* (- z 7) (/ pi 6)))))))) (range 19))))
(define (in-region x y vec)
(ormap (lambda (z) (let ([vec-z-x (disc-x (vector-ref vec z))]
[vec-z-y (disc-y (vector-ref vec z))])
(< (magn (- x vec-z-x) (- y vec-z-y)) (* 2 coin-r)))) (range 19)))
(define (bestfit lst vec)
(cond [(null? (cdr lst)) (car lst)]
[(in-region (caar lst) (cdar lst) vec) (bestfit (cdr lst) vec)]
[else (car lst)]))
(define pos (bestfit poslist coins))
(begin
(myfor (define z 2) : (< z 19) : (set! z (+ z 2)) : (if (and (equal? (vector-ref coin-out z) turn) (= dummy 0))
(begin (vector-set! coin-out z #f)
(set-disc-x! (vector-ref coins z) (car pos))
(set-disc-y! (vector-ref coins z) (cdr pos))
(set-disc-vx! (vector-ref coins z) 0)
(set-disc-vy! (vector-ref coins z) 0)
(set! dummy 10)) '()))
(myfor (set! z 1) : (< z 19) : (set! z (+ z 2)) : (if (and (equal? (vector-ref coin-out z) turn) (= dummy 0))
(begin (vector-set! coin-out z #f)
(set-disc-x! (vector-ref coins z) (car pos))
(set-disc-y! (vector-ref coins z) (cdr pos))
(set-disc-vx! (vector-ref coins z) 0)
(set-disc-vy! (vector-ref coins z) 0)
(set! dummy 20)) '()))
(if (and (equal? (vector-ref coin-out 0) turn) (= dummy 0)) (begin (vector-set! coin-out 0 #f)
(set-disc-x! (vector-ref coins 0) midx)
(set-disc-y! (vector-ref coins 0) midy)
(set-disc-vx! (vector-ref coins 0) 0)
(set-disc-vy! (vector-ref coins 0) 0)
(set! dummy 50)) '())
dummy))
; turn is a global variable where 0 means up and 1 means below
;per unit time interval(0.01s ), the number of pixels travelled
(define speed (+ (quotient max-power 3) (random (quotient max-power 3))))
(define y-val 470)
(define x-val-l 90)
(define x-val-r 450)
(define coin-radius 10)
(define striker-radius 12.5); change it if necessary
(define corners (list->vector (list (cons 36 504) (cons 504 504) (cons 504 36) (cons 36 36))))
(define delta-x 10)
;later move it inside the function
(define curstate #f)
(define striker-x midx)
(define striker-vx 0)
(define striker-vy (- speed))
;(define x-list (map (lambda(x) (* x delta-x)) (range 0 (+ 1 (quotient (- x-val-r x-val-l) delta-x)))))
(define striker-poss (build-vector (+ (quotient (- x-val-r x-val-l) delta-x) 1)
(lambda (x) (cons (+ x-val-l (* x delta-x)) y-val))))
(define (dist a b)
(sqrt (+ (expt (- (car a) (car b)) 2) (expt (- (cdr a) (cdr b)) 2))))
;find area of triangle formed by three points
(define (area p q r)
(let* ([x1 (car p)]
[y1 (cdr p)]
[x2 (car q)]
[y2 (cdr q)]
[x3 (car r)]
[y3 (cdr r)])
(/ (abs (- (+ (* x2 y3) (* x3 y1) (* x1 y2)) (+ (* x3 y2) (* x1 y3) (* x2 y1)))) 2)))
;vectorizes two points
(define (vectorize i f)
(cons (- (car f) (car i)) (- (cdr f) (cdr i))))
(define (dot-product v1 v2)
(+ (* (car v1) (car v2)) (* (cdr v1) (cdr v2))))
;p and q are a pair of coordinates of the form x and y
(define (min-dist p q x)
(define perp (/ (* 2 (area p q x)) (dist p q)))
(if (and (> (dot-product (vectorize q x) (vectorize q p)) 0) (> (dot-product (vectorize p x) (vectorize p q)) 0))
perp (min (dist p x) (dist q x))))
; q-p vector
(define (cosine p q)
(/ (- (car q) (car p)) (sqrt (+ (expt (- (car q) (car p)) 2) (expt (- (cdr q) (cdr p)) 2)))))
(define (sine p q)
(/ (- (cdr q) (cdr p)) (sqrt (+ (expt (- (car q) (car p)) 2) (expt (- (cdr q) (cdr p)) 2)))))
(define (extend-vec p q)
(cons (+ (car q) (* (+ striker-radius coin-radius) (cosine p q))) (+ (cdr q) (* (+ striker-radius coin-radius) (sine p q)))))
;coordinates of the hole must be given
(define (possible-coin hole coin-num)
(define table (state-coi curstate))
(define poss #t)
(myfor (begin
(define i 0)
(define fixed (vector-ref table coin-num))
(define pos1 (cons (disc-x fixed) (disc-y fixed)))):
(< i 19):(set! i (+ i 1)):
(let* ([var (vector-ref table i)]
[pos2 (cons (disc-x var) (disc-y var))]
[p (or (equal? coin-num i) (> (min-dist hole pos1 pos2) (* 1.999 coin-radius)))])
(set! poss (and poss p))))
(begin
;(displayln poss)
poss))
; pos1 is the position of the striker and point is the destination
(define (possible-striker point pos1 coin-num)
(define table (state-coi curstate))
(define poss #t)
(myfor (define i 0):
(< i 19):(set! i (+ i 1)):
(let* ([var (vector-ref table i)]
[pos2 (cons (disc-x var) (disc-y var))]
[p (or (= coin-num i) (> (min-dist point pos1 pos2) (* 0.999 (+ striker-radius coin-radius))))]) ; 0.999
(begin
;(displayln poss)
(set! poss (and poss p)))))
(begin
;(displayln poss)
poss))
(define (possible-overall hole coin-num striker-pos)
(define table (state-coi curstate))
(define fixed (vector-ref table coin-num))
(define pos1 (cons (disc-x fixed) (disc-y fixed)))
(define newpos (extend-vec hole pos1))
(let* ([a (and (possible-striker newpos striker-pos coin-num) (possible-coin hole coin-num)
(< (dot-product (vectorize newpos hole) (vectorize newpos striker-pos)) 0))])
(begin
;(displayln a)
a)))
(struct striker-state (x vx vy angle) #:mutable #:transparent)
;assume that Akshat has a function called end-state which gives the last state given a particular state
(define (find-best curstate1)
(begin
(define vec (make-vector 3 (striker-state #f #f #f 2)))
(set! striker-x midx)
(set! striker-vx 0)
(set! striker-vy (- speed))
(set! curstate curstate1)
(define vector-coins (state-coi curstate))
(myfor (define hole 2):
(< hole 4):
(set! hole (+ hole 1)):
(myfor (define striker 0):
(< striker (vector-length striker-poss)):
(set! striker (+ striker 1)):
(myfor (define coin 0):
(< coin 19):
(set! coin (+ coin 1)):
(begin
(define p (possible-overall (vector-ref corners hole) coin (vector-ref striker-poss striker)))
;(if p (displayln "YES") 0)
(if (and p (not (vector-ref (state-coi-o curstate) coin)))
(begin
;(displayln "YES")
;(set! striker-x (car (vector-ref striker-poss striker)))
(let()
(define index (cond [(= coin 0) 0]
[(= (remainder coin 2) 1) 1]
[else 2]))
(define act-coin (vector-ref vector-coins coin))
(define pos-coin (cons (disc-x act-coin) (disc-y act-coin)))
(define dest (extend-vec (vector-ref corners hole) pos-coin))
(define cos-angle (/ (dot-product (vectorize pos-coin (vector-ref corners hole))
(vectorize pos-coin (vector-ref striker-poss striker)))
(* (dist pos-coin (vector-ref corners hole))
(dist pos-coin (vector-ref striker-poss striker)))))
; cos-angle should be minimum
(define origin (vector-ref striker-poss striker))
(if (and (< (sine origin dest) 0) (< cos-angle (striker-state-angle (vector-ref vec index))))
(begin
(set-striker-state-angle! (vector-ref vec index) cos-angle)
(set-striker-state-x! (vector-ref vec index) (car (vector-ref striker-poss striker)))
(set-striker-state-vx! (vector-ref vec index) (* speed (cosine origin dest)))
(set-striker-state-vy! (vector-ref vec index) (* speed (sine origin dest))))
0))
)
;(displayln (cosine dest origin))
;(displayln (sine dest origin))
;(set! striker-vx (* speed (cosine origin dest)))
;(set! striker-vy (* speed (sine origin dest)))
0)))))
; set everything
(define best-id #f)
(cond [(not (equal? (striker-state-x (vector-ref vec 0)) #f)) (set! best-id 0)]
[(not (equal? (striker-state-x (vector-ref vec 1)) #f)) (set! best-id 1)]
[(not (equal? (striker-state-x (vector-ref vec 2)) #f)) (set! best-id 2)])
(if (equal? best-id #f)
(begin
(set-disc-x! (state-str curstate1) striker-x)
(set-disc-vx! (state-str curstate1) striker-vx)
(set-disc-vy! (state-str curstate1) striker-vy))
(begin
(set-disc-x! (state-str curstate1) (striker-state-x (vector-ref vec best-id)))
(set-disc-vx! (state-str curstate1) (striker-state-vx (vector-ref vec best-id)))
(set-disc-vy! (state-str curstate1) (striker-state-vy (vector-ref vec best-id)))))
))
(define (pass-time ws)
(define striker (state-str ws))
(define coins (state-coi ws))
(define striker-out (state-str-o ws))
(define coin-out (state-coi-o ws))
(define score (state-scr ws))
(define queen-turn (state-qt ws))
(define next-queen-turn (state-nqt ws))
(define coin-taken (state-coi-t ws))
(define turn-end (state-turn-end ws))
(begin
(if (and (= mode 1) turn-end (= turn 1)) (begin (find-best ws) (set! turn-end #f)) '())
(if striker-out '()
(let ([vel-magn (magn (disc-vx striker) (disc-vy striker))])
(begin (set-disc-x! striker (+ (disc-x striker) (* del-t (disc-vx striker))))
(set-disc-y! striker (+ (disc-y striker) (* del-t (disc-vy striker))))
(set-disc-vx! striker (- (disc-vx striker) (with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ (* del-t (disc-coeff striker) g (disc-vx striker)) vel-magn))))
(set-disc-vy! striker (- (disc-vy striker) (with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ (* del-t (disc-coeff striker) g (disc-vy striker)) vel-magn))))
(if (and (< (abs (disc-vx striker)) static) (< (abs (disc-vy striker)) static)) (begin (set-disc-vx! striker 0) (set-disc-vy! striker 0)) '()))))
(myfor (define z 0) : (< z 19) : (set! z (+ z 1)) : (let ([coins-z (vector-ref coins z)])
(if (vector-ref coin-out z) '()
(let ([vel-magn (magn (disc-vx coins-z) (disc-vy coins-z))])
(begin (set-disc-x! coins-z (+ (disc-x coins-z) (* del-t (disc-vx coins-z))))
(set-disc-y! coins-z (+ (disc-y coins-z) (* del-t (disc-vy coins-z))))
(set-disc-vx! coins-z (- (disc-vx coins-z)
(with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ (* del-t (disc-coeff coins-z) g (disc-vx coins-z)) vel-magn))))
(set-disc-vy! coins-z (- (disc-vy coins-z)
(with-handlers [(exn:fail:contract:divide-by-zero? (lambda (exn) 0))]
(/ (* del-t (disc-coeff coins-z) g (disc-vy coins-z)) vel-magn))))
(if (and (< (abs (disc-vx coins-z)) static) (< (abs (disc-vy coins-z)) static))
(begin (set-disc-vx! coins-z 0) (set-disc-vy! coins-z 0)) '()))))))
(myfor (set! z 0) : (< z 19) : (set! z (+ z 1)) : (let ([coins-z (vector-ref coins z)])
(if (vector-ref coin-out z) '()
(map (lambda (w) (if (< (magn (- (car w) (disc-x coins-z)) (- (cdr w) (disc-y coins-z)))
(sqrt (- (* pocket-r pocket-r) (* coin-r coin-r))))
(begin (vector-set! coin-out z turn)
(set-disc-vx! coins-z 0) (set-disc-vy! coins-z 0)
(set-disc-x! coins-z 1000)
(set! coin-taken #t)
(if (equal? (disc-color coins-z) black)
(vector-set! score turn (+ 10 (vector-ref score turn)))
(if (equal? (disc-color coins-z) white)
(vector-set! score turn (+ 20 (vector-ref score turn)))
(set! next-queen-turn #t))))
'())) pockets))))
(if striker-out '() (map (lambda (w) (if (< (magn (- (car w) (disc-x striker)) (- (cdr w) (disc-y striker)))
(sqrt (- (* pocket-r pocket-r) (* striker-r striker-r))))
(begin (set-disc-vx! striker 0) (set-disc-vy! striker 0)
(set-disc-x! striker 1000) (set! striker-out #t)) '())) pockets))
(if striker-out '() (wall-collision striker))
(myfor (set! z 0) : (< z 19) : (set! z (+ z 1)) : (let ([coins-z (vector-ref coins z)])
(if (vector-ref coin-out z) '()
(begin (wall-collision coins-z);collision between coin and wall
(if (and (not striker-out)
(< (magn (- (disc-x striker) (disc-x coins-z)) (- (disc-y striker) (disc-y coins-z)))
(+ striker-r coin-r)))
(collision striker coins-z) '()); collision between coin and striker
(let() (myfor (define w 0) :
(< w 19) :
(set! w (+ w 1)):
(let ([coins-w (vector-ref coins w)]);check collision between coins
(if (and (not (= z w))
(not (vector-ref coin-out z))
(< (magn (- (disc-x coins-w) (disc-x coins-z))
(- (disc-y coins-w) (disc-y coins-z)))
(* 2 coin-r)))
(collision coins-w coins-z) '()))))))))
(cond [(and (= (disc-vx striker) 0) (= 0 (disc-vy striker)) (andmap (lambda (z)
(and (= 0 (disc-vx (vector-ref coins z)))
(= 0 (disc-vy (vector-ref coins z)))))
(range 19)) (not turn-end))
(begin
(if queen-turn (if coin-taken (vector-set! score turn (+ (vector-ref score turn) 50))
(begin (vector-set! coin-out 0 #f) (set-disc-vx! (vector-ref coins 0) 0)
(set-disc-vy! (vector-ref coins 0) 0)
(set-disc-x! (vector-ref coins 0) midx)
(set-disc-y! (vector-ref coins 0) midy))) '())
(if striker-out (vector-set! score turn (- (vector-ref score turn) (put-back coin-out coins))) '())
(if coin-taken '() (set! turn (if (= turn 0) 1 0)))
;take inputs
(set-disc-x! striker midx)
(set-disc-y! striker (if (= turn 0) (+ y0 edges) (- y1 edges)))
(set-disc-vx! striker 0)
(set-disc-vy! striker 0)
(set! queen-turn next-queen-turn)
(set! next-queen-turn #f)
(set! striker-out #f)
(set! coin-taken #f)
(set! turn-end #t))])
(state striker coins striker-out coin-out queen-turn next-queen-turn coin-taken score turn-end)
))
(define empty_frame
(empty-scene 740 540))
(define s1 (square 500 "outline" "white"))
(define s2 (square 540 "solid" "LightSkyBlue"))
(define rec1 (rectangle 200 540 "solid" "Dim Gray"))
(define hole (circle 16 "solid" "DimGray"))
(define coin (circle 10 "outline" "white"))
(define strikers (circle 12.5 "solid" "Dark Green"))
(define hor-line (line 360 0 "white"))
(define ver-line (line 0 360 "white"))
(define line-circle (circle 10 "outline" "white"))
(define centre-circle (circle 50 "outline" "white"))
(define centre-circle2 (circle 49 "outline" "white"))
(define design (radial-star 8 8 12 "solid" "white"))
(define a (text "Player 1" 24 "white"))
(define c (text "Carrom King" 30 "white"))
(define b (text (if (= mode 0) "Player 2" "AI") 24 "white"))
(define (carrom_board argument)
(define cons-of-all (helper-func striker coins))
(define car-cons (car cons-of-all))
(define cdr-cons (car (cdr cons-of-all)))
(define a-score (text (number->string (vector-ref (state-scr argument) 0)) 24 "white"))
(define b-score (text (number->string (vector-ref (state-scr argument) 1)) 24 "white"))
(place-images (list a b a-score b-score c design strikers black white black white black white black white black white black white black white black white black white red
coin centre-circle centre-circle2 rec1 hole hole hole hole hor-line hor-line coin coin hor-line hor-line coin coin
ver-line ver-line coin coin ver-line ver-line coin coin s1 s2
)
(list
(make-posn 640 140)
(make-posn 640 350)
(make-posn 640 170)
(make-posn 640 380)
(make-posn 640 50)
(make-posn (car car-cons) (cdr car-cons))
(make-posn (car car-cons) (cdr car-cons))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(let* ((x (caar cdr-cons))
(y (cdar cdr-cons)))
(set! cdr-cons (cdr cdr-cons))
(make-posn x y))
(make-posn 270 270)
(make-posn 270 270)
(make-posn 270 270)
(make-posn 640 270)
(make-posn 36 36)
(make-posn 504 36)
(make-posn 36 504)
(make-posn 504 504)
(make-posn 270 60)
(make-posn 270 80)
(make-posn 90 70)
(make-posn 450 70)
(make-posn 270 480)
(make-posn 270 460)
(make-posn 90 470)
(make-posn 450 470)
(make-posn 60 270)
(make-posn 80 270)
(make-posn 70 90)
(make-posn 70 450)
(make-posn 480 270)
(make-posn 460 270)
(make-posn 470 90)
(make-posn 470 450)
(make-posn 270 270)
(make-posn 270 270)
)
empty_frame))
(define (helper-func struct vector)
(define striker (cons (disc-x struct) (disc-y struct)))
(define (helper l ans n)
(cond [(equal? n 19) ans]
[else (helper l (cons (cons (disc-x (vector-ref l n)) (disc-y (vector-ref l n))) ans) (+ n 1))]))
(cons striker (list (helper vector '() 0))))
(define (cond1 x y a b)
(if (and (< y 70) (<= (+ (* (- x a) (- x a)) (* (- y b) (- y b))) 2500)) #t
#f))
(define (cond2 x y a b)
(if (and (> y 470) (<= (+ (* (- x a) (- x a)) (* (- y b) (- y b))) 2500)) #t
#f))
(define (mouse-expr ws x y type)
(define power-event 0)
(define striker (state-str ws))
(define coins (state-coi ws))
(define striker-out (state-str-o ws))
(define coin-out (state-coi-o ws))
(define score (state-scr ws))
(define queen-turn (state-qt ws))
(define next-queen-turn (state-nqt ws))
(define coin-taken (state-coi-t ws))
(define turn-end (state-turn-end ws))
(begin (if (and turn-end (or (= turn 0) (= mode 0))) (begin
(cond
; move the striker
;[(mouse=? type "enter")
;(cond [(and (>= y 20) (<= y 520) (>= x 20) (<= x 520)) play-the-game])]
;; pause the game
;[(mouse=? type "leave")
;;; play the game again
;(cond [(or (<= y 20) (>= y 520) (<= x 20) (>= x 520)) pause-the-game])]
[(mouse=? type "button-down")
(cond [(and (>= y 60) (<= y 80) (>= x 90) (<= x 450) (= turn 0))
(set-disc-x! striker x)
(set-disc-y! striker 70)]
[(and (>= y 460) (<= y 480) (>= x 90) (<= x 450)(= turn 1))
(set-disc-x! striker x)
(set-disc-y! striker 470)])]
; put the striker down. store it somewhere maybe. make an arrow pointing the direction.
[(mouse=? type "drag")
(cond [(and
(cond1 x y (disc-x striker) (disc-y striker))
(= turn 0))
(let* ((a (disc-x striker))
(b (disc-y striker))
(length (sqrt (+ (* (- x a) (- x a)) (* (- y b) (- y b))))))
(set! power-event (* max-power (/ length 40))))]
[(and
(cond2 x y (disc-x striker) (disc-y striker))
(= turn 1))
(let* ((a (disc-x striker))
(b (disc-y striker))
(length (sqrt (+ (* (- x a) (- x a)) (* (- y b) (- y b))))))
(set! power-event (* max-power (/ length 40))))])]
[(mouse=? type "move")
(cond [(and (>= y 60) (<= y 80) (>= x 90) (<= x 450) (= turn 0))
(set-disc-x! striker x)
(set-disc-y! striker 70)]
[(and (>= y 460) (<= y 480) (>= x 90) (<= x 450)(= turn 1))
(set-disc-x! striker x)
(set-disc-y! striker 470)])]
[(mouse=? type "button-up")
(cond [(and
(cond1 x y (disc-x striker) (disc-y striker))
(= turn 0))
(let* ((a (disc-x striker))
(b (disc-y striker))
(length (sqrt (+ (* (- x a) (- x a)) (* (- y b) (- y b)))))
(sin-theta (/ (- b y) length))
(cos-theta (/ (- a x) length)))
(set! power-event (* max-power (/ length 50)))
(set-disc-vx! striker (* power-event cos-theta))
(set-disc-vy! striker (* power-event sin-theta))
(set! turn-end #f))]
[(and
(cond2 x y (disc-x striker) (disc-y striker))
(= turn 1))
(let* ((a (disc-x striker))
(b (disc-y striker))
(length (sqrt (+ (* (- x a) (- x a)) (* (- y b) (- y b)))))
(sin-theta (/ (- b y) length))
(cos-theta (/ (- a x) length)))
(set! power-event (* max-power (/ length 50)))
(set-disc-vx! striker (* power-event cos-theta))
(set-disc-vy! striker (* power-event sin-theta))
(set! turn-end #f))])])) '())
(state striker coins striker-out coin-out queen-turn next-queen-turn coin-taken score turn-end)
))
(define (to-draw-helper t)
(cond [(equal? states 'main-menu) (main_menu "welcome")]
[(equal? states 'rules) (rules_ "welcome")]
[(equal? states 'how-to-play) (how_play "welcome")]
[(equal? states 'carrom-board) (carrom_board t)]))
(define (game-end ws)
(if (andmap (lambda (x) (vector-ref (state-coi-o ws) x)) (range 19)) #t #f))
(define (main ws)
(set! states 'main-menu)
(big-bang ws
[on-tick on-tick-helper (/ 1 50)]
[to-draw to-draw-helper]
[on-mouse on-mouse-helper]
[stop-when game-end]))
(define (on-tick-helper t)
(if (equal? states 'carrom-board) (pass-time t) t))
(define (on-mouse-helper ws x y type)
(cond [(equal? states 'carrom-board) (mouse-expr ws x y type)]
[(and (equal? type "button-down") (equal? states 'main-menu))
(cond [(and (> x 25) (< x 345) (> y 307) (< y 367)) (begin (set! mode 1) (set! states 'carrom-board) ws)]
[(and (< x 715) (> x 395) (> y 307) (< y 367)) (begin (set! mode 0) (set! states 'carrom-board) ws)]
[(and (< x 345) (> x 25) (> y 443) (< y 503)) (begin (set! states 'how-to-play) ws)]
[(and (< x 715) (> x 395) (< y 503) (> y 443)) (begin (set! states 'rules) ws)])]
[(and (equal? type "button-down") (equal? states 'how-to-play))
(cond [(and (> x 570) (< x 660) (> y 460) (< y 550)) (begin (set! states 'main-menu) ws)])]
[(and (equal? type "button-down") (equal? states 'rules))
(cond [(and (> x 570) (< x 660) (> y 460) (< y 550)) (begin (set! states 'main-menu) ws)])]
[else ws]
))
(define empty_frame3
(empty-scene 740 540))
;(define a (text "How to Play" 120 "blue"))
(define base (bitmap/file "image/howtoplay.PNG"))
;(define b (text "Use mouse to play." 50 "blue"))
;(define c (text "For each strike ,position the striker on the base line." 50 "blue"))
;(define d (text "Before striking ,click and drag drag the hand to select
;the power and then release it to pocket the piece" 50 "blue"))
(define (how_play argument)
(place-images (list base)
(list (make-posn 370 270)) empty_frame3))
(define empty_frame4
(empty-scene 740 540))
(define bases (bitmap/file "image/rules.PNG"))
;(define b (text "A turn consists of one or more strikes. A player having higher score wins at the end of game
;
;Sinking the striker will cost you one piece.
;After pocketing the red colour piece, you must sink
; any of your carrom men,
; covering it in the next shot,
;or else red colour piece will be returned back to
;the center point of the board." 50 "blue"))
(define (rules_ argument)
(place-images (list bases)
(list
(make-posn 370 270)) empty_frame4))
(define empty_frame2
(empty-scene 740 540))
(define (main_menu argument)
(place-images (list basess aa bb cc dd)
(list
(make-posn 370 135)
(make-posn 185 337)
(make-posn 555 337)
(make-posn 185 473)
(make-posn 555 473)) empty_frame2))
(define basess (bitmap/file "image/project.png"))
(define aa (bitmap/file "image/button1.png"))
(define bb (bitmap/file "image/button2.PNG"))
(define cc (bitmap/file "image/button3.PNG"))
(define dd (bitmap/file "image/button4.PNG"))
(main (state striker coins #f (make-vector 19 #f) #f #f #f (make-vector 2 0) #t))
| true |
2fd83515c6169f869fc468c62a607ca0a92e0bd8 | dd4cc30a2e4368c0d350ced7218295819e102fba | /vendored_parsers/tree-sitter-racket/corpus/box.rkt | 03abbe78c6868c39cb0d8e74000e3495e72551e8 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | Wilfred/difftastic | 49c87b4feea6ef1b5ab97abdfa823aff6aa7f354 | a4ee2cf99e760562c3ffbd016a996ff50ef99442 | refs/heads/master | 2023-08-28T17:28:55.097192 | 2023-08-27T04:41:41 | 2023-08-27T04:41:41 | 162,276,894 | 14,748 | 287 | MIT | 2023-08-26T15:44:44 | 2018-12-18T11:19:45 | Rust | UTF-8 | Racket | false | false | 109 | rkt | box.rkt | ===
box
===
#&17
#&"str"
#& ()
---
(program
(box
(number))
(box
(string))
(box
(list)))
| false |
9b73dd04b83a7fab51610b437b8081b68b63a2f0 | e0ea6503b51c4742398ca00e3ee040671d53059f | /prerequisite_works/rkt_work/preq/racket_practice.rkt | 7e5b33ce17d47f524900d326943989a311d827b6 | []
| no_license | andrewtshen/riscv-symbolic-emulator | b25622649f4387dffbd7103ad7fa4c7f4dafc629 | c7b02091521a4dc3dcd45f3cef35e1af0a43759a | refs/heads/master | 2023-04-30T13:38:41.101292 | 2021-03-23T20:01:27 | 2021-03-23T20:01:27 | 206,185,823 | 1 | 0 | null | 2021-03-23T20:01:27 | 2019-09-03T22:55:21 | Racket | UTF-8 | Racket | false | false | 2,170 | rkt | racket_practice.rkt | #lang racket
(provide (all-defined-out))
(printf (string-append "rope" "twine" "yarn" "\n"))
(define (sqrt-wrapper i)
(if (equal? 8 (sqrt i))
(printf "Square root is 8\n")
(printf "Square root isn't 8\n")))
(sqrt-wrapper 64)
(if (equal? "hello world" (string-append "hello " "world"))
(printf "They are equal!\n")
(printf "They aren't equal!\n")
)
(define (reply s)
(cond
[(equal? "hello" (substring s 0 5))
(printf "hey\n")]
[(equal? "bye" (substring s 0 3))
(printf "see ya later\n")]
[else (printf "what did you say?\n")]))
(define (double v)
((if (string? v) string-append *) v v))
(define (triple f x)
(f (f (f x))))
(let* ([x (random 10)]
[o (random 10)]
[diff (number->string (abs (- x o)))])
(cond
[(> x o) (printf (string-append "X wins by " diff "\n"))]
[(> o x) (printf (string-append "O wins by " diff "\n"))]
[else "cat's game\n"]))
; List Usage
(printf "List Usage\n")
(printf (string-append "list length: " (number->string (length (list "hop" "skip" "jump"))) "\n"))
(printf (string-append "list 2nd index: " (list-ref (list "hop" "skip" "jump") 2) "\n"))
; List mappings
(map (lambda (i)
(+ i 1))
(list 1 2 3 4))
(filter number? (list 1 2 "hello" 3))
(first (list 1 2 3 "hello" "world"))
(rest (list 1 2 3 "hello" "world"))
; Keyword Arguments
(define (sub x y) (- x y))
(sub 12 30) ; -18
(define (kw-sub #:foo foo-val y) (sub foo-val y))
(kw-sub 12 #:foo 18) ; 18
; Set Default Values
(define (add-defaults x [y 10] #:z [z 1]) (+ x y z))
(add-defaults 100 20 #:z 2) ; 121
(add-defaults 500) ; 511
(define (remove-dups l)
(display l)
(printf " ")
(display (rest l))
(printf "\n")
(cond
[(empty? l) empty] ; check if the initial list empty
[(empty? (rest l)) l] ; check if the rest of the list is empty
[else
(let ([i (first l)])
(if (equal? i (first (rest l))) ; check if the first element is equal to the second element
(remove-dups (rest l)) ; if true, discard the first element
(cons i (remove-dups (rest l)))))])) ; if false, keep the first element
(remove-dups (list 1 1 2 1 2 2))
| false |
683462edc34a3037a9960410c60c1137ffecdc4e | fbb3acdba70545604c02b0aa9454c95e79511aea | /a3/a3_test.rkt | 8e1bbdc960fabe747f48ef8b92d7fe162695248c | []
| no_license | srowhani/comp3007 | 7e8ee7c006dd5deb3dba1a18978bd064be61d4d1 | 89facf8bd447a3fecbe05ac939ed5d4b3d790131 | refs/heads/master | 2021-03-21T05:34:43.332581 | 2016-04-15T17:20:08 | 2016-04-15T17:20:08 | 50,802,345 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 1,474 | rkt | a3_test.rkt | #lang racket
(require "a3_q1.rkt")
(require "a3_q3.rkt")
;q1==============================
(define g (make-graph))
(define n1 (make-node 1))
(define n2 (make-node 2))
(define n3 (make-node 3))
(define n4 (make-node -1))
(define e1 (make-edge n1 n2))
(define e2 (make-edge n1 n3))
(define e3 (make-edge n2 n3))
(define e4 (make-edge n1 n4))
(~a "((g 'add-node) n1) -> " ((g 'add-node) n1))
(~a "((g 'add-node) n2) -> " ((g 'add-node) n2))
(~a "((g 'add-node) n3) -> " ((g 'add-node) n3))
(~a "((g 'add-edge) e1) -> " ((g 'add-edge) e1))
(~a "((g 'add-edge) e2) -> " ((g 'add-edge) e2))
(~a "((g 'add-edge) e3) -> " ((g 'add-edge) e3))
(~a "((g 'add-edge) e4) -> " ((g 'add-edge) e4))
(~a "((g 'print-graph)) -> " ((g 'print-graph)))
;q3==============================
(~a "(stream-ref (seq-gen) 5) -> " (stream-ref (seq-gen) 5))
(~a "(stream->list (first 5 (seq-gen))) -> " (stream->list (first 5 (seq-gen))))
(~a "(stream->list (first 5 (stream-filter odd? (seq-gen)))) -> " (stream->list (first 5 (stream-filter odd? (seq-gen)))))
(~a "(stream->list (first 5 (random-gen))) -> " (stream->list (first 5 (random-gen))))
(~a "(stream->list (first 10 (fib-gen))) -> " (stream->list (first 10 (fib-gen))))
(~a "(list->stream (list 1 2 3)) -> " (list->stream (list 1 2 3)))
(~a "(stream-cdr (list->stream (list 1 2 3))) -> " (stream-cdr (list->stream (list 1 2 3))))
(~a "(stream->list (first 10 (partial-sums (seq-gen)))) -> " (stream->list (first 10 (partial-sums (seq-gen)))))
| false |
703fbdfdf87eb1cd0dee7a9afadd763982a2b60c | ab00a4b7743b55f05ee117bd5a20ceb300e069d4 | /compiler-rjs/info.rkt | f9bd5b9498f5856bae06aabfd8d98af717c53a78 | []
| no_license | soegaard/urlang | 8bf331fab485ab75cd6c96e11fd01a6c6a502d40 | f7ac3390d73d7991bfb956d480042a2efdd68607 | refs/heads/master | 2023-06-08T12:58:44.389834 | 2023-05-31T12:47:15 | 2023-05-31T12:47:15 | 40,402,158 | 324 | 22 | null | 2022-02-27T11:55:51 | 2015-08-08T12:27:06 | Racket | UTF-8 | Racket | false | false | 697 | rkt | info.rkt | #lang info
;;; This file describes the contents of the Urlang package.
;;; The information is used by the Racket package system.
;;; The Urlang package contains multiple collections (urlang, urlang-doc, compiler etc)
(define collection "compiler-rjs")
;;; Version number
(define version "1.0")
;;; Dependencies declared here will need source
(define deps '())
;;; Dependencies here can be installed as binaries (i.e. zo-files)
(define build-deps '("base"
"nanopass"
"at-exp-lib"
"rackunit-lib"
"scribble-lib"
"racket-doc"))
(define compile-omit-paths '())
| false |
e84e4095e9fc8c62f77bd035100760ea3f144c67 | 375fdeeab76639fdcff0aa64a9b30bd5d7c6dad9 | /pure-lands/utilities/symbol-set.rkt | ea71a18021c45f5256e1e947f87c130410934bec | []
| no_license | VincentToups/racket-lib | 64fdf405881e9da70753315d33bc617f8952bca9 | d8aed0959fd148615b000ceecd7b8a6128cfcfa8 | refs/heads/master | 2016-09-08T01:38:09.697170 | 2012-02-02T20:57:11 | 2012-02-02T20:57:11 | 1,755,728 | 15 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,451 | rkt | symbol-set.rkt | #lang racket
(define-for-syntax (add-qmark s)
(string->symbol
(string-append (symbol->string s) "?")))
(define (all-symbols? lst)
(match lst
[(list x)
(symbol? x)]
[(cons x rest)
(if (symbol? x)
(all-symbols? rest)
#f)]))
(define (symbol-in-symbol-set s set)
(match set
[(list) #f]
[(cons hd tl)
(if (equal? hd s)
#t
(symbol-in-symbol-set s tl))]))
(define (unique-cons s set)
(let loop ((passed '())
(subset set))
(match subset
[(list) (reverse (cons s passed))]
[(cons hd tl)
(if
(equal? hd s) set
(loop (cons hd passed)
tl))])))
(define (list->set items)
(let loop ((items items)
(set '()))
(match items
[(list) set]
[(cons hd tl)
(loop tl
(unique-cons hd set))])))
(define-syntax (declare-symbol-set stx)
(syntax-case stx ()
[(declare-symbol-set name predicate-name member ...)
#'(begin
(unless (all-symbols? '(member ...))
(error "Cannot declare a symbol set on non-symbol members."))
(define name (list->set '(member ...)))
(define predicate-name
(let ((name name))
(lambda
(x)
(symbol-in-symbol-set
x
name)))))]))
(provide declare-symbol-set symbol-in-symbol-set?)
| true |
f5f315d56f43813184a773528e08e3de7b94c38c | 577e548e1744ef39e5b1325974cea6e488b08436 | /MiniKanren/10_8.rkt | 4559ac628081e9d8d814444ec4ebb766884ba24b | []
| no_license | ya0guang/ProgrammingLanguageCourse | 5bc1637f68d489a6da4042e7f2a95df124495ae7 | 2bb082091c43912237f6e3d3dd535411d83173d9 | refs/heads/master | 2023-01-29T21:59:32.195901 | 2020-12-13T16:53:51 | 2020-12-13T16:53:51 | 291,375,264 | 7 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,825 | rkt | 10_8.rkt | #lang typed/racket
(struct Var
([name : Symbol])
#:transparent)
(define-type Substitution
(Listof (Pairof Var Term)))
(define-type Term
(U Var
Number
Symbol
Null
(Pairof Term Term)))
(: unify (→ Term Term Substitution
(U Substitution False)))
(define unify
(λ (t₁ t₂ σ)
(let ([t₁ (walk t₁ σ)]
[t₂ (walk t₂ σ)])
(cond
[(eqv? t₁ t₂) σ]
[(Var? t₁) (ext-s t₁ t₂ σ)]
[(Var? t₂) (ext-s t₂ t₁ σ)]
[(and (pair? t₁) (pair? t₂))
(let ([σ^ (unify (car t₁) (car t₂) σ)])
(and σ^ (unify (cdr t₁) (cdr t₂) σ^)))]
[else #f]))))
(: walk (→ Term Substitution Term))
(define walk
(λ (t σ)
(cond
[(Var? t)
(cond
[(assv t σ)
=>
(λ ([pr : (Pairof Var Term)])
(walk (cdr pr) σ))]
[else t])]
[else t])))
#;
(walk (Var 'x) `((,(Var 'x) . 42) (,(Var 'y) . ,(Var 'x)) (,(Var 'z) . cat)))
; this will always yield (Var 'x) since there these two (Var 'x) are different!!!!!!!
#;
(let ([x (Var 'x)]
[y (Var 'y)]
[z (Var 'z)]
[q (Var 'q)])
(walk z `((,x . 42) (,y . x) (,z . cat))))
; (walk (Var 'x) `((,x . 42) (,y . x) (,z . cat)))
(: occurs? (→ Var Term Substitution
Boolean))
(define occurs?
(λ (x t σ)
(let ([t (walk t σ)])
(cond
[(Var? t) (eqv? t x)]
[(pair? t) (or (occurs? x (car t) σ)
(occurs? x (cdr t) σ))]
[else #f]))))
#|there shouldn't be a loop in a substitution|#
(: ext-s (→ Var Term Substitution
(U Substitution False)))
(define ext-s
(λ (x t σ)
(cond
[(occurs? x t σ) #f]
[else `((,x . ,t) . ,σ)])))
(: empty-s Substitution)
(define empty-s '())
#;
(let ([x (Var 'x)]
[y (Var 'y)]
[z (Var 'z)]
[q (Var 'q)])
(unify `(,x . cat) `(42 . ,y) empty-s))
#;
(let ([x (Var 'x)]
[y (Var 'y)]
[z (Var 'z)]
[q (Var 'q)])
(unify `(,x . ,y) `(,y . (,x . ,x)) empty-s))
#;
(let ([x₁ (Var 'x)]
[x₂ (Var 'x)])
(eqv? x₁ x₂))
(define-type Goal
(→ Substitution Stream))
(define-type Stream
(U Null
(Pairof Substitution Stream)
(→ Stream)))
(: ≡ (→ Term Term Goal))
(define ≡
(λ (t₁ t₂)
(λ (σ)
(let ([σ^ (unify t₁ t₂ σ)])
(cond
[σ^ `(,σ^)]
[else '()])))))
(: take (→ Stream Number
(Listof Substitution)))
(define take
(λ ($ n)
(cond
[(zero? n) '()]
[(null? $) '()]
[(pair? $) (cons (car $) (take (cdr $) (sub1 n)))]
[else (take ($) n)])))
#;
(let ([x₁ (Var 'x)]
[x₂ (Var 'x)])
(take ((≡ x₁ 'cat) empty-s) 1))
(: append$ (→ Stream Stream
Stream))
(define append$
(λ ($₁ $₂)
(cond
[(null? $₁) $₂]
[(pair? $₁) (cons (car $₁) (append$ (cdr $₁) $₂))]
[else (λ () (append$ $₂ ($₁)))])))
(: disj₂ (→ Goal Goal
Goal))
(define disj₂
(λ (g₁ g₂)
(λ (σ)
(append$ (g₁ σ) (g₂ σ)))))
(: append-map$ (→ Goal Stream
Stream))
(define append-map$
(λ (g $)
(cond
[(null? $) '()]
[(pair? $) (append$ (g (car $)) (append-map$ g (cdr $)))]
[else (λ () (append-map$ g ($)))])))
(: conj₂ (→ Goal Goal
Goal))
(define conj₂
(λ (g₁ g₂)
(λ (σ)
(append-map$ g₂ (g₁ σ)))))
(let ([x (Var 'x)]
[y (Var 'y)]
[z (Var 'z)]
[q (Var 'q)])
(take ((disj₂ (conj₂ (≡ x 'cat) (≡ y 42))
(conj₂ (≡ x 'dog) (≡ x 'cat)))
empty-s)
10))
#;
(take (append$ (nats 0) (nats 0)) 10)
(let ([x (Var 'x)]) ((≡ x 'cat) empty-s)) | false |
238af24c0f9becda4ef7c6fa89289a86a343ee76 | a1737280e5bde10cf78c3514c1b0713ec750d36b | /lang/scheme/programing_design/6-2.rkt | c99d864c90224519840c19f175abb5ec45774cba | []
| no_license | kaiwk/playground | ee691f6a98f6870e9e53dcf901c85dddb2a9d0cc | cf982a8ba769a232bfc63fd68f36fe863ca7a4c5 | refs/heads/master | 2022-02-19T01:23:49.474229 | 2019-09-05T12:59:13 | 2019-09-05T12:59:13 | 56,390,601 | 3 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,172 | rkt | 6-2.rkt | ;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-advanced-reader.ss" "lang")((modname 6-2) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f () #f)))
(require htdp/draw)
(define WIDTH 50)
(define HEIGHT 160)
(define BULB-RADIUS 20)
(define BULB-DISTANCE 10)
(define X-BULB (quotient WIDTH 2))
(define Y-RED (+ BULB-DISTANCE BULB-RADIUS))
(define Y-GREEN (+ Y-RED BULB-DISTANCE (* 2 BULB-RADIUS)))
(define Y-YELLOW (+ Y-GREEN BULB-DISTANCE (* 2 BULB-RADIUS)))
(start WIDTH HEIGHT)
(draw-solid-disk (make-posn X-BULB Y-RED) BULB-RADIUS 'red)
(draw-circle (make-posn X-BULB Y-GREEN) BULB-RADIUS 'green)
(draw-circle (make-posn X-BULB Y-YELLOW) BULB-RADIUS 'yellow)
;;; symbol -> bool
(define (clear-bulb color)
(cond
[(symbol=? color 'red)
(and
(draw-solid-disk (make-posn X-BULB Y-RED) BULB-RADIUS 'white)
(draw-circle (make-posn X-BULB Y-RED) BULB-RADIUS 'red))]
[(symbol=? color 'green)
(and
(draw-solid-disk (make-posn X-BULB Y-GREEN) BULB-RADIUS 'white)
(draw-circle (make-posn X-BULB Y-GREEN) BULB-RADIUS 'green))]
[(symbol=? color 'yellow)
(and
(draw-solid-disk (make-posn X-BULB Y-YELLOW) BULB-RADIUS 'white)
(draw-circle (make-posn X-BULB Y-YELLOW) BULB-RADIUS 'YELLOW))]))
;;; symbol -> bool
(define (draw-bulb color)
(cond
[(symbol=? color 'red)
(draw-solid-disk (make-posn X-BULB Y-RED) BULB-RADIUS 'red)]
[(symbol=? color 'green)
(draw-solid-disk (make-posn X-BULB Y-GREEN) BULB-RADIUS 'green)]
[(symbol=? color 'yellow)
(draw-solid-disk (make-posn X-BULB Y-YELLOW) BULB-RADIUS 'yellow)]))
;;; symbol -> bool
(define (switch close-color open-color)
(and
(clear-bulb close-color)
(draw-bulb open-color)))
;;; symbol -> symbol
(define (next current-color)
(cond
[(symbol=? current-color 'red)
(switch current-color 'green)]
[(symbol=? current-color 'green)
(switch current-color 'yellow)]
[(symbol=? current-color 'yellow)
(switch current-color 'red)]))
| false |
92116e5ce59077e7ff0ccb50865d2eb570b9ba6b | 1335ef22e0c7a074fb85cedd91d43518f0a960d7 | /Assignments/Assignment13/a13.1.rkt | 133e4ff41505d198ddd32fb082c6c0a940b46a16 | []
| no_license | zhengguan/Scheme | 55d35fbf40790fd22cd98876dba484e5bd59ad99 | e27eedd2531c18a9b23134dc889a4ed1a0cd22c9 | refs/heads/master | 2021-01-13T04:58:50.945397 | 2014-12-19T05:24:36 | 2014-12-19T05:24:36 | 29,330,341 | 1 | 0 | null | 2015-01-16T03:12:28 | 2015-01-16T03:12:28 | null | UTF-8 | Racket | false | false | 431 | rkt | a13.1.rkt | #lang racket
(require C311/numbers)
(require C311/mk)
(require C311/let-pair)
(provide (all-defined-out))
(define listo
(lambda (ls)
(conde
((== ls '()))
((=/= ls '())
(fresh (a d)
(== `(,a . ,d) ls) (listo d))))))
(run 1 (q) (listo '(a b c d e)))
;(_.0)
(run 1 (q) (listo '(a b c d . e)))
;()
(run 4 (q) (listo q))
;(() (_.0) (_.0 _.1) (_.0 _.1 _.2))
(run 4 (q) (listo `(a b ,q)))
;(_.0) | false |
7692dcfec562e7a26be4431a7e59e2c0fd4e39ec | bdb6b8f31f1d35352b61428fa55fac39fb0e2b55 | /sicp/ex2.36.rkt | 6b09da47525210b5d82330cbe5e95363d0424f3c | []
| no_license | jtskiba/lisp | 9915d9e5bf74c3ab918eea4f84b64d7e4e3c430c | f16edb8bb03aea4ab0b4eaa1a740810618bd2327 | refs/heads/main | 2023-02-03T15:32:11.972681 | 2020-12-21T21:07:18 | 2020-12-21T21:07:18 | 323,048,289 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,033 | rkt | ex2.36.rkt | #lang racket
;ex2.36
(define nil '())
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op
initial
(cdr sequence)))))
(define (accumulate-n op init seqs)
(if (null? (car seqs))
nil
(cons (accumulate op init (map (lambda(x) (list-ref x 0)) seqs))
(accumulate-n op init (map (lambda(x) (cdr x)) seqs)))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
s
(accumulate + 0 (map (lambda(x) (list-ref x 0)) s))
(define s1 (map (lambda(x) (cdr x)) s))
s1
(accumulate + 0 (map (lambda(x) (list-ref x 0)) s1))
(define s2 (map (lambda(x) (cdr x)) s1))
s2
(accumulate + 0 (map (lambda(x) (list-ref x 0)) s2))
(define s3 (map (lambda(x) (cdr x)) s2))
s3
(newline)
;(accumulate + 0 (map (lambda(x) (list-ref x 0)) s1))
;(map (lambda(x) (cdr x)) s)
;(accumulate + 0 (map (lambda(x) (list-ref x 0)) s))
;(map (lambda(x)(cdr x)) s)
(accumulate-n + 0 s)
;(22 26 30)
| false |
4ea96296fc03a1c2c02dd28a5eda14e91c065c93 | e1cf61b84282c33b7a245f4d483883cf77739b91 | /se3-bib/sim/simBase/simActorClass-module.rkt | b6bee89caadc0e97c4ec6b85280eabf953494a60 | []
| no_license | timesqueezer/uni | c942718886f0366b240bb222c585ad7ca21afcd4 | 5f79a40b74240f2ff88faccf8beec7b1b3c28a7c | refs/heads/master | 2022-09-23T21:57:23.326315 | 2022-09-22T13:17:29 | 2022-09-22T13:17:29 | 71,152,113 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 4,886 | rkt | simActorClass-module.rkt | #lang swindle
#|
################################################################################
## ##
## This file is part of the se3-bib Racket module v3.0 ##
## Copyright by Leonie Dreschler-Fischer, 2010 ##
## Ported to Racket v6.2.1 by Benjamin Seppke, 2015 ##
## ##
################################################################################
|#
#|
=================================================================
sim-actor A mixin class for simulation objects,
provides a framework for
- broadcasting messages to all actors
-initializing and resetting all actors
- displaying a picture of the actors
=================================================================
|#
(provide
; accessors
actor-num actor-name sim-actor?
the-actors set-the-actors! the-last-num
; global variables
*the-number-generator* *all-actors*
)
#|
auto provide
classes: sim-actor
generics: initialize
sim-init! sim-start sim-info
tell broadcast broadcast-some
map-actors
add-actor!
|#
(require se3-bib/sim/simBase/sim-utility-base-package)
(defclass* actor-numbers ()
(lastnum :initvalue 0
:accessor the-last-num
:type <integer>
:allocation :class)
:autopred #t ; auto generate predicate sim-actor?
:printer #t
:documentation "a generator for unique actor numbers"
)
(define *the-number-generator*
(make actor-numbers))
(defgeneric* next-actor-number ((ng actor-numbers))
:documentation "generate a unique actor number"
:method (method
((ng actor-numbers))
(inc! (the-last-num ng))
(the-last-num ng)))
(defmethod next-actor-number
((ng actor-numbers))
(inc! (the-last-num ng))
(the-last-num ng))
(defclass* sim-actor ()
(actor-name
:reader actor-name
:initvalue "anonymous"
:initarg :actor-name
:type <string>
:documentation "The name of the actor"
)
(actor-num
:reader actor-num
:initializer
(lambda ()
(next-actor-number
*the-number-generator*))
:type <integer>
:documentation
"A picture of the current state of the actor"
)
:autopred #t ; auto generate predicate sim-actor?
:printer #t
;:documentation "A mixin class for simulation objects,
;provides a framework for broadcasting messages to all actors"
)
(defclass* set-of-actors ()
(theActors
:accessor the-actors
:writer set-the-actors!
:initvalue '()
:type <list>
:documentation
"A set of actors"
)
:autopred #t ; auto generate predicate set-of-actors?
:printer #t
)
(define *all-actors* (make set-of-actors))
(defgeneric* add-actor! ((a sim-actor) (s setOfActors))
:documentation
"add an actor to the set of all actors"
)
(defgeneric* remove-duplicates! ((s set-of-actors))
:documentation
"remove duplicate entries"
)
(defgeneric* sim-init! ((obj sim-actor))
:documentation
"further initializations after all actors have been created"
:combination generic-begin-combination)
(defgeneric* sim-start ((obj sim-actor))
:documentation
"Trigger the start-up actions, get the system going"
:combination generic-begin-combination)
(defgeneric* sim-info ((obj sim-actor))
:documentation
"request state information."
:combination generic-begin-combination)
;;; ===========================================================
;;; Message passing
;;; ===========================================================
(defgeneric* tell ((obj sim-actor) (message <function>))
:documentation
"Pass message to actor.
The message must be the name
of an applicable method or procedure."
)
(defgeneric* broadcast
((actor sim-actor)
(message <function>)
&key (sim-class sim-actor))
:documentation
"Broadcast a message to all actors of a subclass of sim-class"
)
(defgeneric* broadcast-some
((actor sim-actor)
(message <function>)
&optional (sim-type sim-actor))
:documentation
"Send message to actors of type sim-type,
and find some actor who confirms the message
by answering 'not #f'."
)
(defgeneric* retrieve-by-name
((actor sim-actor)
(name <string>)
&optional (sim-class sim-actor))
:documentation
"Return an actor of type sim-type, whose actor-name is 'name'.")
(defgeneric* map-actors
((actor sim-actor)
(message <function>)
&optional (sim-class sim-actor))
:documentation
"Send message to actors of type sim-type,
and collect the results in a list")
(defgeneric* longest-name
((actor sim-actor)
&optional (sim-class sim-actor))
:documentation
"Send message to actors of type sim-type,
and collect the longest name")
| false |
c3117b93c1fe8ac4f4874773e9e6a240bfe8afa9 | 53543edaeff891dd1c2a1e53fc9a1727bb9c2328 | /benchmarks/take5/typed/basics-types.rkt | 28b36d45852f9d00b21418ef59a1bd09c63dcc0a | [
"MIT"
]
| permissive | bennn/gtp-checkup | b836828c357eb5f9f2b0e39c34b44b46f2e97d22 | 18c69f980ea0e59eeea2edbba388d6fc7cc66a45 | refs/heads/master | 2023-05-28T16:26:42.676530 | 2023-05-25T03:06:49 | 2023-05-25T03:06:49 | 107,843,261 | 2 | 0 | NOASSERTION | 2019-04-25T17:12:26 | 2017-10-22T06:39:33 | Racket | UTF-8 | Racket | false | false | 135 | rkt | basics-types.rkt | #lang typed/racket/base
(provide Face Bulls Name)
(define-type Name Natural)
(define-type Face Natural)
(define-type Bulls Natural)
| false |
19cf291ea3692c4def50d7e38c0750e5e1bdc5bc | 0c76408a0cab75d299550fff8cb3b2d5cb22aa1e | /yamm-test.rkt | 17786fae44e2fde5c138cf787cd88b4f481df2a9 | [
"MIT"
]
| permissive | tfidfwastaken/yamm | aa7b2eb1efcaf61945d6f2e3fd499ae8b087bb40 | 9df6e29bfaa66dfc4f150197ccb918fd6c59b458 | refs/heads/master | 2022-11-06T15:23:10.468007 | 2020-06-26T09:53:23 | 2020-06-26T09:53:23 | 274,469,666 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 231 | rkt | yamm-test.rkt | #lang yamm
--- # The yamms are the powers that be
processed: $e (equal? 5 5.0) e$
$e (for/hash ([i (in-range 5)]
[j '("bunch" "of" "values" "here")])
(values i j)) e$
$e (list "this" "is" "a" "list") e$
| false |
2e392f9d1344691ff4190f49aad1c14ef764065b | 5990618629d710f65b3dfa7b857bc790ccaac8e9 | /5-language/server/main.rkt | 4e9b051287197c6cf7234b329a6935497c447977 | []
| no_license | mflatt/web-macro-tutorial | bcf3fe9ec8b3058bc0c0ac285fca209a87896a62 | 3337dcddc827d8a4f1cfcce9a9fd34cabc849540 | refs/heads/master | 2021-01-13T01:30:00.522032 | 2014-04-11T16:05:45 | 2014-04-11T16:05:45 | 18,652,850 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,300 | rkt | main.rkt | #lang racket
(require web-server/servlet-env
web-server/http/xexpr
(for-syntax syntax/parse))
(provide div a
(except-out (all-from-out racket) #%module-begin)
(rename-out [module-begin #%module-begin]))
(define-syntax (define-tag stx)
(syntax-parse stx
[(define-tag tag ok-attrib ...)
#`(define-syntax (tag stx)
(syntax-parse stx
[(tag ([attrib a-expr] (... ...)) content-expr)
(for-each (lambda (attrib-stx)
(unless (member (syntax-e attrib-stx) '(ok-attrib ...))
(raise-syntax-error #f
"bad attribute"
stx
attrib-stx)))
(syntax-e #'(attrib (... ...))))
#'`(tag ([attrib ,a-expr] (... ...))
,content-expr)]))]))
(define-tag div style)
(define-tag a href style)
(define-syntax (module-begin stx)
(syntax-parse stx
[(module-begin expr)
#'(#%module-begin
(start (lambda () expr)))]))
(define (start reply-thunk)
(serve/servlet
(lambda (req)
(response/xexpr
(reply-thunk)))))
(module reader syntax/module-reader
server)
| true |
2b0d87b3d8c31633a2a2eae0cf775d7997514de1 | 9db1a54c264a331b41e352365e143c7b2b2e6a3e | /code/chapter_3/continuation.rkt | 19c6ee519ae87b38b7da9a061cab4d28eff68263 | []
| no_license | magic3007/sicp | 7103090baa9a52a372be360075fb86800fcadc70 | b45e691ae056410d0eab57d65c260b6e489a145b | refs/heads/master | 2021-01-27T10:20:28.743896 | 2020-06-05T15:17:10 | 2020-06-05T15:17:10 | 243,478,192 | 4 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 881 | rkt | continuation.rkt | #lang racket
(define exit #f)
(define cont-list '())
(define len (read))
(define (set-cont-list n)
(define (output n)
(for-each (lambda (x) (displayln x)) (reverse (build-list (add1 n) add1))))
(set! cont-list (build-list n
(lambda (idx)
(let* ([sc #f]
[cc (let/cc cc (set! sc cc) #t)])
(if (false? cc) (output idx) (void))
sc)))))
(define (show n)
(define (show-helper l n)
(if (= n 0)
(if (continuation? (car l))
((car l) #f)
(displayln "error"))
(show-helper (cdr l) (- n 1))))
(show-helper cont-list (- n 1)))
(define (main)
(set-cont-list len)
(define k (read))
(if (eq? k eof)
(void)
(show k)))
(main) | false |
d4b75d22e3ac7c03d3b3f13264b5cfff640a10fe | bd28ae267be477e767d63b5d72cee24ab8ec9192 | /erosion-timeline/utils.rkt | e0e01c97bb95a3e8d1c58ed0932c39df90552745 | []
| no_license | eehah5ru/erosion-machine-timeline-builder | 57f5dd32dd386b3f26bf87bd752b96273b445add | 16ebd929d40be0a307091dfc72f06d24367083ef | refs/heads/master | 2023-01-27T21:21:12.300293 | 2020-12-07T16:49:14 | 2020-12-07T16:49:14 | 307,392,050 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 327 | rkt | utils.rkt | #lang racket
(provide (all-defined-out))
(define (is-type? typ x)
(eq? typ (hash-ref x 'type 'unknown)))
(define (show-image? x)
(is-type? "showImage" x))
(define (show-text? x)
(is-type? "showText" x))
(define (show-video? x)
(is-type? "showVideo" x))
(define (add-background? x)
(is-type? "addBackground" x))
| false |
97f7b311afe36656c6d96400721961fb7f7cda54 | 00ff1a1f0fe8046196c043258d0c5e670779009b | /sdsl/bv/lang/location.rkt | 50a3b32da00a001ee699211f384c07e144ac0baa | [
"BSD-2-Clause"
]
| permissive | edbutler/rosette | 73364d4e5c25d156c0656b8292b6d6f3d74ceacf | 55dc935a5b92bd6979e21b5c12fe9752c8205e7d | refs/heads/master | 2021-01-14T14:10:57.343419 | 2014-10-26T05:12:03 | 2014-10-26T05:12:03 | 27,899,312 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,329 | rkt | location.rkt | #lang s-exp rosette
(provide (except-out (all-defined-out) set-location!))
; Represents the type of instruction location.
; Values of this type must be totally ordered,
; and comparable using the operators <?, <=?,
; and =?. It should also be possible to retrive
; the ith location value using location-ref.
(define inputs (make-parameter 0))
(define (set-location! loc? loc loc<?)
(set! location? loc?)
(set! location loc)
(set! location<? loc<?))
;; enum-based
(define-syntax-rule (define-locations size)
(local [(define-enum location (build-list (+ size (inputs)) values))]
(set-location! location? location location<?)))
(define location #f)
(define location? #f)
(define location<? #f)
(define (location>? x y) (location<? y x))
(define location=? eq?)
(define location-ordinal ordinal)
(define (location<=? x y)
(|| (location=? x y) (location<? x y)))
(define (location-bitwidth inputs lib) 0)
#|
;; bitvector-based
(define-syntax-rule (define-locations size) (void))
(define location? number?)
(define location<? <)
(define location>? >)
(define location=? =)
(define location<=? <=)
(define location identity)
(define location-ordinal identity)
(define (location-bitwidth inputs lib)
(+ (integer-length (+ (length inputs) (length lib))) 1))|#
#|
(define-signature location^
(location? ; type?
location<? ; (-> location? location? boolean?)
location=? ; (-> location? location? boolean?)
location<=? ; (-> location? location? boolean?)
location-ref)) ; (-> number? location?)
; Returns a location unit that is based on an enumerated typed.
(define (location-enum@ size)
(unit
(import)
(export location^)
(define-enum location (build-list size values))
(define location=? eq?)
(define (location<=? x y)
(or (location=? x y) (location<? x y)))
(define (location-ref idx)
(vector-ref (enum-members location?) idx))))
; Returns a location unit that is based on the bitvector
; (i.e., number?) type.
(define (location-bv@ size)
(unit
(import)
(export location^)
(define location? number?)
(define location<? <)
(define location=? =)
(define location<=? <=)
(define location-ref identity)))
(provide location^ location-enum@ location-bv@)
|#
| true |
bdeee08d92edee0084d760f3cda73d934d4d56b5 | fc90b5a3938850c61bdd83719a1d90270752c0bb | /web-server-test/tests/web-server/private/connection-manager-test.rkt | a5768e8347955c40dee14b8a3c604b0cc20ad878 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/web-server | cccdf9b26d7b908701d7d05568dc6ed3ae9e705b | e321f8425e539d22412d4f7763532b3f3a65c95e | refs/heads/master | 2023-08-21T18:55:50.892735 | 2023-07-11T02:53:24 | 2023-07-11T02:53:24 | 27,431,252 | 91 | 42 | NOASSERTION | 2023-09-02T15:19:40 | 2014-12-02T12:20:26 | Racket | UTF-8 | Racket | false | false | 2,839 | rkt | connection-manager-test.rkt | #lang racket/base
(require rackunit
web-server/private/connection-manager
web-server/private/timer)
(provide connection-manager-tests)
(module+ test
(require rackunit/text-ui)
(run-tests connection-manager-tests))
(define cm (start-connection-manager))
(define (make-connection&evt ttl ib ob [cust (make-custodian)] [close? #t])
(define conn
(new-connection cm ttl ib ob cust close?))
;; Modify the timer s.t. it fires an event when its action completes.
;; This means we don't have to rely on static sleeps to test this
;; code, although it does couple the tests to the implementation.
(define chan (make-channel))
(define timer (connection-timer conn))
(define action (timer-action timer))
(revise-timer!
timer
(max 0 (- (timer-deadline timer)
(current-inexact-milliseconds)))
(lambda ()
(dynamic-wind
void
action
(lambda ()
(channel-put chan 'done)))))
;; Ensure the connection object is retained for longer than the
;; timer, otherwise things will flake out.
(define evt (handle-evt chan (lambda _ conn)))
(values conn evt))
(define connection-manager-tests
(test-suite
"Connection Manager"
(test-case "Input closed"
(define ib (open-input-bytes #""))
(define ob (open-output-bytes))
(define-values (_conn evt)
(make-connection&evt 1 ib ob))
(sync/timeout 10 evt)
(check-true
(with-handlers ([exn? (lambda _ #t)])
(begin0 #f
(read ib)))))
(test-case "Output closed"
(define ib (open-input-bytes #""))
(define ob (open-output-bytes))
(define-values (_conn evt)
(make-connection&evt 1 ib ob))
(sync/timeout 10 evt)
(check-true
(with-handlers ([exn? (lambda _ #t)])
(begin0 #f
(write 1 ob)))))
(test-case "Early kill"
(define ib (open-input-bytes #""))
(define ob (open-output-bytes))
(define-values (conn evt)
(make-connection&evt 1 ib ob))
(kill-connection! conn)
(check-true
(and (with-handlers ([exn? (lambda _ #t)])
(begin0 #f
(read ib)))
(with-handlers ([exn? (lambda _ #t)])
(begin0 #f
(write 1 ob))))))
(test-case "Extend timer"
(define ib (open-input-bytes #""))
(define ob (open-output-bytes))
(define st (current-inexact-milliseconds))
(define-values (conn evt)
(make-connection&evt 1 ib ob))
(adjust-connection-timeout! conn 1)
(sync/timeout 20 evt)
(check-true
(and (with-handlers ([exn? (lambda _ #t)])
(begin0 #f
(read ib)))
(with-handlers ([exn? (lambda _ #t)])
(begin0 #f
(write 1 ob)))
(>= (- (current-inexact-milliseconds) st) 2000))))))
| false |
d003daf1bc79b6903d9f608d5abfeb0b53dce260 | d20c6b7f351b82141faa1578c8e744d358f4de9d | /racket/ejecucionnointeractiva.rkt | 65aa9c0d33d05bbb588c5da7e853e2fda346df45 | []
| no_license | programacionparaaprender/proyectosracket | 3fcc4ac49408782e3cecaded26d26ffb86fa2e9d | f018b1dcd3f651a6f52c62016ca0c0d69c013f20 | refs/heads/master | 2021-09-13T23:34:19.529235 | 2018-05-05T20:13:12 | 2018-05-05T20:13:12 | 132,279,140 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 79 | rkt | ejecucionnointeractiva.rkt | #lang racket
; extraer2 .rkt
( define ( extraer str)
( substring str 4 7)
) | false |
297ffb0ad51396b21d1cc9e4d3ced910eb6b490d | 14be9e4cde12392ebc202e69ae87bbbedd2fea64 | /CSC324/lecture/w8/control-flow.D.rkt | ed53fda39e9407a466d18947f271d2c8bd9fdb03 | [
"LicenseRef-scancode-unknown-license-reference",
"GLWTPL"
]
| permissive | zijuzhang/Courses | 948e9d0288a5f168b0d2dddfdf825b4ef4ef4e1e | 71ab333bf34d105a33860fc2857ddd8dfbc8de07 | refs/heads/master | 2022-01-23T13:31:58.695290 | 2019-08-07T03:13:09 | 2019-08-07T03:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,064 | rkt | control-flow.D.rkt | #lang racket #| Yield |#
#| Early resumable return.
E.g. Python's and Javascript's generators. |#
(require (only-in racket/control prompt abort call/comp))
(define-syntax-rule (let-continuation id ; Name this whole expression's continuation as ‘id’.
; Evaluate the body expressions in order.
; These are *not* part of the continuation.
; Use the last expression for the value of the whole expression.
body
...) ; The spot *after* is named ‘id’.
(call/comp (λ (id) body ...)))
#| Working up to ‘yield’. |#
; 1. Save a continuation to restart a function call “from the outside”.
(define K (void))
(define (f)
(prompt (displayln '(f a))
(let-continuation k
(set! K k))
; k is here ...
(displayln '(f b))
; ... to here
)
(displayln '(f d)))
(f) ; Prints (f a), (f b), (f d). ; not subsequent exprs in prompt is evaluated after let-continuation
(K) ; Prints (f b).
(K) ; Prints (f b).
; 2. Add the early return behaviour.
(define (g)
(prompt ; coming through here makes abort jump to ★
(displayln '(g a))
(let-continuation k
(set! K k)
(abort) ; jump to ★ and continue
)
; k is here ...
(displayln '(g b))
; ... to here, i.e. to ★, BUT then return to caller of k.
)
; ★
(displayln '(g d)))
(g) ; Prints (g a), (g d).
(K) ; Prints (g b).
(K) ; Prints (g b).
; Notice that abort and k represent non-overlapping control flows:
; • k makes a function out of a slice of the remaining computation,
; returning to whatever calls it later
; • abort jumps over that slice
; 3. Try two yields.
(define (h)
(prompt ; coming through here makes abort jump to ★
(displayln '(h a))
(let-continuation k1
(set! K k1)
(abort) ; jump to ★ and continue
)
; k1 is here ...
(displayln '(h b))
(let-continuation k2
(set! K k2)
(abort)) ; k1 only captures rest of exprs in prompt,
; so aborting here is in context of caller, so promp above does not capture it
; k2 is here ...
(displayln '(h c))
; ... to here ...,
; except calling k1 is interrupted by the abort causing an early return,
; and calling k2 gets to here and returns to its caller.
)
; ★
(displayln '(h d)))
(h) ; Prints (h a), (h d).
; Calling ‘K’ prints (h b), but aborts the rest of the program.
#;(K)
; Wouldn't get here:
#;(displayln 'again)
#;(K)
(prompt (K)) ; Prints (h b), the abort is caught by this prompt.
(K) ; Prints (h c).
; 3. Add the prompt protection to the saved continuation.
(define (j)
(prompt (displayln '(j a))
(let-continuation k
(set! K (λ () (prompt (k))))
(abort))
(displayln '(j b))
(let-continuation k
(set! K (λ () (prompt (k))))
(abort))
(displayln '(j c)))
(displayln '(j d)))
(j) ; Prints (j a), (h d).
; Let's save that point for later.
(define ja K)
(K) ; Prints (j b) [and also mutates ‘K’].
(K) ; Prints (j c).
(ja) ; Prints (j b) [and also mutates ‘K’].
; 4. Return the continuation directly to the caller, so that multiple yields,
; perhaps from different contexts, and multiple resumers, don't conflict.
(define (m)
(prompt (displayln '(m a))
(let-continuation k
(abort (λ () (prompt (k))))) ; returning a continuation instead of storing in a global state
(displayln '(m b))
(let-continuation k
(abort (λ () (prompt (k)))))
(displayln '(m c))
'(m d))
; Nothing outside the prompt, because we want aborts to come here
; and have their values be used as the return value
)
(define m′ (m)) ; Prints (m a).
(define m′′ (m′)) ; Prints (m b).
(m) ; Prints (m a), and the returned resumer function.
(m′′) ; Prints (m c), and m's return value '(m d).
(m′) ; Prints (m b), and the returned resumer function.
(m′′) ; Prints (m c), and m's return value '(m d).
; returning a lambda, that when invoked, prompts the captured continuation
(define (yield) (let-continuation k (abort (λ () (prompt (k))))))
(define (y)
(prompt (displayln '(y a))
(yield)
(displayln '(y b))
(yield)
(displayln '(y c))
'(y d)))
(define y′ (y)) ; Prints (y a).
(define y′′ (y′)) ; Prints (y b).
(y) ; Prints (y a), and the returned resumer procedure.
(y′′) ; Prints (y c), and y's return value '(y d).
(y′) ; Prints (y b), and the returned resumer procedure.
(y′′) ; Prints (y c), and y's return value '(y d).
| true |
88e52f5d43f9c63c3e2b27b24f77ab955cbd9937 | 5bbc152058cea0c50b84216be04650fa8837a94b | /benchmarks/synth/extra/funkytown/base/array-types.rkt | b122f7083e81e20f6f23d182c1815d5ce755244f | []
| no_license | nuprl/gradual-typing-performance | 2abd696cc90b05f19ee0432fb47ca7fab4b65808 | 35442b3221299a9cadba6810573007736b0d65d4 | refs/heads/master | 2021-01-18T15:10:01.739413 | 2018-12-15T18:44:28 | 2018-12-15T18:44:28 | 27,730,565 | 11 | 3 | null | 2018-12-01T13:54:08 | 2014-12-08T19:15:22 | Racket | UTF-8 | Racket | false | false | 1,047 | rkt | array-types.rkt | #lang typed/racket/base
(provide Indexes
In-Indexes
(struct-out Array)
(struct-out Settable-Array)
(struct-out Mutable-Array)
Weighted-Signal
Drum-Symbol
Pattern)
(define-type Indexes (Vectorof Integer))
(define-type In-Indexes Indexes)
;(define-type Indexes (Vectorof Index))
;(define-type In-Indexes (U (Vectorof Integer) Indexes))
(struct: (A) Array ([shape : Indexes]
[size : Integer]
[strict? : (Boxof Boolean)]
[strict! : (-> Void)]
[unsafe-proc : (Indexes -> A)]))
(struct: (A) Settable-Array Array ([set-proc : (Indexes A -> Void)]))
(struct: (A) Mutable-Array Settable-Array ([data : (Vectorof A)]))
;; From mix: A Weighted-Signal is a (List (Array Float) Real)
(define-type Weighted-Signal (List (Array Float) Real))
;; drum patterns are simply lists with either O (bass drum), X (snare) or
;; #f (pause)
(define-type Drum-Symbol (U 'O 'X #f))
(define-type Pattern (Listof Drum-Symbol))
| false |
c140a6085701df50578db61837394b73a7a8af4e | 613a68a69f184222406cba1b63ff7d7258cd6987 | /srpnt/apu.rkt | 8ecc5535732b758436845a98398a57b79ce5cec5 | []
| no_license | cwebber/srpnt | e0eab789c648a78b56fc9dc1abed418abe71a463 | c26e74ce524bb988d6643273c96f4e94406b1746 | refs/heads/master | 2023-08-11T10:01:58.470875 | 2020-04-28T19:29:19 | 2020-04-28T19:29:19 | 413,471,435 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 8,045 | rkt | apu.rkt | #lang racket/base
(require (only-in srpnt/speaker sample-rate.0)
racket/flonum
racket/fixnum
racket/performance-hint)
(define AUTHENTIC? #f)
;; The NES APU is synchronized with the clock of the CPU and all of
;; its sounds are specified by period (i.e. iterations of the CPU per
;; cycle) rather than frequency (cycles per second). We could do a
;; clock-accurate simulation and implement periods directly, but I
;; don't think it is worth it, so instead we convert the period into
;; the frequency.
(define CPU-FREQ-MHz 1.789773)
(define CPU-FREQ-Hz (fl* CPU-FREQ-MHz (fl* 1000.0 1000.0)))
(define max-pulse-period (fx- (expt 2 11) 1))
(begin-encourage-inline
(define (pulse-period->freq period)
(fl/ CPU-FREQ-Hz (fl* 16.0 (fl+ 1.0 (fx->fl period))))))
(define (pulse-freq->period freq)
(define pre-period (fl/ CPU-FREQ-Hz (fl* 16.0 freq)))
(define r (fl->fx (flround (fl- pre-period 1.0))))
(if AUTHENTIC?
(if (and (fx<= 0 r) (fx<= r max-pulse-period))
r
#f)
r))
;; The triangle wave actually runs twice as slow which makes its
;; sounds lower and makes it so a period twice as long gets the same
;; sound as the pulse.
(begin-encourage-inline
(define (triangle-period->freq period)
(fl/ (pulse-period->freq period) 2.0)))
(define (triangle-freq->period freq)
(pulse-freq->period (fl* 2.0 freq)))
;; In the case of triangle and pulse, I am slightly inaccurate by
;; allowing frequencies where the corresponding period is specially
;; coded to be ignored.
;; In the code below, we implements periods/frequencies as a % of a
;; single cycle, i.e. a value between [0,1]. We turn a frequency
;; (cycles per second) into a %-increment (cycles per sample) by
;; dividing by the sample-rate. Every time a sample is generated, we
;; increment and then remove any values that go above 1.0
(begin-encourage-inline
(define (cycle%-step % freq)
(define %step (fl/ freq sample-rate.0))
(define next% (fl+ % %step))
(fl- next% (flfloor next%))))
;; The pulse wave has only 4 duty cycles. A duty cycle is the
;; percentage of a cycle that the sound is active. Since we represent
;; the cycle has a percentage, this is very easy to implement.
(define DUTY-CYCLES (flvector 0.125 0.25 0.50 0.75))
(begin-encourage-inline
(define (duty-n->cycle n)
(flvector-ref DUTY-CYCLES n)))
(begin-encourage-inline
(define (pulse-wave duty-n period volume %)
(define freq (pulse-period->freq period))
(define duty-cycle (duty-n->cycle duty-n))
(define next-% (cycle%-step % freq))
(define out
(if (fl< next-% duty-cycle)
volume
0))
(values out next-%)))
(module+ test
(pulse-period->freq 0)
(pulse-period->freq (- (expt 2 11) 1)))
;; The triangle goes through a fixed amplitude pattern (it has no
;; volume control). We implement this by multiplying the cycle
;; percentage by the width of the pattern, thus getting the sample of
;; the pattern to look at.
(define TRIANGLE-PATTERN
(bytes 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))
(begin-encourage-inline
(define (triangle-wave on? period %)
(define freq (triangle-period->freq period))
(define next-% (cycle%-step % freq))
(define %-as-step (fl->fx (flround (fl* next-% 31.0))))
(define out
(if on?
(bytes-ref TRIANGLE-PATTERN %-as-step)
0))
(values out next-%)))
(module+ test
(triangle-period->freq 0)
(triangle-period->freq (- (expt 2 11) 1)))
;; The noise channel is a 15-bit linear feedback shift register that
;; is initialized to 1. Every cycle the PRNG steps. The period is a
;; 4-bit selector from a specific period table. Then, the noise runs
;; much faster than the other oscillators (8 times!). Next, the noise
;; has two modes that correspond to the length of the PRNG cycle.
(define NOISE-PERIODS
(vector 4 8 16 32 64 96 128 160 202 254 380 508 762 1016 2034 4068))
;; xxx i think i am doing this wrong, because when i get a period, i
;; restrict it to 4 bits, but i don't refer to this table, as i think
;; i should.
(begin-encourage-inline
(define (noise-period->freq period)
(fl* (pulse-period->freq period) 8.0)))
(begin-encourage-inline
(define (noise short? period volume register %)
(define freq (noise-period->freq period))
(define next-% (cycle%-step % freq))
(define next-register
(cond
;; A cycle has ended when the next-% is smaller than the current one
[(fl< next-% %)
(define (bit i) (bitwise-bit-field register i (fx+ i 1)))
(define other-bit (if short? 6 1))
(define feedback (bitwise-xor (bit 0) (bit other-bit)))
(define shifted-ref (arithmetic-shift register -1))
(define feedback-at-bit14 (arithmetic-shift feedback 14))
(bitwise-ior shifted-ref feedback-at-bit14)]
[else
register]))
(values
;; The volume is emitted when the register's 0 bit is 1
(fx* volume (fxmodulo next-register 2))
next-register
next-%)))
;; The NES DMC could play samples encoding in a complicated
;; way. Ultimately a 7-bit sound was produced. I just represent the
;; samples directly as 7-bit PCM data.
(define (read-sample/port base mult p)
(define-values (7bit-out 7bit-in) (make-pipe))
(local-require racket/port)
(let loop ()
(define c (read-byte p))
(cond
[(eof-object? c)
(void)]
[else
(define b (fxmin (fxmax 0 (fx+ base (fx* mult (fx- c 128)))) 127))
(write-byte b 7bit-in)
(loop)]))
(close-output-port 7bit-in)
(port->bytes 7bit-out))
(define (read-sample/path base mult p)
(read-sample/port base mult (open-input-file p)))
(define (read-sample/gzip base mult p)
(local-require file/gunzip)
(define-values (ungzipped gzipped) (make-pipe))
(gunzip-through-ports (open-input-file p) gzipped)
(close-output-port gzipped)
(read-sample/port base mult ungzipped))
;; The NES uses a strange non-linear mixing scheme. Each of the waves
;; produces a 4-bit value except for the DMC which produces a 7-bit
;; value. These are combined in analog in the NES, which would imply
;; using a very accurate (float) representation. However, I stick them
;; all into 7-bit audio after doing an accurate mixing. Furthermore, I
;; "optimize" this by storing it pre-computed in a bytes-array
(define (raw-p-mix p1 p2)
(fl/ 95.88
(fl+ (fl/ 8128.0
(fx->fl (fx+ p1 p2)))
100.0)))
(begin-encourage-inline
(define (p-mix-off p1 p2)
(fx+ (fx* 16 p1) p2)))
(define (make-p-mix-bytes)
(define v (make-bytes (* 16 16)))
(for* ([p1 (in-range 16)]
[p2 (in-range 16)])
(bytes-set! v (p-mix-off p1 p2)
(fl->fx (flround (fl* 127.0 (raw-p-mix p1 p2))))))
v)
(define p-mix-bs
(make-p-mix-bytes))
(begin-encourage-inline
(define (p-mix p1 p2)
(bytes-ref p-mix-bs (p-mix-off p1 p2))))
(define (raw-tnd-mix t n d)
(fl/ 159.79
(fl+ (fl/ 1.0
(fl+ (fl/ (fx->fl t) 8227.0)
(fl+ (fl/ (fx->fl n) 12241.0)
(fl/ (fx->fl d) 22638.0))))
100.0)))
(begin-encourage-inline
(define (tn-mix-off t n)
(fx+ (fx* (fx* 128 16) t) (fx* 128 n)))
(define (tnd-mix-off t n d)
(fx+ (tn-mix-off t n) d)))
(define (make-tnd-mix-bytes)
(define v (make-bytes (* 16 16 128)))
(for* ([t (in-range 16)]
[n (in-range 16)]
[d (in-range 128)])
(bytes-set! v
(tnd-mix-off t n d)
(fl->fx (flround (fl* 127.0 (raw-tnd-mix t n d))))))
v)
(define tnd-mix-bs
(make-tnd-mix-bytes))
(begin-encourage-inline
(define (tnd-mix t n d)
(bytes-ref tnd-mix-bs (tnd-mix-off t n d))))
(provide AUTHENTIC?
pulse-wave
triangle-wave
noise
p-mix
tnd-mix
pulse-freq->period
triangle-freq->period
read-sample/port
read-sample/path
read-sample/gzip)
| false |
61f65f3ac425a9c3db8bd3207ad61779f8804bbc | e1cf61b84282c33b7a245f4d483883cf77739b91 | /se3-bib/sim/simAppl/simDoorImpl-module.rkt | ed8cbaaed7e950c723fa0e1a103fb02dba4d9e6b | []
| no_license | timesqueezer/uni | c942718886f0366b240bb222c585ad7ca21afcd4 | 5f79a40b74240f2ff88faccf8beec7b1b3c28a7c | refs/heads/master | 2022-09-23T21:57:23.326315 | 2022-09-22T13:17:29 | 2022-09-22T13:17:29 | 71,152,113 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 3,692 | rkt | simDoorImpl-module.rkt | #lang swindle
#|
################################################################################
## ##
## This file is part of the se3-bib Racket module v3.0 ##
## Copyright by Leonie Dreschler-Fischer, 2010 ##
## Ported to Racket v6.2.1 by Benjamin Seppke, 2015 ##
## ##
################################################################################
|#
#|
=================================================================
Module "simDoorImpl-module"
The sim-door creates uniformly distributed events
by scheduling the first item of the queue idle-items,
idle actors are enqueued randomly.
This type of event source keeps the simulation process going
and has to be triggered initially to start the process.
auto provide:
classes: sim-door
generics: send-backstage
=================================================================
|#
(provide *the-sim-door* )
(require
se3-bib/sim/simBase/sim-base-package
se3-bib/sim/simAppl/simDoorClass-module
se3-bib/sim/simAppl/simCustomerClass-module)
(define *the-sim-door* #f)
(defmethod initialize :after
((door sim-door) initargs)
;(display "make-simdoor-after")
(setf! *the-sim-door* door))
#|
(add-method ; Variante 2, mit Tiny-Clos
initialize
(qualified-method
:after
((door sim-door) initargs)
(setf! *the-sim-door*
door)
(if (next-method?)
(call-next-method door initargs))))
|#
(defmethod arrival ((a <top>))
(display (list "unknown customer arriving." a "ignore ********." ))
)
(defmethod arrival ((a customer))
(let ((theMessage (string-append
"Enter: " (actor-name a))))
(set-ActorInTheDoor! *the-sim-door* a)
(set-event-message! *the-sim-door* theMessage)))
(defmethod close-the-door ((d sim-door))
"an actor is closing the door
after entering the scene."
(set-ActorInTheDoor! d ???))
(defmethod send-backstage ((a customer))
"make the actor a idle"
; recycle actor for the next appearance
(enqueue! *the-sim-door* a))
(defmethod departure ((a customer))
"an actor is leaving and idle again"
(let ((theMessage (string-append
"Departure: " (actor-name a))))
(set-event-message! *the-sim-door* theMessage)
(send-backstage a)))
(defmethod handle ((door sim-door))
"handle a door event, schedule a customer to appear"
(unless (empty-queue? door)
; dispatch the next customer from the queue
(let ((nextCustomer (dequeue! door)))
(display "handle door: next customer")
(display nextCustomer)
(arrival nextCustomer)
(schedule nextCustomer
(+ (now)
(random-exp :1/mu
(event-rate door)))))))
; schedule the next door event
;(next-exp-event door)); done by handle :after
(defmethod sim-init! ((door sim-door))
"tell the customers that the door is ready,
call the customers backstage"
(broadcast door
sim-init!
:sim-class customer))
(defmethod sim-start ((door sim-door))
"schedule the first door event"
(next-event door))
(defmethod door-empty? ((d sim-door))
"is there no actor entering just now?"
(not (slot-bound? d 'actorInTheDoor)))
#|
(print "loading: simDoorImpl-module")
(require
se3-bib/sim/simAppl/sim-application-package
se3-bib/sim/simAppl/simDoorClass-module
se3-bib/sim/simAppl/simDoorImpl-module)
(define d (make sim-door))
|#
| false |
d90010eec5c52ff334b9bc7d1f774d8d8b41e477 | d9c17bbf78ee71e76c3631b50409906c5e8fe3b0 | /lang/reader.rkt | 21df4c546e04333b8e84342324ee155ed4083e5a | []
| no_license | williamberman/stack-language | d11ef0c8f2cfcc9282d239d889754db559d5c996 | ad741faa85b7f79eaa16948b1618c27756e6ec92 | refs/heads/master | 2022-04-23T12:42:17.577222 | 2020-04-18T04:07:08 | 2020-04-18T04:07:08 | 256,666,172 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 443 | rkt | reader.rkt | #lang racket
(require "datum.rkt")
(provide (rename-out [x-read-syntax read-syntax])
(rename-out [x-read read]))
(define (x-read-syntax path port)
(define the-arguments (format-datums '~a (port->lines port)))
(define the-module `(module stacker-module stack-language/lang/expander (stack-program ,@the-arguments)))
(define the-syntax (datum->syntax #f the-module))
the-syntax)
(define (x-read in)
(x-read-syntax #f in))
| false |
a17590f6060306b5ce96f960f93a0eb8bff63204 | f44b1c2a88be94b4b8f849720c3cb1fcc7661e02 | /sudoku/sudoku.rkt | ae145e26c63937229c1490aa51d744465ec513b2 | []
| no_license | willghatch/cs6965 | 37a654a82af2c98504c06dd8e979d3d1d7a9f8b6 | 47481d7d96628fa27af045421d4c05e487637b79 | refs/heads/master | 2021-01-10T02:15:04.322723 | 2016-03-23T17:58:38 | 2016-03-23T17:59:25 | 53,610,756 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 12,883 | rkt | sudoku.rkt | #lang racket/base
(require racket/string)
(require racket/set)
(require racket/math)
(require lens)
(module+ test (require rackunit))
(provide (all-defined-out))
(struct sudoku-board
(M N rows)
#:transparent)
(define (empty-sudoku-board m n)
(let* ([mn (* m n)]
[empty-row (for/hash ([i (in-range mn)])
(values i (get-board-potential-values (sudoku-board m n #f))))]
;(values i 'blank))]
[rows (for/hash ([i (in-range mn)])
(values i empty-row))])
(sudoku-board m n rows)))
(define board-rows-lens (make-lens sudoku-board-rows
(λ (b r) (struct-copy sudoku-board b [rows r]))))
(define (board-to-cell-lens x y) (hash-ref-nested-lens y x))
(define (cell-lens x y) (lens-compose (board-to-cell-lens x y) board-rows-lens))
(define (get-sudoku-cell board x y)
(lens-view (cell-lens x y) board))
(define (set-sudoku-cell/no-update board x y v)
(lens-set (cell-lens x y) board v))
(define (get-m*n board)
(* (sudoku-board-M board) (sudoku-board-N board)))
(define (get-row-coordinates board _ y)
(for/list ([x (in-range (get-m*n board))])
(cons x y)))
(define (get-column-coordinates board x _)
(for/list ([y (in-range (get-m*n board))])
(cons x y)))
(define (get-peer-group-coordinates board x y)
;; m is the number of columns in a sub-board
;; n is the number of rows in a sub-board
(let* ([m (sudoku-board-M board)]
[n (sudoku-board-N board)]
;; start of peer group ranges
[px (* m (quotient x m))]
[py (* n (quotient y n))])
(for*/list ([cx (in-range px (+ px m))]
[cy (in-range py (+ py n))])
(cons cx cy))))
(define (get-cells board coord-func x y)
(for/list ([coord (coord-func board x y)])
(get-sudoku-cell board (car coord) (cdr coord))))
(define (get-peer-group-cells board x y)
(get-cells board get-peer-group-coordinates x y))
(define (get-row-cells board y)
(get-cells board get-row-coordinates #f y))
(define (get-column-cells board x)
(get-cells board get-column-coordinates x #f))
(define (update-potential-values board x y)
(define v (get-sudoku-cell board x y))
(define (xform setval)
(if (set? setval)
(set-remove setval v)
setval))
(if (set? v)
board
(for/fold ([b board])
([c (append (get-row-coordinates board x y)
(get-column-coordinates board x y)
(get-peer-group-coordinates board x y))])
(lens-transform (cell-lens (car c) (cdr c)) b xform))))
(define (un-set-single-values board)
;; when I have a set of 1 possible value, lift it out of the set and re-update
(define (un-set-rec board x y)
(let ([mn (get-m*n board)])
(cond [(x . >= . mn) (un-set-rec board 0 (add1 y))]
[(y . >= . mn) board]
[else
(let ([v (get-sudoku-cell board x y)])
(if (and (set? v) (equal? (set-count v) 1))
(set-sudoku-cell/update board x y (set-first v))
(un-set-rec board (add1 x) y)))])))
(un-set-rec board 0 0))
(define (post-set-update board x y)
(un-set-single-values (update-potential-values board x y)))
(define (set-sudoku-cell/update b x y v)
(post-set-update (set-sudoku-cell/no-update b x y v) x y))
(define set-sudoku-cell set-sudoku-cell/update)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (string->board s)
(define parts (string-split s))
(define l (length parts))
(when (< l 3) (error "invalid board"))
(let ([m (string->number (car parts))]
[n (string->number (cadr parts))]
[elems (list->vector (cddr parts))])
(when (< (vector-length elems) (* m n)) (error "invalid board"))
(for*/fold ([board (empty-sudoku-board m n)])
([x (in-range (* m n))]
[y (in-range (* m n))])
(let ([v (vector-ref elems (+ x (* m n y)))])
(if (or (equal? v "_") (equal? v "0"))
board
(set-sudoku-cell board x y (string->number v)))))))
(module+ test
(check-equal? (string->board "2 1\n1 _\n2 _")
(set-sudoku-cell (set-sudoku-cell (empty-sudoku-board 2 1) 0 1 2) 0 0 1)))
(define (board->string b #:extra-space? [extra-space? #t])
(let* ([m (sudoku-board-M b)]
[n (sudoku-board-N b)]
[mn (* m n)])
(string-append
(format "~a ~a~n" m n)
(if extra-space? "\n" "")
(apply
string-append
(for*/list ([y (in-range mn)]
[x (in-range mn)])
(string-append
(let ([cell (get-sudoku-cell b x y)])
(if (number? cell)
(number->string cell)
"_"))
(if (not (equal? x (sub1 mn))) " " "")
;; print an extra space between groups
(if (and extra-space?
(equal? (sub1 m) (modulo x m))
(not (equal? x (sub1 mn))))
" "
"")
(if (and (equal? x (sub1 mn)) (not (equal? y (sub1 mn))))
;; extra vertical space between groups
(if (and extra-space? (equal? (sub1 n) (modulo y n)))
"\n\n"
"\n")
"")
)))
"\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; validators
(define (valid-group? g)
;; a group will be a list of m*n values
(foldl (λ (v s) (cond [(not s) #f]
[(set? v) s]
;[(equal? v 'blank) s]
[(set-member? s v) #f]
[else (set-add s v)]))
(set)
g))
(module+ test
(check-not-false (valid-group? '(1 3 5)))
(check-false (valid-group? '(1 5 5))))
(define (valid-board-row? b y)
(valid-group? (get-row-cells b y)))
(define (valid-board-column? b x)
(valid-group? (get-column-cells b x)))
(define (valid-peer-group? b x y)
(valid-group? (get-peer-group-cells b x y)))
(define (valid-board? b)
(let* ([m (sudoku-board-M b)]
[n (sudoku-board-N b)]
[mn (* m n)])
(and
;; rows have unique cells
(for/and ([i (in-range mn)])
(valid-board-row? b i))
;; columns have unique cells
(for/and ([i (in-range mn)])
(valid-board-column? b i))
;; sub-boards have unique cells
;; m is the number of columns in a sub-board
;; n is the number of rows in a sub-board
(for/and ([i m])
(for/and ([j n])
(valid-peer-group? b (* j m) (* i n)))))))
(module+ test
(define bad-board-string #<<EOB
3 3
_ _ _ _ _ _ 1 _ _
_ _ _ 1 1 _ 3 _ _
_ _ _ _ 1 _ 2 _ _
_ _ _ _ _ _ 5 _ _
_ _ _ _ _ _ 6 _ _
1 2 3 4 5 6 7 8 9
_ _ _ _ _ _ 4 _ _
_ _ _ _ _ _ 8 _ _
_ _ _ _ _ _ 9 _ _
EOB
)
(define good-board-string #<<EOB
3 3
_ _ _ _ _ _ 1 _ _
_ _ _ _ _ _ 3 _ _
_ _ _ _ _ _ 2 _ _
_ _ _ _ _ _ 5 _ _
_ _ _ _ _ _ 6 _ _
1 2 3 4 5 6 7 8 9
_ _ _ _ _ _ 4 _ _
_ _ _ _ _ _ 8 _ _
_ _ _ _ _ _ 9 _ _
EOB
)
(define bad-board (string->board bad-board-string))
(define good-board (string->board good-board-string))
(check-equal? bad-board-string (board->string bad-board #:extra-space? #t))
(check-false (valid-board-row? bad-board 1))
(check-false (valid-board-column? bad-board 4))
(check-false (valid-peer-group? bad-board 3 0))
(check-not-false (valid-board-row? bad-board 5))
(check-not-false (valid-board-column? bad-board 6))
(check-not-false (valid-peer-group? bad-board 6 5))
(check-false (valid-board? bad-board))
(check-not-false (valid-board? good-board))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (get-board-potential-values b)
(list->set (in-range 1 (add1 (* (sudoku-board-M b) (sudoku-board-N b))))))
(define (get-cell-potential-values b x y)
(let ([v (get-sudoku-cell b x y)])
(if (set? v) v (set v))))
(define (get-cell-potential-values/old b x y)
(let ([rcs (get-row-cells b y)]
[ccs (get-column-cells b x)]
[pcs (get-peer-group-cells b x y)])
(set-subtract (get-board-potential-values b)
(list->set rcs)
(list->set ccs)
(list->set pcs))))
(module+ test
(check-equal? (get-cell-potential-values good-board 8 3)
(set 1 2 3 4)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (solve-rec/sort b n-max solutions-so-far)
(if (>= (set-count solutions-so-far) n-max)
solutions-so-far
(let* ([m (sudoku-board-M b)]
[n (sudoku-board-N b)]
[mn (* m n)]
[coords (for*/list ([x (in-range mn)]
[y (in-range mn)])
(cons x y))])
(let-values ([(mincoord npossible)
(for/fold ([mincoord (cons 0 0)]
[minv +inf.0])
([c coords])
(let ([v (if (number? (get-sudoku-cell b (car c) (cdr c)))
+inf.0
(set-count (get-cell-potential-values b (car c) (cdr c))))])
(if (> minv v)
(values c v)
(values mincoord minv))))])
(if (infinite? npossible)
(set-add solutions-so-far b)
(for/fold ([solutions solutions-so-far])
([p (get-cell-potential-values b (car mincoord) (cdr mincoord))])
(solve-rec/sort (set-sudoku-cell b (car mincoord) (cdr mincoord) p)
n-max
solutions)))
))))
(define (solve-rec b x y n-max solutions-so-far)
(let* ([m (sudoku-board-M b)]
[n (sudoku-board-N b)]
[mn (* m n)]
[cell (if (and (< x mn) (< y mn))
(get-sudoku-cell b x y)
'out-of-bounds)])
(cond [(<= n-max (set-count solutions-so-far)) solutions-so-far]
[(>= x mn) (solve-rec b 0 (add1 y) n-max solutions-so-far)]
[(>= y mn) (set-add solutions-so-far b)]
[(number? cell) (solve-rec b (add1 x) y n-max solutions-so-far)]
;[(equal? cell 'blank)
[(set? cell)
(for/fold ([solutions solutions-so-far])
([p (get-cell-potential-values b x y)])
(solve-rec (set-sudoku-cell b x y p) (add1 x) y n-max solutions))
])))
(define (solve board n-solutions)
;; returns a set of solutions
(if (valid-board? board)
(solve-rec/sort board n-solutions (set))
(set)))
(define (solve-unique board)
(let ((s (solve board 2)))
(cond [(set-empty? s) #f]
[(> (set-count s) 1) 'multiple]
[else (set-first s)])))
(module+ test
(check-false (solve-unique bad-board))
(define test-1-string #<<EOB
3 3
_ 5 _ _ 6 _ _ _ 1
_ _ 4 8 _ _ _ 7 _
8 _ _ _ _ _ _ 5 2
2 _ _ _ 5 7 _ 3 _
_ _ _ _ _ _ _ _ _
_ 3 _ 6 9 _ _ _ 5
7 9 _ _ _ _ _ _ 8
_ 1 _ _ _ 6 5 _ _
5 _ _ _ 3 _ _ 6 _
EOB
)
(define test-1-solution-string #<<EOB
3 3
9 5 3 7 6 2 8 4 1
6 2 4 8 1 5 9 7 3
8 7 1 3 4 9 6 5 2
2 8 9 4 5 7 1 3 6
1 6 5 2 8 3 4 9 7
4 3 7 6 9 1 2 8 5
7 9 6 5 2 4 3 1 8
3 1 8 9 7 6 5 2 4
5 4 2 1 3 8 7 6 9
EOB
)
(define test-1 (string->board test-1-string))
(check-equal? (solve-unique test-1) (string->board test-1-solution-string))
(check-equal? (set-count (solve (string->board "1 2 \n _ _ \n _ _") +inf.f))
2)
)
(define (generate-board m n [fuel 500])
(define mn (* m n))
(define (rec b b/no-update fuel)
(if (< fuel 0)
#f
(let* ([x (random mn)]
[y (random mn)]
[v-possible (get-cell-potential-values b x y)]
[v (if (set-empty? v-possible)
;; if nothing is possible, just choose 1 and it will later show its invalid, and use a fuel
1
(list-ref (set->list v-possible) (random (set-count v-possible))))]
[nb/no-update (set-sudoku-cell/no-update b/no-update x y v)]
[nb (set-sudoku-cell b x y v)]
[valid? (valid-board? nb)]
[solution (and valid? (solve-unique nb))])
(cond
;; if there is a unique solution, use the current board
[(sudoku-board? solution) nb/no-update]
;; if there is no solution, try going forward with the last good board
[(not solution) (rec b b/no-update (- fuel 1))]
;; there are multiple solutions still, so let's prune some more
[else (rec nb nb/no-update fuel)]))))
(or (let ([b (empty-sudoku-board m n)])
(rec b b fuel))
(generate-board m n fuel)))
(module+ main
(let ([b (generate-board 3 3)])
(printf "~a~n" (board->string b))
(printf "~a~n" (board->string (solve-unique (string->board (board->string b)))))
))
| false |
fa9d424c9bbe99d05fec8b316184a6d57d8813db | eb5af9bec411095a0afc81a54e2124fedc1d645b | /least-squares/function-struct/multi-var-taylor-ish.rkt | a5ec238f89f83efdc9e1c0d82463771c8cc86e9a | [
"MIT"
]
| permissive | AlexKnauth/least-squares | e3a4d1df10ad5fc6250c50e3ec8f6c64de89aadb | a27b1598e13a124572d5520db3f29a95f7b8c398 | refs/heads/master | 2022-01-10T06:31:31.772261 | 2022-01-07T15:03:42 | 2022-01-07T15:03:42 | 29,675,867 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,133 | rkt | multi-var-taylor-ish.rkt | #lang racket/base
(provide multi-var-taylor-ish
zero-f
const
mx+b
ax^2+bx+c
ax+by+c
ax+by+cz+d
)
(require racket/match
racket/splicing
math/array
math/number-theory
"../utils.rkt"
(for-syntax racket/base
syntax/parse
))
(module+ test (require rackunit))
(struct super-multi-var-taylor-ish (lst) #:transparent)
(define (make-multi-var-taylor-ish lst)
(define d
(match lst
[(list) 0]
[(list _) 0]
[(list _ (array: #[a ...]) _ ...) (length a)]))
(for ([arr (in-list lst)]
[n (in-naturals)])
(define arr.shape (array-shape arr))
(define expected-shape (vector->immutable-vector (make-vector n d)))
(unless (equal? arr.shape expected-shape)
(error 'multi-var-taylor-ish "wrong shape for array\n shape: ~v\n expected: ~v"
arr.shape expected-shape)))
(define constructor (get-multi-var-taylor-ish-constructor d))
(constructor lst))
(splicing-local
[;; sub-constructors : (HashTable Natural [(Listof (Arrayof Real)) -> Multi-Var-Taylor-Ish])
(define sub-constructors (make-hash))
;; multi-var-taylor-ish : [Multi-Var-Taylor-Ish Real * -> Real]
;; will be passed as the procedure argument to prop:procedure
(define (multi-var-taylor-ish f . args)
(match-define (super-multi-var-taylor-ish lst) f)
(define d (length args))
(for/sum ([arr (in-list lst)]
[n (in-naturals)])
(define arr.shape (array-shape arr))
(define n! (factorial n))
(* (/ n!)
(for/sum ([p (in-array arr)]
[is (in-array-indexes arr.shape)])
(* p (for/product ([i (in-vector is)])
(list-ref args i)))))))
;; proc : [My-F Real * -> Real]
(define proc multi-var-taylor-ish)]
(define (get-multi-var-taylor-ish-constructor d)
(hash-ref! sub-constructors d
(lambda ()
(struct multi-var-taylor-ish super-multi-var-taylor-ish () #:transparent
#:property prop:procedure (procedure-reduce-arity proc (add1 d)))
multi-var-taylor-ish))))
(define-match-expander multi-var-taylor-ish
(syntax-parser
[(multi-var-taylor-ish lst-pat:expr)
#'(super-multi-var-taylor-ish lst-pat)])
(make-var-like/pat #'make-multi-var-taylor-ish (~or :id (:id :expr))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define zero-f
(multi-var-taylor-ish '()))
(define (make-const c)
(multi-var-taylor-ish
(list (array c))))
(define-match-expander const
(syntax-parser
[(const c:expr)
#'(multi-var-taylor-ish
(list (array: c)))])
(make-var-like/pat #'make-const (~or :id (:id :expr))))
(define (make-mx+b m b)
(multi-var-taylor-ish
(list (array b)
(array #[m]))))
(define-match-expander mx+b
(syntax-parser
[(mx+b m:expr b:expr)
#'(multi-var-taylor-ish
(list (array: b)
(array: #[m])))])
(make-var-like/pat #'make-mx+b (~or :id (:id :expr :expr))))
(define (make-ax^2+bx+c a b c)
(multi-var-taylor-ish
(list (array c)
(array #[b])
(array #[#[(* 2 a)]]))))
(define-match-expander ax^2+bx+c
(syntax-parser
[(ax^2+bx+c a:expr b:expr c:expr)
#'(multi-var-taylor-ish
(list (array: c)
(array: #[b])
(array: #[#[(app (λ (x) (* 1/2 x)) a)]])))])
(make-var-like/pat #'make-ax^2+bx+c (~or :id (:id :expr :expr :expr))))
(define (make-ax+by+c a b c)
(multi-var-taylor-ish
(list (array c)
(array #[a b]))))
(define (make-ax+by+cz+d a b c d)
(multi-var-taylor-ish
(list (array d)
(array #[a b c]))))
(define-match-expander ax+by+c
(syntax-parser [(ax+by+c a:expr b:expr c:expr)
#'(multi-var-taylor-ish
(list (array: c)
(array: #[a b])))])
(make-var-like/pat #'make-ax+by+c (~or :id (:id :expr :expr :expr))))
(define-match-expander ax+by+cz+d
(syntax-parser [(ax+by+cz+d a:expr b:expr c:expr d:expr)
#'(multi-var-taylor-ish
(list (array: d)
(array: #[a b c])))])
(make-var-like/pat #'make-ax+by+cz+d (~or :id (:id :expr :expr :expr :expr))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(module+ test
(define-syntax (chk stx)
(define-syntax-class cls
[pattern [a:expr e:expr] #:with norm (syntax/loc this-syntax (check-equal? a e))])
(syntax-parse stx
[(chk :cls ...) #'(begin norm ...)]))
(test-case "multi-var-taylor-ish"
(test-case "f() = 1"
(define f
(multi-var-taylor-ish
(list (array 1))))
(check-equal? (const 1) f)
(check-equal? (procedure-arity f) 0)
(check-equal? (f) 1))
(test-case "f(x) = 1 + 2*x"
(define (g x) (+ 1 (* 2 x)))
(define f
(multi-var-taylor-ish
(list (array 1)
(array #[2]))))
(check-equal? (mx+b 2 1) f)
(check-equal? (procedure-arity f) 1)
(check-equal? (f 0) 1)
(check-equal? (f 1) 3)
(check-equal? (f 2) 5)
(for ([i (in-range 100)])
(define x (exact-random/sgn 100))
(check-equal? (f x) (g x))))
(test-case "f(x) = 1 + 2*x + 3*x^2"
(define (g x) (+ 1 (* 2 x) (* 3 (expt x 2))))
(define f
(multi-var-taylor-ish
(list (array 1)
(array #[2])
(array #[#[6]]))))
(check-equal? (ax^2+bx+c 3 2 1) f)
(check-equal? (procedure-arity f) 1)
(check-equal? (f 0) 1)
(check-equal? (f 1) 6)
(check-equal? (f 2) 17)
(for ([i (in-range 100)])
(define x (exact-random/sgn 100))
(check-equal? (f x) (g x))))
(test-case "f(x,y) = 1 + 2*x + 3*y"
(define (g x y) (+ 1 (* 2 x) (* 3 y)))
(define f
(multi-var-taylor-ish
(list (array 1)
(array #[2 3]))))
(check-equal? (ax+by+c 2 3 1) f)
(check-equal? (procedure-arity f) 2)
(chk [(f 0 0) 1] [(f 1 0) 3] [(f 2 0) 5]
[(f 0 1) 4] [(f 1 1) 6] [(f 2 1) 8]
[(f 0 2) 7] [(f 1 2) 9] [(f 2 2) 11])
(for ([i (in-range 100)])
(define x (exact-random/sgn 100))
(define y (exact-random/sgn 100))
(check-equal? (f x y) (g x y))))
(test-case "f(x,y) = 1 + 2*x + 3*y + 4*x^2 + 5*x*y + 6*y^2"
(define (g x y) (+ 1 (* 2 x) (* 3 y) (* 4 (expt x 2)) (* 5 x y) (* 6 (expt y 2))))
(define f
(multi-var-taylor-ish
(list (array 1)
(array #[2 3])
(array #[#[8 5] #[5 12]]))))
(check-equal? (procedure-arity f) 2)
(chk [(f 0 0) 1] [(f 1 0) 7] [(f 2 0) 21]
[(f 0 1) 10] [(f 1 1) 21] [(f 2 1) 40]
[(f 0 2) 31] [(f 1 2) 47] [(f 2 2) 71])
(for ([i (in-range 100)])
(define x (exact-random/sgn 100))
(define y (exact-random/sgn 100))
(check-equal? (f x y) (g x y))))
))
| true |
07191b58793bad069ea1049149f4d9514edb02ba | 67f496ff081faaa375c5000a58dd2c69d8aeec5f | /koyo-lib/koyo/config.rkt | c5706a6a5cf9a6b589797569c272003de0370490 | [
"BSD-3-Clause"
]
| permissive | Bogdanp/koyo | e99143dd4ee918568ed5b5b199157cd4f87f685f | a4dc1455fb1e62984e5d52635176a1464b8753d8 | refs/heads/master | 2023-08-18T07:06:59.433041 | 2023-08-12T09:24:30 | 2023-08-12T09:24:30 | 189,833,202 | 127 | 24 | null | 2023-03-12T10:24:31 | 2019-06-02T10:32:01 | Racket | UTF-8 | Racket | false | false | 991 | rkt | config.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse)
racket/contract
racket/string)
(provide
current-option-name-prefix
define-option)
(define/contract current-option-name-prefix
(parameter/c non-empty-string?)
(make-parameter "KOYO"))
(define (make-option-name s)
(string-append (current-option-name-prefix) "_"
(string-replace (string-upcase (symbol->string s)) "-" "_")))
(define-syntax (define-option stx)
(syntax-parse stx
[(_ name:id
e:expr ...)
#'(define-option name #:default #f e ...)]
[(_ name:id
#:default default:expr
e:expr ...)
(with-syntax ([(body ...) (if (null? (syntax-e #'(e ...)))
#'(name)
#'(e ...))])
#'(begin
(define name
(let ([name (or (getenv (make-option-name 'name)) default)])
body ...))
(provide name)))]))
| true |
8639adb15c25b03db8f12e87ce5695385e1aa1c0 | ba43dfc778dd761ede87f5a29b2b26a2a7817ac4 | /racket/lego-gears.rkt | 76a1327a5b348ef05448a7e15cc2be5ac5eff600 | [
"MIT"
]
| permissive | 2sb18/lego-gears | 1075a01c4c0e77f64e752d1241c192377a55f9a5 | de0db139cd05ee96562d386c8e49cbdc8f242f35 | HEAD | 2016-08-07T17:08:30.946256 | 2014-08-26T01:48:03 | 2014-08-26T01:48:03 | 17,008,714 | 10 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 11,305 | rkt | lego-gears.rkt | #lang racket
(require "gear-ratios.rkt")
(provide solve-gear-ratio
get-best-solutions)
; define-memoized macro copied from John-Paul Verkamp's blog with his permission
; http://blog.jverkamp.com/2012/10/20/memoization-in-racket/
(define-syntax define-memoized
(syntax-rules ()
[(_ (f args ...) bodies ...)
(define f
; store the cache as a hash of args => result
(let ([results (make-hash)])
; need to do this to capture both the names and the values
(lambda (args ...)
((lambda vals
; if we haven't calculated it before, do so now
(when (not (hash-has-key? results vals))
(hash-set! results vals (begin bodies ...)))
; return the cached result
(hash-ref results vals))
args ...))))]))
; future improvement: have a procedure that removes self-intersections
; future improvement: make the limit either horizontal or vertical
; first let's just try to solve going from one gear type to another
;
; our next gear can go either up or down, but the across always has to be positive
; this should return a list of solutions. each solution should be a list of gear combos.
; so here would be one solution
; ( (40 16 1/3 7/2) (16
; this should return a list where each element is like
; (36 40 1 9/2)
; and there's the down move too
; (36 40 -1 9/2)
(define-memoized
(get-possible-combinations gear include-down? two-gears-on-one-axle-allowed?)
(let ((admissable-combinations
(if two-gears-on-one-axle-allowed?
(append gear-combinations
(filter-map (lambda (combination)
(if (= (first combination) (second combination))
#f
(list (second combination)
(first combination)
(third combination))))
gear-combinations))
(map (lambda (combination)
(if (= (first combination) gear)
combination
(list (second combination) (first combination) (third combination))))
(filter (lambda (x)
(or (= gear (car x))
(= gear (cadr x))))
gear-combinations)))))
; this gives a list of possibilities, each possibility being a list
(define (expand-possibilities combination)
(let ((positive-possibilities (map (lambda (up-and-across)
(list (car combination)
(cadr combination)
(car up-and-across)
(cadr up-and-across)))
(caddr combination))))
(let ((negative-possibilities (map (lambda (x)
(list (car x) (cadr x) (- (caddr x)) (cadddr x)))
(filter (lambda (x) (not (= 0 (caddr x))))
positive-possibilities))))
(if include-down?
(append positive-possibilities negative-possibilities)
positive-possibilities))))
(apply append (map expand-possibilities admissable-combinations))))
; solve-gear-ratio returns false if it doesn't work
; solve-gear-ratio returns a list of solutions if it does work
; maybe call combination head-combo and tail-combos and list-of-tail-combos
; head looks like '(8 8 0 1)
; tails is a list of solutions. is a list of combos
; so tails looks like '(((1 2 3 4) (1 2 3 2)) ((1 2 1 2) (2 3 4 3)))
;
(define (combine-head-and-tails head-combo tail-solutions)
(cond ((not tail-solutions) #f) ; if tail-solutions is false, that means that no solution could be found, propogate the #f
((= 0 (length tail-solutions)) (list (list head-combo)))
(else (filter-map (lambda (tail-combo)
(cons head-combo tail-combo))
tail-solutions))))
; the objectives are the points, and this procedure gives us the piecewise straight line distances
; from point to point
; this is the real physical distance
(define (get-total-distance list-of-objectives)
(if (null? list-of-objectives)
0
(+ (sqrt (+ (expt (* up-unit-in-mm (caar list-of-objectives)) 2)
(expt (* across-unit-in-mm (cadar list-of-objectives)) 2)))
(get-total-distance (cdr list-of-objectives)))))
(define (subtract-combo-from-list-of-objectives combination list-of-objectives)
(let ((ratio-left (if (= 3 (length (car list-of-objectives)))
(caddar list-of-objectives)
'())))
(cons
(append
(list (- (caar list-of-objectives) (third combination))
(- (cadar list-of-objectives) (fourth combination)))
(if (null? ratio-left)
'()
(list (- (* ratio-left (/ (first combination) (second combination)))))))
(cdr list-of-objectives))))
; an objective looks like '(up across ratio)
; an objective can also look like this '(up across) if we don't care about what the ratio is
; can we put multiple gears on one axle?
; this checks to make sure we're getting closer to our objective
(define (solve-gear-ratio list-of-objectives include-down? two-gears-on-one-axle-allowed?)
(define (get-solutions list-of-objectives-left previous-gear)
(let ((solutions
(apply append
(filter-map
(lambda (combination)
; this gives back a list of solutions
(combine-head-and-tails
combination
(let ((new-list-of-objectives-left (subtract-combo-from-list-of-objectives
combination list-of-objectives-left)))
; this is the part that makes sure we're getting closer
; to our objective
; we have to get at least 1mm closer to our goal
(if (< (+ 1 (get-total-distance new-list-of-objectives-left))
(get-total-distance list-of-objectives-left))
(iter new-list-of-objectives-left (second combination))
#f))))
(get-possible-combinations previous-gear include-down? two-gears-on-one-axle-allowed?)))))
(if (= 0 (length solutions))
#f
solutions)))
; returns a list of solutions
(define-memoized (iter list-of-objectives-left previous-gear)
(let ((up-left (caar list-of-objectives-left))
(across-left (cadar list-of-objectives-left))
(ratio-left (if (= 3 (length (car list-of-objectives-left)))
(caddar list-of-objectives-left)
'())))
(cond ((< across-left 0) #f)
((= across-left 0)
(if (or (and (= 3 (length (car list-of-objectives-left))) (= up-left 0) (= ratio-left 1))
(and (= 2 (length (car list-of-objectives-left))) (= up-left 0)))
(if (= 1 (length list-of-objectives-left))
'()
(get-solutions (cdr list-of-objectives-left) previous-gear))
#f))
(else
(get-solutions list-of-objectives-left previous-gear)))))
(apply append
(filter-map
(lambda (starting-gear)
(iter list-of-objectives starting-gear))
(if two-gears-on-one-axle-allowed?
'(0) ; if two-gears-on-one-axle-allowed? is true, then we don't have to go through each starting gear
gear-sizes))))
(define (get-shortest-solutions solutions)
(if (= 0 (length solutions))
'()
; x is the new guy, y is the length of the current champion
(let ((shortest-length (foldr (lambda (x y) (if (< (length x) y) (length x) y))
(length (car solutions))
solutions)))
(filter (lambda (x) (= shortest-length (length x))) solutions))))
(define (ratio-of-solution solution)
(if (null? solution)
1
(- (* (/ (cadar solution) (caar solution))
(ratio-of-solution (cdr solution))))))
; if big-ratio is true, that means we want a lot torque,
; if big-ratio is false, that means we want a lot of speed
(define (get-solutions-with-best-ratio solutions negative-ratio? big-ratio?)
; let's convert all ratios into big positives
(define (converter ratio)
(let ((negatized (if negative-ratio? (- ratio) ratio)))
(if big-ratio? negatized (/ 1 negatized))))
(let ((best-ratio (foldr (lambda (x y) (if (> (converter (ratio-of-solution x)) y)
(converter (ratio-of-solution x))
y))
-10000000
solutions)))
(filter (lambda (x) (= best-ratio (converter (ratio-of-solution x)))) solutions)))
(define (is-element-in-list? element lst)
(cond ((null? lst) #f)
((= element (car lst)) #t)
(else (is-element-in-list? element (cdr lst)))))
(define (solution-with-preferred-gears? solution preferred-gears)
(cond ((null? solution) #t)
((or (not (is-element-in-list? (caar solution) preferred-gears))
(not (is-element-in-list? (cadar solution) preferred-gears)))
#f)
(else (solution-with-preferred-gears? (cdr solution) preferred-gears))))
(define (get-solutions-with-preferred-gears solutions list-of-preferred-gears)
(filter (lambda (x)
(solution-with-preferred-gears? x list-of-preferred-gears))
solutions))
; "best" is pretty subjective. Here's the order in which I define best
; solutions.
; 1. shortest solutions using '(24 20 16 12)
; 2. shortest solutions using '(24 20 16 12 8)
; 3. shortest solutions using '(40 36 24 20 16 12 8)
; best does not include down movements
(define (get-best-solutions list-of-objectives)
(let ((solutions (solve-gear-ratio list-of-objectives #f #f)))
(let ((awesome-solutions (get-shortest-solutions
(get-solutions-with-preferred-gears
solutions '(24 20 16 12))))
(good-solutions (get-shortest-solutions
(get-solutions-with-preferred-gears
solutions '(24 20 16 12 8))))
(alright-solutions (get-shortest-solutions
(get-solutions-with-preferred-gears
solutions '(40 36 24 20 16 12 8)))))
(cond ((< 0 (length awesome-solutions)) awesome-solutions)
((< 0 (length good-solutions)) good-solutions)
(else alright-solutions)))))
| true |
a73988aff75d1e11e0ab056bbddb831bab9fb81e | bb14dc54eb1c44a6b17b352e7dcca5e26a195876 | /tests/std_lib/std/defined1.rkt | 38121646675b1250fb574bc97b99d71761cf4a72 | [
"Apache-2.0"
]
| permissive | mtdol/cm | e1d96ac42377bbd833fcde4be7ff69f8a25fdd78 | 4dbec0bf18d41fda1df2488453077ec8c3f5e3cf | refs/heads/main | 2023-06-22T20:14:27.730795 | 2021-07-18T05:01:56 | 2021-07-18T05:01:56 | 341,087,770 | 0 | 0 | null | 2021-04-24T02:03:55 | 2021-02-22T05:17:00 | Racket | UTF-8 | Racket | false | false | 2,088 | rkt | defined1.rkt | #lang racket
(require cm/tests/test-utils rackunit)
(run-stat-silent "#:lang cm")
;;
;; defined?
;;
(run-silent "def x1 := 3")
(run-silent "static x2 := 4")
(check-equal? (run "defined? \"x1\" :>current_module")
val-true)
(check-equal? (run "defined? \"x2\" :>current_module")
val-true)
(check-equal? (run "defined? \"x3\" :>current_module")
val-false)
(check-equal? (run "let x3 := 3 in defined? \"x3\" :>current_module")
val-true)
(check-equal? (run "param x3 := 3 in defined? \"x3\" :>current_module")
val-true)
(check-equal? (run "param x1 := 3 in defined? \"x1\" :>current_module")
val-true)
;;
;; global.defined?
;;
(check-equal? (run "global.defined? \"x1\" :>current_module")
val-true)
(check-equal? (run "global.defined? \"x2\" :>current_module")
val-true)
(check-equal? (run "global.defined? \"x3\" :>current_module")
val-false)
(check-equal? (run "let x3 := 3 in global.defined? \"x3\" :>current_module")
val-false)
(check-equal? (run "param x3 := 3 in global.defined? \"x3\" :>current_module")
val-false)
(check-equal? (run "param x1 := 3 in global.defined? \"x1\" :>current_module")
val-true)
;;
;; local.defined?
;;
(check-equal? (run "local.defined? \"x1\"")
val-false)
(check-equal? (run "local.defined? \"x2\"")
val-false)
(check-equal? (run "local.defined? \"x3\"")
val-false)
(check-equal? (run "let x3 := 3 in local.defined? \"x3\"")
val-true)
(check-equal? (run "param x3 := 3 in local.defined? \"x3\"")
val-false)
(check-equal? (run "param x1 := 3 in local.defined? \"x1\"")
val-false)
(check-equal? (run "let x1 := 3 in local.defined? \"x1\"")
val-true)
;;
;; params.defined?
;;
(check-equal? (run "params.defined? \"x1\"")
val-false)
(check-equal? (run "params.defined? \"x2\"")
val-false)
(check-equal? (run "params.defined? \"x3\"")
val-false)
(check-equal? (run "let x3 := 3 in params.defined? \"x3\"")
val-false)
(check-equal? (run "param x3 := 3 in params.defined? \"x3\"")
val-true)
(check-equal? (run "param x1 := 3 in params.defined? \"x1\"")
val-true)
(check-equal? (run "let x1 := 3 in params.defined? \"x1\"")
val-false)
| false |
03226eb61ea9c85c4a1182bb5853dc5c5fe501db | 91dc09382f6cc58925f46622212d36ab37e7e4ae | /pages/blog/post-2020-08-13.rkt | 34bc871a6e4cec8a6f2b8286273b8c0c6eee294e | []
| no_license | srfoster/codespells.org | 53b4e62afb2131ed7198f76d02e023e977547bdc | fe6c14a70bf3a88579bfc675403e6a4605d6473c | refs/heads/master | 2023-08-16T20:40:03.931174 | 2021-05-24T21:29:26 | 2021-05-24T21:29:26 | 285,627,595 | 3 | 1 | null | 2021-09-11T23:53:09 | 2020-08-06T17:10:42 | Racket | UTF-8 | Racket | false | false | 1,716 | rkt | post-2020-08-13.rkt | #lang at-exp racket
;TODO: make this a legit package.
(require "../../lang.rkt")
(require "./lang.rkt")
(require codespells-runes)
(define-post
2020-08-13
"Voxels and Runes!"
@div{
All @(authored-works) can have voxels and novel programming languages; the @(authoring-tools) make this easy.
}
@div{
@p{I've written a lot of long posts recently. Let's do a short one.
These three quick videos show the main character in @(the-seeker) traversing
the voxel world and deforming it with spells:}
@(image-grid
(cons
video:build-sphere-demo3.webm
"Just a standin' and a jumpin'")
(cons
video:build-sphere-demo.webm
"Just a castin' and a runnin'")
(cons
video:build-sphere-demo2.webm
"Just a rollin' and a rollin'"))
@p{Things to note:}
@ul{
@li{Worlds are huge. I'm not faking that it stretches out as far as the eye can see.}
@li{The 3rd-person avatar has jump and roll capabilities.}
@li{Voxels are what allow for the cliffs and overhangs you see.}
@li{The spell being cast adds a sphere to the voxel terrain and is written in a programming language I'm designing to fit with the lore in @(the-seeker).}
}
@p{Here's the source code for the spell shown in the videos.}
@(div
style: (properties
width: "100%"
height: 120
position: "relative")
(typeset-runes the-seeker-lang
(build small)))
@p{Stay tuned for details about this "rune-based programming paradigm" and how the @(authoring-tools) will help authors add such languages to their own @(authored-works), creating a polyglottic multiverse within the @(canon).}
@p{- Stephen R. Foster}
@(logo 200)
})
| false |
bcab3173c36917754842ac339752310b8f915f8a | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/100-doors-3.rkt | eeb07dc491ae2895b41610206d11103de87ce5e9 | []
| no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867677 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 539 | rkt | 100-doors-3.rkt | #lang slideshow
(define-syntax-rule (vector-neg! vec pos)
(vector-set! vec pos (not (vector-ref vec pos))))
(define (make-doors)
(define doors (make-vector 100 #f))
(for* ([i 100] [j (in-range i 100 (add1 i))]) (vector-neg! doors j))
doors)
(displayln (list->string (for/list ([d (make-doors)]) (if d #\o #\-))))
(define closed-door (inset (filled-rectangle 4 20) 2))
(define open-door (inset (rectangle 4 20) 2))
(for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)])
(hc-append doors (if open? open-door closed-door)))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.